import {
	Alert,
	AlertIcon,
	Box,
	Button,
	ButtonGroup,
	Container,
	Flex,
	Heading,
	Stack,
	useBreakpointValue,
	useMediaQuery,
	useToast,
} from '@chakra-ui/react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { __ } from '@wordpress/i18n';
import React, { useEffect } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useNavigate } from 'react-router';
import { Link, NavLink, useParams } from 'react-router-dom';
import BackButton from '../../../../../../assets/js/back-end/components/common/BackButton';
import {
	Header,
	HeaderLeftSection,
	HeaderLogo,
} from '../../../../../../assets/js/back-end/components/common/Header';
import {
	NavMenu,
	NavMenuLink,
} from '../../../../../../assets/js/back-end/components/common/Nav';
import {
	navActiveStyles,
	navLinkStyles,
} from '../../../../../../assets/js/back-end/config/styles';
import routes from '../../../../../../assets/js/back-end/constants/routes';
import { useWarnUnsavedChanges } from '../../../../../../assets/js/back-end/hooks/useWarnUnSavedChanges';
import API from '../../../../../../assets/js/back-end/utils/api';
import {
	deepClean,
	editOperationInCache,
} from '../../../../../../assets/js/back-end/utils/utils';
import LinkedCourses from '../../common/components/LinkedCourses';
import Name from '../../common/components/Name';
import { urls } from '../../constants/urls';
import { groupsBackendRoutes } from '../../routes/routes';
import { GroupSchema } from '../../types/group';
import SkeletonEdit from './Skeleton/SkeletonEdit';
import Author from './elements/Author';
import Description from './elements/Description';
import Emails from './elements/Emails';
import GroupActionBtn from './elements/GroupActionBtn';
const headerTabStyles = {
	mr: '10',
	py: '6',
	d: 'flex',
	gap: 1,
	justifyContent: 'flex-start',
	alignItems: 'center',
	fontWeight: 'medium',
	fontSize: ['xs', null, 'sm'],
};

