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

import { IconCash } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import FormSwitcherCard from '@material-hu/components/composed-components/SwitcherCard/form';
import HuAlert from '@material-hu/components/design-system/Alert';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import FormAutocomplete from '@material-hu/components/design-system/Inputs/Autocomplete/form';
import ListItem from '@material-hu/components/design-system/List/components/ListItem';

import { useLokaliseTranslation } from 'src/utils/i18n';
import { getSellingBalanceOptions } from 'src/utils/vacations';

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

export type SellingBalanceShellProps = {
  allowedToSell: number;
  switcherTitle: string;
  switcherDescription: string;
};

const SellingBalanceShell = ({
  allowedToSell,
  switcherTitle,
  switcherDescription,
}: SellingBalanceShellProps) => {
  const { t } = useLokaliseTranslation('time_off');
  const form = useFormContext<RequestCreateForm>();

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

  const sellingOptions = useMemo(
    () => getSellingBalanceOptions(allowedToSell),
    [allowedToSell],
  );

  useEffect(() => {
    if (amountInMoney) {
      form.resetField(formFieldsRequestCreate.amountInMoney);
    }
    if (!hasSellingBalance) {
      form.clearErrors(formFieldsRequestCreate.amountInMoney);
    }
  }, [hasSellingBalance, fromDate?.getTime(), toDate?.getTime()]);

  const allowedToDisplayForm = fromDate && toDate;

  return (
    <FormSwitcherCard
      name={formFieldsRequestCreate.hasSellingBalance}
      switcherCardProps={{
        sx: {
          width: '100%',
          backgroundColor: theme => theme.palette.new.background.elements.grey,
        },
        slotProps: {
          title: {
            title: switcherTitle,
            description: switcherDescription,
          },
        },
      }}
    >
      <Stack sx={{ gap: 2, py: 1 }}>
        {!allowedToDisplayForm && (
          <HuAlert
            severity="info"
            title={t('money_request_alert')}
          />
        )}
        {allowedToDisplayForm && (
          <Stack sx={{ gap: 2 }}>
            <CardContainer
              fullWidth
              padding={0}
            >
              <ListItem
                avatar={{ Icon: IconCash }}
                text={{
                  title: t('total_days', { count: allowedToSell }),
                  description: t('available_in_money'),
                }}
              />
            </CardContainer>
            <FormAutocomplete
              name={formFieldsRequestCreate.amountInMoney}
              options={sellingOptions}
              autocompleteProps={{
                placeholder: t('select_count'),
                isServerFiltered: false,
              }}
              rules={{
                required: {
                  value: hasSellingBalance,
                  message: t('required_field'),
                },
              }}
            />
          </Stack>
        )}
      </Stack>
    </FormSwitcherCard>
  );
};

export default SellingBalanceShell;
