import { useEffect } from 'react';
import { FormProvider, type UseFormReturn } from 'react-hook-form';

import Stack from '@material-hu/mui/Stack';

import CardContainer from '@material-hu/components/design-system/CardContainer';
import FormCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox/form';
import FormAutocomplete from '@material-hu/components/design-system/Inputs/Autocomplete/form';
import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import FormDatePicker from '@material-hu/components/design-system/Inputs/DatePicker/form';
import Title from '@material-hu/components/design-system/Title';

import { useLokaliseTranslation } from 'src/utils/i18n';
import { optionalLabel } from 'src/utils/stringUtils';

import { type GeneralConfigForm, type HiringReason } from '../../../types';
import {
  generalConfigFormFields as getGeneralConfigFormFields,
  INPUT_MAX_LENGTH,
} from '../../constants';
import { getHiringReasonsOptions } from '../../utils';

export const GeneralConfigStep = ({
  form,
  hiringReasons,
}: {
  form: UseFormReturn<GeneralConfigForm>;
  hiringReasons: HiringReason[];
}) => {
  const { t } = useLokaliseTranslation('ats');
  const { watch, trigger } = form;
  const generalConfigFields = getGeneralConfigFormFields(t);

  const targetCloseDate = watch(generalConfigFields.targetCloseDate.name) as
    | Date
    | undefined
    | null;

  // biome-ignore lint/correctness/useExhaustiveDependencies: Each time the targetCloseDate changes, we need to trigger the targetEmployeeStartDate validation
  useEffect(() => {
    trigger(generalConfigFields.targetEmployeeStartDate.name);
  }, [
    targetCloseDate,
    trigger,
    generalConfigFields.targetEmployeeStartDate.name,
  ]);

  const targetEmployeeStartDate = watch(
    generalConfigFields.targetEmployeeStartDate.name,
  ) as Date | undefined | null;

  // biome-ignore lint/correctness/useExhaustiveDependencies: Each time the targetEmployeeStartDate changes, we need to trigger the targetCloseDate validation
  useEffect(() => {
    trigger(generalConfigFields.targetCloseDate.name);
  }, [
    targetEmployeeStartDate,
    trigger,
    generalConfigFields.targetCloseDate.name,
  ]);

  const getOptionalLabel = (label: string) =>
    optionalLabel(label, t('common.optional'));

  return (
    <FormProvider {...form}>
      <Stack
        sx={{
          flexDirection: 'column',
          gap: 2,
        }}
      >
        <Stack sx={{ flexDirection: 'column' }}>
          <Title
            variant="L"
            title={t('job_offers.new.general_config.title')}
            description={`${t('job_offers.new.general_config.description')} ${t('common.mandatory_description')}`}
          />
        </Stack>
        {/* Section 1: Identificación del empleo */}
        <CardContainer
          fullWidth
          sx={{
            '& .MuiCardContent-root': {
              display: 'flex',
              flexDirection: 'column',
              width: '100%',
              gap: 3,
            },
          }}
        >
          <Title
            variant="M"
            title={t('job_offers.new.general_config.section_1.title')}
            description={t(
              'job_offers.new.general_config.section_1.description',
            )}
          />
          <Stack
            sx={{
              flexDirection: 'row',
              gap: 2,
            }}
          >
            <FormInputClassic
              name={generalConfigFields.name.name}
              inputProps={{
                label: generalConfigFields.name.label,
                placeholder: generalConfigFields.name.placeholder,
                hasCounter: false,
                maxLength: INPUT_MAX_LENGTH,
                sx: {
                  flex: 2,
                  width: 'auto',
                },
              }}
            />
            <FormInputClassic
              name={generalConfigFields.externalId.name}
              inputProps={{
                label: generalConfigFields.externalId.label,
                placeholder: generalConfigFields.externalId.placeholder,
                hasCounter: false,
                sx: {
                  maxLength: INPUT_MAX_LENGTH,
                  flex: 1.5,
                  width: 'auto',
                },
              }}
            />
          </Stack>
          <FormCheckbox
            name={generalConfigFields.isTestJob.name}
            checkBoxProps={{
              label: t(
                'job_offers.new.general_config.section_1.fields.is_test.label',
              ),
              description: t(
                'job_offers.new.general_config.section_1.fields.is_test.description',
              ),
            }}
          />
        </CardContainer>
        {/* Section 2: Estructura Organizacional */}
        <CardContainer
          fullWidth
          sx={{
            '& .MuiCardContent-root': {
              display: 'flex',
              flexDirection: 'column',
              width: '100%',
              gap: 3,
            },
          }}
        >
          <Title
            variant="M"
            title={t('job_offers.new.general_config.section_2.title')}
            description={t(
              'job_offers.new.general_config.section_2.description',
            )}
          />
          <FormInputClassic
            name={generalConfigFields.brand.name}
            inputProps={{
              label: generalConfigFields.brand.label,
              placeholder: generalConfigFields.brand.placeholder,
              helperText: generalConfigFields.brand.helperText,
              hasCounter: false,
              maxLength: INPUT_MAX_LENGTH,
            }}
          />
          <Stack
            sx={{
              flexDirection: 'row',
              gap: 2,
            }}
          >
            <FormInputClassic
              name={generalConfigFields.department.name}
              inputProps={{
                label: generalConfigFields.department.label,
                placeholder: generalConfigFields.department.placeholder,
                hasCounter: false,
                maxLength: INPUT_MAX_LENGTH,
                sx: {
                  flex: 1,
                  width: 'auto',
                },
              }}
            />
            <FormInputClassic
              name={generalConfigFields.positionName.name}
              inputProps={{
                label: generalConfigFields.positionName.label,
                placeholder: generalConfigFields.positionName.placeholder,
                hasCounter: false,
                maxLength: INPUT_MAX_LENGTH,
                sx: {
                  flex: 1,
                  width: 'auto',
                },
              }}
            />
          </Stack>
        </CardContainer>
        {/* Section 3: Detalles de la vacante */}
        <CardContainer
          fullWidth
          sx={{
            '& .MuiCardContent-root': {
              display: 'flex',
              flexDirection: 'column',
              width: '100%',
              gap: 3,
            },
          }}
        >
          <Title
            variant="M"
            title={t('job_offers.new.general_config.section_3.title')}
            description={t(
              'job_offers.new.general_config.section_3.description',
            )}
          />
          <FormAutocomplete
            name={generalConfigFields.hireReasonId.name}
            options={getHiringReasonsOptions(hiringReasons, t)}
            autocompleteProps={{
              isServerFiltered: false,
              multiple: false,
              placeholder: t('general:select'),
              label: getOptionalLabel(
                t(
                  'job_offers.new.general_config.section_3.fields.reason.label',
                ),
              ),
            }}
          />
          <Stack
            sx={{
              flexDirection: 'row',
              gap: 2,
            }}
          >
            <FormDatePicker
              name={generalConfigFields.targetCloseDate.name}
              inputProps={{
                label: getOptionalLabel(
                  t(
                    'job_offers.new.general_config.section_3.fields.expected_close_date.label',
                  ),
                ),
                enableClear: true,
                minDate: new Date(),
                maxDate: targetEmployeeStartDate || undefined,
              }}
            />
            <FormDatePicker
              name={generalConfigFields.targetEmployeeStartDate.name}
              inputProps={{
                label: getOptionalLabel(
                  t(
                    'job_offers.new.general_config.section_3.fields.expected_start_date.label',
                  ),
                ),
                enableClear: true,
                minDate: targetCloseDate || new Date(),
              }}
            />
          </Stack>
        </CardContainer>
      </Stack>
    </FormProvider>
  );
};
