import { useEffect } from 'react';
import { Controller, useFormContext, useWatch } from 'react-hook-form';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import { IconEdit, IconTrash, IconUserPlus } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import MenuList, {
  type MenuListProps,
} from '@material-hu/components/composed-components/MenuList';
import UserAvatar from '@material-hu/components/composed-components/UserAvatar';
import Alert from '@material-hu/components/design-system/Alert';
import Button from '@material-hu/components/design-system/Buttons/Button';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import FormSwitcher from '@material-hu/components/design-system/Switcher/form';

import useFormatDate from 'src/hooks/useFormatDate';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { formFieldsRequestCreate } from '../../constant';
import { type RequestCreateForm } from '../../hooks/useRequestCreate';
import useSubstituteApprover from '../../hooks/useSubstituteApprover';

type SubstituteApproverProps = {
  disabled?: boolean;
};

const SubstituteApprover = ({ disabled = false }: SubstituteApproverProps) => {
  const { formatDate } = useFormatDate();
  const { t } = useLokaliseTranslation('time_off');
  const form = useFormContext<RequestCreateForm>();

  const [hasSubstituteApprover, substituteApprover, fromDate, toDate] =
    useWatch({
      name: [
        formFieldsRequestCreate.hasSubstituteApprover,
        formFieldsRequestCreate.substituteApprover,
        formFieldsRequestCreate.fromDate,
        formFieldsRequestCreate.toDate,
      ],
      control: form.control,
    });

  useEffect(() => {
    if (!hasSubstituteApprover) {
      form.clearErrors(formFieldsRequestCreate.substituteApprover);
    }
  }, [hasSubstituteApprover]);

  const {
    drawer: peopleSelectionDrawer,
    showDrawer: showPeopleSelectionDrawer,
  } = useDrawerV2(useSubstituteApprover);

  const options: MenuListProps['options'] = [
    {
      title: t('general:edit'),
      Icon: IconEdit,
      onClick: () => showPeopleSelectionDrawer({ isEdit: true }),
    },
    {
      title: t('general:delete'),
      Icon: IconTrash,
      onClick: () =>
        form.setValue(formFieldsRequestCreate.substituteApprover, null),
    },
  ];

  const displaySubstituteApproverAlert =
    substituteApprover && fromDate && toDate;

  return (
    <Controller
      name={formFieldsRequestCreate.substituteApprover}
      control={form.control}
      rules={{
        validate: value => {
          const hasSubstitute = form.getValues(
            formFieldsRequestCreate.hasSubstituteApprover,
          );

          if (hasSubstitute && !value) {
            return t('substitute_approver.required');
          }

          return true;
        },
      }}
      render={({ fieldState: { error } }) => (
        <CardContainer
          fullWidth
          color="grey"
        >
          {peopleSelectionDrawer}
          <FormSwitcher
            name={formFieldsRequestCreate.hasSubstituteApprover}
            switcherProps={{
              title: t('substitute_approver.assign'),
              description: t('substitute_approver.assign_description'),
              disabled,
            }}
          />
          <Stack sx={{ mt: 2, gap: 1 }}>
            {hasSubstituteApprover && (
              <>
                {substituteApprover && (
                  <Stack sx={{ gap: 1 }}>
                    <CardContainer fullWidth>
                      <Stack
                        sx={{
                          alignItems: 'center',
                          justifyContent: 'space-between',
                          flexDirection: 'row',
                        }}
                      >
                        <UserAvatar
                          user={substituteApprover}
                          profileProps={{ showEmployeeInternalId: true }}
                          sx={{
                            maxWidth: 500,
                            '& .MuiListItem-root': { p: 0 },
                          }}
                        />
                        <MenuList options={options} />
                      </Stack>
                    </CardContainer>
                    {displaySubstituteApproverAlert && (
                      <Alert
                        severity="info"
                        title={t('substitute_approver.assigned', {
                          startDate: formatDate(fromDate),
                          endDate: formatDate(toDate),
                        })}
                      />
                    )}
                  </Stack>
                )}
                {!substituteApprover && (
                  <Button
                    onClick={() => showPeopleSelectionDrawer({})}
                    variant="secondary"
                    sx={{ width: '100%' }}
                    startIcon={<IconUserPlus />}
                  >
                    {t('substitute_approver.assign')}
                  </Button>
                )}
              </>
            )}

            {error && (
              <Alert
                severity="error"
                title={error?.message as string}
              />
            )}
          </Stack>
        </CardContainer>
      )}
    />
  );
};

export default SubstituteApprover;
