'use client';

import { RefObject, useMemo } from 'react';
import { useFormik } from 'formik';
import { Icon } from '@iconify/react';
import Modal from '@/components/Modal';
import Button from '@/components/Button';
import SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import { MARKETING_APPROVAL_LINE } from '@/config/approval-line';
import { MarketingFilter } from '@/types/api/marketing/marketing';
import SelectInputCheckbox from '@/components/input/SelectInputCheckbox';
import { MarketingApi } from '@/services/api/marketing/marketing';
import { isResponseSuccess } from '@/lib/api-helper';
import { BaseMarketing, BaseSalesOrder } from '@/types/api/marketing/marketing';

interface MarketingFilterModal {
  ref: RefObject<HTMLDialogElement | null>;
  onSubmit?: (values: MarketingFilter) => void;
  onReset?: () => void;
}

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

  // ===== OPTIONS =====
  const {
    rawData: productsRawData,
    isLoadingOptions: isLoadingProductsOptions,
    setInputValue: setProductsInputValue,
    loadMore: loadMoreProducts,
  } = useSelect<BaseMarketing>(MarketingApi.basePath, 'id', 'so_number', '', {
    limit: 'limit',
  });

  const productsOptions = useMemo(() => {
    if (!productsRawData || !isResponseSuccess(productsRawData)) return [];

    const productsMap = new Map<number, { value: number; label: string }>();

    productsRawData.data.forEach((deliveryOrder: BaseMarketing) => {
      deliveryOrder.sales_order?.forEach((so: BaseSalesOrder) => {
        const product = so.product_warehouse?.product;
        if (product?.id && product?.name) {
          productsMap.set(product.id, {
            value: product.id,
            label: product.name,
          });
        }
      });
    });

    return Array.from(productsMap.values());
  }, [productsRawData]);

  const {
    options: customersOptions,
    isLoadingOptions: isLoadingCustomersOptions,
    setInputValue: setCustomersInputValue,
    loadMore: loadMoreCustomers,
  } = useSelect(MarketingApi.basePath, 'customer.id', 'customer.name', '', {
    limit: 'limit',
  });

  const uniqueCustomersOptions = useMemo(() => {
    const seen = new Set();
    return customersOptions.filter((customer) => {
      if (seen.has(customer.value)) return false;
      seen.add(customer.value);
      return true;
    });
  }, [customersOptions]);

  const statusOptions = [
    ...MARKETING_APPROVAL_LINE.map((item) => ({
      value: item.step_name.split(' ').join('_').toUpperCase(),
      label: item.step_name,
    })),
    { value: 'DITOLAK', label: 'Ditolak' },
  ];

  const formik = useFormik<{
    product_ids: OptionType[];
    status: OptionType | null;
    customer_id: OptionType | null;
  }>({
    initialValues: {
      product_ids: [],
      status: null,
      customer_id: null,
    },

    onSubmit: async (values) => {
      const formattedValues = {
        ...values,
        product_ids: values.product_ids.map((item) => Number(item.value)),
        status: values.status?.value.toString() || '',
        customer_id: Number(values.customer_id?.value),
      };

      onSubmit?.(formattedValues);
      closeModalHandler();
    },

    onReset: () => {
      onReset?.();
      closeModalHandler();
    },
  });

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

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

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

  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'>
          {/* select multiple product */}
          <SelectInputCheckbox
            label='Product'
            isClearable
            placeholder='Pilih product'
            options={productsOptions}
            isLoading={isLoadingProductsOptions}
            value={formik.values.product_ids}
            onChange={productChangeHandler}
            onInputChange={setProductsInputValue}
            onMenuScrollToBottom={loadMoreProducts}
            isMulti
          />
          {/* select status */}
          <SelectInput
            label='Status'
            isClearable
            placeholder='Pilih status'
            options={statusOptions}
            value={formik.values.status}
            onChange={statusChangeHandler}
          />
          {/* select customer */}
          <SelectInput
            label='Customer'
            isClearable
            placeholder='Pilih customer'
            options={uniqueCustomersOptions}
            isLoading={isLoadingCustomersOptions}
            value={formik.values.customer_id}
            onChange={customerChangeHandler}
            onInputChange={setCustomersInputValue}
            onMenuScrollToBottom={loadMoreCustomers}
          />
        </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 MarketingFilterModal;
