'use client';

import { RefObject, useState, useEffect } from 'react';
import { useFormik } from 'formik';
import toast from 'react-hot-toast';

import { Icon } from '@iconify/react';
import Modal from '@/components/Modal';
import Button from '@/components/Button';
import DateInput from '@/components/input/DateInput';
import SelectInputCheckbox from '@/components/input/SelectInputCheckbox';

import { OptionType, useSelect } from '@/components/input/SelectInput';
import { ProjectFlockApi } from '@/services/api/production';
import { Flock } from '@/types/api/master-data/flock';
import {
  TransferToLayingFilterSchema,
  TransferToLayingFilterValues,
} from '@/components/pages/production/transfer-to-laying/filter/TransferToLayingFilter';

interface TransferToLayingFilterModal {
  ref: RefObject<HTMLDialogElement | null>;
  initialValues?: Partial<TransferToLayingFilterValues>;
  onSubmit?: (values: TransferToLayingFilterValues) => void;
  onReset?: () => void;
}

const TransferToLayingFilterModal = ({
  ref,
  initialValues: initialValuesProp,
  onSubmit,
  onReset,
}: TransferToLayingFilterModal) => {
  const closeModalHandler = () => {
    ref.current?.close();
  };

  // ===== DATE ERROR STATE =====
  const [dateErrorShown, setDateErrorShown] = useState(false);
  const [hasDateError, setHasDateError] = useState(false);

  // ===== CLEANUP TOAST ON UNMOUNT =====
  useEffect(() => {
    return () => {
      if (dateErrorShown) {
        toast.dismiss();
      }
    };
  }, [dateErrorShown]);

  // ===== CLEANUP TOAST WHEN MODAL CLOSES =====
  useEffect(() => {
    const dialogElement = ref.current;
    const handleModalClose = () => {
      if (dateErrorShown) {
        toast.dismiss();
        setDateErrorShown(false);
      }
    };

    dialogElement?.addEventListener('close', handleModalClose);

    return () => {
      dialogElement?.removeEventListener('close', handleModalClose);
    };
  }, [ref, dateErrorShown]);

  //   Flock Source
  const {
    setInputValue: setFlockSourceInputValue,
    options: flockSourceOptions,
    isLoadingOptions: isLoadingFlockSourceOptions,
    loadMore: loadMoreFlockSource,
  } = useSelect<Flock>(ProjectFlockApi.basePath, 'id', 'flock_name', 'search', {
    category: 'GROWING',
  });

  // Flock Destination
  const {
    setInputValue: setFlockDestinationInputValue,
    options: flockDestinationOptions,
    isLoadingOptions: isLoadingFlockDestinationOptions,
    loadMore: loadMoreFlockDestination,
  } = useSelect<Flock>(ProjectFlockApi.basePath, 'id', 'flock_name', 'search', {
    category: 'LAYING',
  });

  const formik = useFormik<TransferToLayingFilterValues>({
    initialValues: {
      startDate: initialValuesProp?.startDate ?? '',
      endDate: initialValuesProp?.endDate ?? '',
      flockSource: initialValuesProp?.flockSource ?? [],
      flockDestination: initialValuesProp?.flockDestination ?? [],
      status: initialValuesProp?.status ?? [],
    },
    enableReinitialize: true,
    validationSchema: TransferToLayingFilterSchema,
    onSubmit: async (values) => {
      onSubmit?.(values);
      closeModalHandler();
    },
    onReset: () => {
      onReset?.();
      closeModalHandler();
    },
  });

  const flockSourceChangeHandler = (val: OptionType | OptionType[] | null) => {
    formik.setFieldValue('flockSource', val);
  };

  const flockDestinationChangeHandler = (
    val: OptionType | OptionType[] | null
  ) => {
    formik.setFieldValue('flockDestination', val);
  };

  const statusChangeHandler = (val: OptionType | OptionType[] | null) => {
    formik.setFieldValue('status', val);
  };

  return (
    <Modal
      ref={ref}
      className={{
        modalBox: 'p-0 rounded-xl',
      }}
    >
      <form
        onSubmit={formik.handleSubmit}
        onReset={formik.handleReset}
        className='w-full flex flex-col'
      >
        {/* Modal Header */}
        <div className='p-4 flex items-center justify-between gap-2 border-b border-gray-300'>
          <div className='flex items-center gap-2 text-primary'>
            <Icon icon='heroicons:funnel' width={20} height={20} />
            <h3 className='text-sm font-medium'>Filter Data</h3>
          </div>

          <Button
            type='button'
            variant='ghost'
            color='none'
            onClick={closeModalHandler}
            className='p-0 text-base-content/50 hover:text-base-content'
          >
            <Icon icon='heroicons:x-mark' width={20} height={20} />
          </Button>
        </div>

        {/* Modal Body */}
        <div className='p-4 flex flex-col gap-1.5'>
          <div className='flex flex-col'>
            <span className='py-2 text-xs font-semibold'>Tanggal</span>
            <div className='flex flex-row items-center gap-1.5'>
              <DateInput
                name='startDate'
                placeholder='Tanggal Awal'
                value={formik.values.startDate || ''}
                errorMessage={formik.errors.startDate}
                onChange={(e) => {
                  const value = e.target.value;
                  formik.setFieldValue('startDate', value);

                  if (value && formik.values.endDate) {
                    const startDate = new Date(value);
                    const endDateObj = new Date(formik.values.endDate);

                    if (endDateObj < startDate) {
                      setHasDateError(true);
                      if (!dateErrorShown) {
                        toast.error('Tanggal akhir tidak boleh masa lampau', {
                          duration: Infinity,
                        });
                        setDateErrorShown(true);
                      }
                    } else {
                      setHasDateError(false);
                      if (dateErrorShown) {
                        toast.dismiss();
                        setDateErrorShown(false);
                      }
                    }
                  } else {
                    setHasDateError(false);
                  }
                }}
                onBlur={formik.handleBlur}
                isError={
                  formik.touched.startDate && Boolean(formik.errors.startDate)
                }
              />
              <hr className='w-full max-w-3 h-px border-base-content/10' />
              <DateInput
                name='endDate'
                placeholder='Tanggal Akhir'
                value={formik.values.endDate || ''}
                errorMessage={formik.errors.endDate}
                onChange={(e) => {
                  const value = e.target.value;
                  formik.setFieldValue('endDate', value);

                  if (value && formik.values.startDate) {
                    const startDateObj = new Date(formik.values.startDate);
                    const endDate = new Date(value);

                    if (endDate < startDateObj) {
                      setHasDateError(true);
                      if (!dateErrorShown) {
                        toast.error('Tanggal akhir tidak boleh masa lampau', {
                          duration: Infinity,
                        });
                        setDateErrorShown(true);
                      }
                      return;
                    }
                  }

                  setHasDateError(false);
                  if (dateErrorShown) {
                    toast.dismiss();
                    setDateErrorShown(false);
                  }
                }}
                onBlur={formik.handleBlur}
                isError={
                  (formik.touched.endDate && Boolean(formik.errors.endDate)) ||
                  hasDateError
                }
              />
            </div>

            <SelectInputCheckbox
              label='Flock Asal'
              placeholder='Flock Asal'
              value={formik.values.flockSource as OptionType[]}
              onChange={flockSourceChangeHandler}
              options={flockSourceOptions}
              isLoading={isLoadingFlockSourceOptions}
              onInputChange={setFlockSourceInputValue}
              onMenuScrollToBottom={loadMoreFlockSource}
            />

            <SelectInputCheckbox
              label='Flock Tujuan'
              placeholder='Flock Tujuan'
              value={formik.values.flockDestination as OptionType[]}
              onChange={flockDestinationChangeHandler}
              options={flockDestinationOptions}
              isLoading={isLoadingFlockDestinationOptions}
              onInputChange={setFlockDestinationInputValue}
              onMenuScrollToBottom={loadMoreFlockDestination}
            />

            <SelectInputCheckbox
              label='Status'
              placeholder='Pilih Status'
              options={[
                { value: 'PENDING', label: 'Pengajuan' },
                { value: 'APPROVED', label: 'Disetujui' },
                { value: 'REJECTED', label: 'Ditolak' },
              ]}
              value={formik.values.status as OptionType[]}
              onChange={statusChangeHandler}
            />
          </div>
        </div>

        {/* Modal Footer */}
        <div className='p-4 flex justify-between gap-4 border-t border-gray-300 bg-gray-100'>
          <Button
            type='reset'
            variant='ghost'
            color='none'
            className='p-3 rounded-lg text-base-content/65'
          >
            Reset Filter
          </Button>

          <Button
            type='submit'
            className='p-3 rounded-lg w-fit sm:w-full max-w-40 text-base-100 text-sm'
          >
            Apply Filter
          </Button>
        </div>
      </form>
    </Modal>
  );
};

export default TransferToLayingFilterModal;