const EditGroup: React.FC = () => {
	const { groupId }: any = useParams();
	const toast = useToast();
	const queryClient = useQueryClient();
	const methods = useForm();
	const navigate = useNavigate();
	const groupAPI = new API(urls.groups);
	const [isLargerThan992] = useMediaQuery('(min-width: 992px)');
	const buttonSize = useBreakpointValue(['sm', 'md']);

	const groupQuery = useQuery<GroupSchema>({
		queryKey: [`group${groupId}`, groupId],
		queryFn: () => groupAPI.get(groupId, 'edit'),
	});

	useEffect(() => {
		if (groupQuery?.isError) {
			navigate(routes.notFound);
		}
	}, [groupQuery?.isError, navigate]);

	const updateGroup = useMutation<GroupSchema>({
		mutationFn: (data) => groupAPI.update(groupId, data),
		...{
			onSuccess: (data: any) => {
				editOperationInCache(
					queryClient,
					['groupsList', { order: 'desc', orderby: 'date' }],
					data,
				);
				queryClient.invalidateQueries({ queryKey: [`group${groupId}`] });
				queryClient.invalidateQueries({ queryKey: [`groupsList`] });
				toast({
					title: __(
						'Group updated successfully.',
						'learning-management-system',
					),
					isClosable: true,
					status: 'success',
				});
				navigate(groupsBackendRoutes.list);
			},

			onError: (error: any) => {
				const message: any = error?.message
					? error?.message
					: error?.data?.message;

				toast({
					title: __(
						'Failed to update the group.',
						'learning-management-system',
					),
					description: message ? `${message}` : undefined,
					status: 'error',
					isClosable: true,
				});
			},
		},
	});

	const onSubmit = (data: any) => {
		// Ensure emails field is preserved even if empty
		const cleanedData = deepClean(data);
		if (!cleanedData.hasOwnProperty('emails')) {
			cleanedData.emails = [];
		}
		updateGroup.mutate(cleanedData);
	};

	useWarnUnsavedChanges(methods.formState.isDirty);

	useEffect(() => {
		if (groupQuery?.isSuccess && groupQuery?.data) {
			// Convert emails array to the format expected by the select component
			const formData = {
				...groupQuery.data,
				emails:
					groupQuery.data.emails?.map((email: string) => ({
						value: email,
						label: email,
					})) || [],
			};
			methods.reset(formData);
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [groupQuery?.data]);

	const FormButton = () => (
		<ButtonGroup>
			<GroupActionBtn
				isLoading={updateGroup.isPending}
				methods={methods}
				onSubmit={onSubmit}
				groupStatus={groupQuery?.data?.status}
				orderInfo={groupQuery?.data?.order}
			/>
			<Button
				size={buttonSize}
				variant="outline"
				isDisabled={updateGroup.isPending}
				onClick={() =>
					navigate({
						pathname: groupsBackendRoutes.list,
					})
				}
			>
				{__('Cancel', 'learning-management-system')}
			</Button>
		</ButtonGroup>
	);

	return (
		<Stack direction="column" spacing="8" alignItems="center">
			<Header>
				<HeaderLeftSection>
					<HeaderLogo />
					<NavMenu color={'gray.600'}>
						<NavMenuLink
							as={NavLink}
							sx={{ ...navLinkStyles, borderBottom: '2px solid white' }}
							_hover={{ textDecoration: 'none' }}
							_activeLink={navActiveStyles}
							isActive={true}
						>
							{__('Edit Group', 'learning-management-system')}
						</NavMenuLink>
					</NavMenu>
				</HeaderLeftSection>
			</Header>
			<Container maxW="container.xl">
				<Stack direction="column" spacing="6">
					<ButtonGroup>
						<Link to={groupsBackendRoutes.list}>
							<BackButton />
						</Link>
					</ButtonGroup>
					{groupQuery.isSuccess ? (
						<FormProvider {...methods}>
							<form onSubmit={methods.handleSubmit(onSubmit)}>
								<Stack
									direction={['column', 'column', 'column', 'row']}
									spacing="8"
								>
									<Box
										flex="1"
										bg="white"
										p="10"
										shadow="box"
										display="flex"
										flexDirection="column"
										justifyContent="space-between"
									>
										<Stack direction="column" spacing="8">
											<Flex align="center" justify="space-between">
												<Heading as="h1" fontSize="x-large">
													{__('Edit Group', 'learning-management-system')}
												</Heading>
											</Flex>

											{/* Show edit order link if group is draft and order is incomplete */}
											{groupQuery?.data?.status === 'draft' &&
												groupQuery?.data?.order &&
												groupQuery?.data?.order?.status !== 'completed' && (
													<Alert status="warning" variant="left-accent">
														<AlertIcon />
														<Box>
															{__(
																'This group is in draft status because the associated order is not completed.',
																'learning-management-system',
															)}{' '}
															<Link
																to={routes.orders.edit.replace(
																	':orderId',
																	groupQuery.data.order.id.toString(),
																)}
																style={{
																	color: '#3182ce',
																	textDecoration: 'underline',
																	fontWeight: 'medium',
																}}
															>
																{__(
																	'Edit Order #%d',
																	'learning-management-system',
																).replace(
																	'%d',
																	groupQuery.data.order.id.toString(),
																)}
															</Link>{' '}
															{__(
																'to complete the purchase and publish this group.',
																'learning-management-system',
															)}
														</Box>
													</Alert>
												)}

											<Stack direction="column" spacing="6">
												<Name defaultValue={groupQuery?.data?.title} />
												<Description
													defaultValue={groupQuery?.data?.description}
												/>

												{isLargerThan992 ? <FormButton /> : null}
											</Stack>
										</Stack>
									</Box>
									<Box w={{ lg: '400px' }} bg="white" p="10" shadow="box">
										<Stack direction="column" spacing="6">
											<Author authorData={groupQuery?.data?.author} />
											<Emails
												defaultValue={groupQuery?.data?.emails || []}
												maxGroupSize={groupQuery?.data?.max_group_size}
											/>
											<LinkedCourses
												courses={groupQuery?.data?.courses || []}
											/>{' '}
											{!isLargerThan992 ? <FormButton /> : null}
										</Stack>
									</Box>
								</Stack>
							</form>
						</FormProvider>
					) : (
						<SkeletonEdit />
					)}
				</Stack>
			</Container>
		</Stack>
	);
};

export default EditGroup;
