'use client';

import { RefObject, useCallback, useEffect, useMemo, useState } from 'react';
import { useFormik } from 'formik';

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

import { OptionType, useSelect } from '@/components/input/SelectInput';
import { LocationApi, SupplierApi } from '@/services/api/master-data';
import { ProjectFlockApi } from '@/services/api/production';
import { Location } from '@/types/api/master-data/location';
import { Supplier } from '@/types/api/master-data/supplier';
import { ProjectFlock } from '@/types/api/production/project-flock';
import { isResponseSuccess } from '@/lib/api-helper';
import {
  ExpensesFilterSchema,
  ExpensesFilterValues,
} from '@/components/pages/expense/filter/ExpensesFilter';

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

const ExpensesFilterModal = ({
  ref,
  initialValues,
  onSubmit,
  onReset,
}: ExpensesFilterModalProps) => {
  const [selectedLocationId, setSelectedLocationId] = useState<string>(
    initialValues?.location?.value ? String(initialValues.location.value) : ''
  );
  const closeModalHandler = () => {
    ref.current?.close();
  };

  const categoryOptions = [
    { value: 'BOP', label: 'BOP' },
    { value: 'NON-BOP', label: 'NON-BOP' },
  ];

  const approvalStatusOptions = [
    { value: 'HEAD_AREA', label: 'Approval Head Area' },
    { value: 'UNIT_VICE_PRESIDENT', label: 'Approval Unit Vice President' },
    { value: 'FINANCE', label: 'Approval Finance' },
    { value: 'REALISASI', label: 'Realisasi' },
    { value: 'SELESAI', label: 'Selesai' },
    { value: 'DITOLAK', label: 'Ditolak' },
  ];

  const realizationStatusOptions = [
    { value: 'NOT_REALIZED', label: 'Belum Realisasi' },
    { value: 'REALIZED', label: 'Sudah Realisasi' },
    { value: 'REJECTED', label: 'Ditolak' },
  ];

  const {
    setInputValue: setLocationInputValue,
    options: locationOptions,
    isLoadingOptions: isLoadingLocationOptions,
    loadMore: loadMoreLocations,
  } = useSelect<Location>(LocationApi.basePath, 'id', 'name');

  const {
    setInputValue: setVendorInputValue,
    options: vendorOptions,
    isLoadingOptions: isLoadingVendorOptions,
    loadMore: loadMoreVendors,
  } = useSelect<Supplier>(SupplierApi.basePath, 'id', 'name');

  const {
    setInputValue: setProjectFlockInputValue,
    rawData: projectFlocksRawData,
    options: projectFlockOptions,
    isLoadingOptions: isLoadingProjectFlockOptions,
    loadMore: loadMoreProjectFlocks,
  } = useSelect<ProjectFlock>(
    ProjectFlockApi.basePath,
    'id',
    'flock_name',
    'search',
    {
      location_id: selectedLocationId || '',
    }
  );

  const formik = useFormik<ExpensesFilterValues>({
    enableReinitialize: true,
    initialValues: initialValues || {
      transaction_date: null,
      realization_date: null,
      location: null,
      vendor: null,
      category: null,
      approval_status: null,
      realization_status: null,
      project_flock: null,
      project_flock_kandang: null,
    },
    validationSchema: ExpensesFilterSchema,
    onSubmit: async (values) => {
      onSubmit?.(values);
      closeModalHandler();
    },
  });

  useEffect(() => {
    setSelectedLocationId(
      initialValues?.location?.value ? String(initialValues.location.value) : ''
    );
  }, [initialValues?.location]);

  const { resetForm } = formik;

  const formikResetHandler = useCallback(() => {
    resetForm({
      values: {
        transaction_date: null,
        realization_date: null,
        location: null,
        vendor: null,
        category: null,
        approval_status: null,
        realization_status: null,
        project_flock: null,
        project_flock_kandang: null,
      },
    });
    setSelectedLocationId('');
    onReset?.();
    closeModalHandler();
  }, [resetForm, onReset, closeModalHandler]);

  const locationChangeHandler = (val: OptionType | OptionType[] | null) => {
    const value = val as OptionType | null;
    formik.setFieldValue('location', value);
    formik.setFieldValue('project_flock', null);
    formik.setFieldValue('project_flock_kandang', null);
    setSelectedLocationId(value?.value ? String(value.value) : '');
  };

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

  const projectFlockKandangOptions = useMemo(() => {
    if (
      !formik.values.project_flock ||
      !projectFlocksRawData ||
      !isResponseSuccess(projectFlocksRawData)
    ) {
      return [];
    }

    const selectedProjectFlock = projectFlocksRawData.data.find(
      (item) => item.id === formik.values.project_flock?.value
    );

    return (
      selectedProjectFlock?.kandangs?.map((item) => ({
        value: item.project_flock_kandang_id,
        label: item.name,
      })) || []
    );
  }, [formik.values.project_flock, projectFlocksRawData]);

  return (
    <Modal
      ref={ref}
      className={{
        modalBox: 'p-0 rounded-xl xl:max-w-4/12 max-w-sm',
      }}
    >
      <form
        onSubmit={formik.handleSubmit}
        onReset={formikResetHandler}
        className='w-full flex flex-col'
      >
        {/* Modal Header */}
        <div className='p-4 flex items-center justify-between gap-2 border-b border-base-content/10'>
          <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'>
          <DateInput
            name='transaction_date'
            label='Tanggal Transaksi'
            placeholder='Tanggal Transaksi'
            value={formik.values.transaction_date || ''}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            isError={
              formik.touched.transaction_date &&
              !!formik.errors.transaction_date
            }
          />

          <DateInput
            name='realization_date'
            label='Tanggal Realisasi'
            placeholder='Tanggal Realisasi'
            value={formik.values.realization_date || ''}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            isError={
              formik.touched.realization_date &&
              !!formik.errors.realization_date
            }
          />

          <SelectInput
            label='Lokasi'
            placeholder='Pilih Lokasi'
            options={locationOptions}
            value={formik.values.location}
            onChange={locationChangeHandler}
            onInputChange={setLocationInputValue}
            isLoading={isLoadingLocationOptions}
            onMenuScrollToBottom={loadMoreLocations}
            isClearable
            isSearchable={true}
            className={{ wrapper: 'w-full' }}
          />

          <SelectInput
            label='Vendor'
            placeholder='Pilih Vendor'
            options={vendorOptions}
            value={formik.values.vendor}
            onChange={vendorChangeHandler}
            onInputChange={setVendorInputValue}
            isLoading={isLoadingVendorOptions}
            onMenuScrollToBottom={loadMoreVendors}
            isClearable
            isSearchable={true}
            className={{ wrapper: 'w-full' }}
          />

          <SelectInput
            label='Kategori'
            placeholder='Pilih Kategori'
            options={categoryOptions}
            value={formik.values.category}
            onChange={(val) =>
              formik.setFieldValue('category', val as OptionType | null)
            }
            isClearable
            className={{ wrapper: 'w-full' }}
          />

          <SelectInput
            label='Status BOP'
            placeholder='Pilih Status BOP'
            options={approvalStatusOptions}
            value={formik.values.approval_status}
            onChange={(val) =>
              formik.setFieldValue('approval_status', val as OptionType | null)
            }
            isClearable
            className={{ wrapper: 'w-full' }}
          />

          <SelectInput
            label='Status Pencairan'
            placeholder='Pilih Status Pencairan'
            options={realizationStatusOptions}
            value={formik.values.realization_status}
            onChange={(val) =>
              formik.setFieldValue(
                'realization_status',
                val as OptionType | null
              )
            }
            isClearable
            className={{ wrapper: 'w-full' }}
          />

          <SelectInput
            label='Project Flock'
            placeholder='Pilih Project Flock'
            options={projectFlockOptions}
            value={formik.values.project_flock}
            onChange={(val) => {
              formik.setFieldValue('project_flock', val as OptionType | null);
              formik.setFieldValue('project_flock_kandang', null);
            }}
            onInputChange={setProjectFlockInputValue}
            isLoading={isLoadingProjectFlockOptions}
            onMenuScrollToBottom={loadMoreProjectFlocks}
            isClearable
            isSearchable={true}
            className={{ wrapper: 'w-full' }}
          />

          <SelectInput
            label='Kandang'
            placeholder='Pilih Kandang'
            options={projectFlockKandangOptions}
            value={formik.values.project_flock_kandang}
            onChange={(val) =>
              formik.setFieldValue(
                'project_flock_kandang',
                val as OptionType | null
              )
            }
            isClearable
            isDisabled={!formik.values.project_flock}
            className={{ wrapper: 'w-full' }}
          />
        </div>

        {/* Modal Footer */}
        <div className='p-4 flex justify-between gap-4 border-t border-base-content/10 bg-gray-50'>
          <Button
            type='reset'
            variant='soft'
            className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
          >
            Reset Filter
          </Button>

          <Button
            type='submit'
            className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
            disabled={!formik.isValid || formik.isSubmitting}
          >
            Apply Filter
          </Button>
        </div>
      </form>
    </Modal>
  );
};

export default ExpensesFilterModal;
