import { type FC, useEffect } from 'react';
import { useFormContext } from 'react-hook-form';

import CardContainer from '@material-hu/components/design-system/CardContainer';
import HuFormInputSelect from '@material-hu/components/design-system/Inputs/Select/form';

import { useGetBalanceConformationForAdjustments } from 'src/hooks/queryHooks/vacations';
import useFormatDate from 'src/hooks/useFormatDate';
import useRules from 'src/hooks/useRules';
import { type BalanceReport, OperationsBalance } from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { type AdjustBalanceForm } from '../AdjustBalance';

export type AdjustBalanceTypeInputProps = {
  name: string;
  reportItem: BalanceReport;
};

export const AdjustBalanceCycle = (props: AdjustBalanceTypeInputProps) => {
  const { name, reportItem } = props;

  const { t } = useLokaliseTranslation('time_off');

  const { formatDate } = useFormatDate();

  const cycles = useGetBalanceConformationForAdjustments(
    reportItem.policy.policyType.id,
    reportItem.user.id,
  );

  const form = useFormContext<AdjustBalanceForm>();
  const { setValue, watch } = form;
  const operation = watch('operation');

  useEffect(() => {
    if (cycles.data && operation) {
      setValue(
        'cycleId',
        cycles.data.find(c =>
          operation === OperationsBalance.ADDITION
            ? c.isDefaultForAddition
            : c.isDefaultForSubtraction,
        )?.id! || cycles.data[0].id,
      );
    }
  }, [operation, cycles.data]);

  const rules = useRules({
    requiredWithMessage: true,
  });

  if (cycles.isLoading) {
    return null;
  }

  const options = cycles.data!.map(cycle => ({
    value: cycle.id,
    label: formatDate(cycle.fromDate) + ' - ' + formatDate(cycle.toDate),
  }));

  return (
    <CardContainer
      color="grey"
      fullWidth
    >
      <HuFormInputSelect
        name={name}
        inputProps={{
          options,
          helperText: t('select_cycle_helper_text'),
          label: t('cycle'),
          placeholder: t('select_cycle'),
        }}
        rules={rules}
      />
    </CardContainer>
  );
};

export default AdjustBalanceCycle;
