import { useState, useMemo, useCallback, useRef } from 'react';
import useSWR from 'swr';
import { useSelect } from '@/components/input/SelectInput';
import DateInput from '@/components/input/DateInput';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import { AreaApi } from '@/services/api/master-data';
import { LocationApi } from '@/services/api/master-data';
import { WarehouseApi } from '@/services/api/master-data';
import { CustomerApi } from '@/services/api/master-data';
import { MarketingReportApi } from '@/services/api/report/marketing-report';
import Table from '@/components/Table';
import { ColumnDef } from '@tanstack/react-table';
import {
  formatCurrency,
  formatNumber,
  formatDate,
  formatVechicleNumber,
  formatTitleCase,
} from '@/lib/helper';
import { DailyMarketingRow } from '@/types/api/report/marketing';
import { isResponseSuccess } from '@/lib/api-helper';
import Button from '@/components/Button';
import Dropdown from '@/components/Dropdown';
import toast from 'react-hot-toast';
import { Icon } from '@iconify/react';
import { useFormik } from 'formik';
import {
  DailyMarketingReportFilterSchema,
  DailyMarketingReportFilterType,
} from '@/components/pages/report/marketing/filter/DailyMarketingFilter';
import SelectInput from '@/components/input/SelectInput';
import Modal, { useModal } from '@/components/Modal';
import { useTabActionsStore } from '@/stores/tab-actions/tab-actions.store';
import DailyMarketingReportSkeleton from '@/components/pages/report/marketing/skeleton/DailyMarketingSkeleton';
import { useEffect as useEffectHook } from 'react';
import {
  MARKETING_DATE_FILTER_TYPE_OPTIONS,
  MARKETING_TYPE_OPTIONS,
} from '@/config/constant';
import ButtonFilter from '@/components/helper/ButtonFilter';
import SelectInputRadio from '@/components/input/SelectInputRadio';

interface DailyMarketingTabProps {
  tabId: string;
}

interface FilterParams {
  page?: number;
  pageSize?: number;
  area_id?: string;
  location_id?: string;
  warehouse_id?: string;
  customer_id?: string;
  start_date?: string;
  end_date?: string;
  filter_by?: string;
  marketing_type?: string;
  sort_by?: string;
}

const DailyMarketingTab = ({ tabId }: DailyMarketingTabProps) => {
  // ===== STATE MANAGEMENT =====
  const [isPdfExportLoading, setIsPdfExportLoading] = useState(false);
  const [isExcelExportLoading, setIsExcelExportLoading] = useState(false);
  const isAnyExportLoading = isPdfExportLoading || isExcelExportLoading;

  // ===== SEARCH STATE =====
  const [searchValue, setSearchValue] = useState<string>('');

  // ===== FILTER STATE =====
  const [filterParams, setFilterParams] = useState<FilterParams>({});

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

  const handleFilterModalOpenRef = useRef(() => {});

  const filterModal = useModal();

  // ===== OPTIONS =====
  const {
    options: areaOptions,
    isLoadingOptions: isLoadingAreas,
    setInputValue: setAreaInputValue,
    loadMore: loadMoreArea,
  } = useSelect(AreaApi.basePath, 'id', 'name', 'search');

  const {
    options: locationOptions,
    isLoadingOptions: isLoadingLocations,
    setInputValue: setLocationInputValue,
    loadMore: loadMoreLocation,
  } = useSelect(LocationApi.basePath, 'id', 'name', 'search');

  const {
    options: warehouseOptions,
    isLoadingOptions: isLoadingWarehouses,
    setInputValue: setWarehouseInputValue,
    loadMore: loadMoreWarehouse,
  } = useSelect(WarehouseApi.basePath, 'id', 'name', 'search');

  const {
    options: customerOptions,
    isLoadingOptions: isLoadingCustomers,
    setInputValue: setCustomerInputValue,
    loadMore: loadMoreCustomer,
  } = useSelect(CustomerApi.basePath, 'id', 'name', 'search');

  // ===== FORMIK SETUP =====
  const formik = useFormik<DailyMarketingReportFilterType>({
    initialValues: {
      page: 1,
      pageSize: 10,
      search: null,
      area_id: null,
      location_id: null,
      warehouse_id: null,
      customer_id: null,
      start_date: null,
      end_date: null,
      filter_by: null,
      marketing_type: null,
      sort_by: null,
    },
    validationSchema: DailyMarketingReportFilterSchema,
    onSubmit: (values, { setSubmitting }) => {
      setFilterParams({
        page: values.page || undefined,
        pageSize: values.pageSize || undefined,
        area_id: values.area_id || undefined,
        location_id: values.location_id || undefined,
        warehouse_id: values.warehouse_id || undefined,
        customer_id: values.customer_id || undefined,
        start_date: values.start_date || undefined,
        end_date: values.end_date || undefined,
        filter_by: values.filter_by || undefined,
        marketing_type: values.marketing_type || undefined,
        sort_by: values.sort_by || undefined,
      });
      filterModal.closeModal();
      setSubmitting(false);
    },
    onReset: () => {
      setFilterParams({});
      filterModal.closeModal();
    },
  });

  handleFilterModalOpenRef.current = () => {
    formik.setValues({
      page: formik.values.page,
      pageSize: formik.values.pageSize,
      search: formik.values.search,
      area_id: filterParams.area_id || null,
      location_id: filterParams.location_id || null,
      warehouse_id: filterParams.warehouse_id || null,
      customer_id: filterParams.customer_id || null,
      start_date: filterParams.start_date || null,
      end_date: filterParams.end_date || null,
      filter_by: filterParams.filter_by || null,
      marketing_type: filterParams.marketing_type || null,
      sort_by: filterParams.sort_by || null,
    });
    filterModal.openModal();
  };

  // ===== SEARCH CHANGE HANDLER =====
  const searchChangeHandler = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      setSearchValue(e.target.value);
    },
    []
  );

  // ===== DERIVED VALUES =====
  const areaValue = useMemo(() => {
    if (!formik.values.area_id) return null;
    return (
      areaOptions.find((opt) => String(opt.value) === formik.values.area_id) ||
      null
    );
  }, [formik.values.area_id, areaOptions]);

  const locationValue = useMemo(() => {
    if (!formik.values.location_id) return null;
    return (
      locationOptions.find(
        (opt) => String(opt.value) === formik.values.location_id
      ) || null
    );
  }, [formik.values.location_id, locationOptions]);

  const warehouseValue = useMemo(() => {
    if (!formik.values.warehouse_id) return null;
    return (
      warehouseOptions.find(
        (opt) => String(opt.value) === formik.values.warehouse_id
      ) || null
    );
  }, [formik.values.warehouse_id, warehouseOptions]);

  const customerValue = useMemo(() => {
    if (!formik.values.customer_id) return null;
    return (
      customerOptions.find(
        (opt) => String(opt.value) === formik.values.customer_id
      ) || null
    );
  }, [formik.values.customer_id, customerOptions]);

  const filterByValue = useMemo(() => {
    if (!formik.values.filter_by) return null;
    return (
      MARKETING_DATE_FILTER_TYPE_OPTIONS.find(
        (opt) => opt.value === formik.values.filter_by
      ) || null
    );
  }, [formik.values.filter_by]);

  const marketingTypeValue = useMemo(() => {
    if (!formik.values.marketing_type) return null;
    return (
      MARKETING_TYPE_OPTIONS.find(
        (opt) => opt.value === formik.values.marketing_type
      ) || null
    );
  }, [formik.values.marketing_type]);

  // ===== DATA FETCHING =====
  const { data: dailyMarketings, isLoading } = useSWR(
    () => {
      const params = new URLSearchParams();

      if (searchValue) params.set('search', searchValue);
      if (filterParams.page) params.set('page', String(filterParams.page));
      if (filterParams.pageSize)
        params.set('limit', String(filterParams.pageSize));
      if (filterParams.area_id) params.set('area_id', filterParams.area_id);
      if (filterParams.location_id)
        params.set('location_id', filterParams.location_id);
      if (filterParams.warehouse_id)
        params.set('warehouse_id', filterParams.warehouse_id);
      if (filterParams.customer_id)
        params.set('customer_id', filterParams.customer_id);
      if (filterParams.start_date)
        params.set('start_date', filterParams.start_date);
      if (filterParams.end_date) params.set('end_date', filterParams.end_date);
      if (filterParams.filter_by)
        params.set('filter_by', filterParams.filter_by);
      if (filterParams.marketing_type)
        params.set('marketing_type', filterParams.marketing_type);
      if (filterParams.sort_by) params.set('sort_by', filterParams.sort_by);

      return ['daily-marketing-report', params.toString()];
    },
    ([, params]) =>
      MarketingReportApi.getAllDailyMarketingFetcher(
        `${MarketingReportApi.basePath}?${params}`
      )
  );

  const data: DailyMarketingRow[] = useMemo(
    () =>
      isResponseSuccess(dailyMarketings)
        ? (dailyMarketings?.data as DailyMarketingRow[]) || []
        : [],
    [dailyMarketings]
  );

  const summaryTotal = useMemo(
    () =>
      isResponseSuccess(dailyMarketings) && dailyMarketings?.total
        ? dailyMarketings.total
        : undefined,
    [dailyMarketings]
  );

  // ===== EXPORT HANDLERS =====
  const handleExportExcel = useCallback(async () => {
    setIsExcelExportLoading(true);
    try {
      const params = new URLSearchParams();

      if (searchValue) params.set('search', searchValue);
      if (filterParams.area_id) params.set('area_id', filterParams.area_id);
      if (filterParams.location_id)
        params.set('location_id', filterParams.location_id);
      if (filterParams.warehouse_id)
        params.set('warehouse_id', filterParams.warehouse_id);
      if (filterParams.customer_id)
        params.set('customer_id', filterParams.customer_id);
      if (filterParams.start_date)
        params.set('start_date', filterParams.start_date);
      if (filterParams.end_date) params.set('end_date', filterParams.end_date);
      if (filterParams.filter_by)
        params.set('filter_by', filterParams.filter_by);
      if (filterParams.marketing_type)
        params.set('marketing_type', filterParams.marketing_type);
      if (filterParams.sort_by) params.set('sort_by', filterParams.sort_by);

      await MarketingReportApi.exportDailyMarketingToExcel(params.toString());

      toast.success('Excel berhasil dibuat dan diunduh.');
    } catch {
      toast.error('Gagal membuat Excel. Silakan coba lagi.');
    } finally {
      setIsExcelExportLoading(false);
    }
  }, [filterParams, searchValue]);

  const handleExportPDF = useCallback(async () => {
    setIsPdfExportLoading(true);
    try {
      const params = new URLSearchParams();

      if (searchValue) params.set('search', searchValue);
      if (filterParams.area_id) params.set('area_id', filterParams.area_id);
      if (filterParams.location_id)
        params.set('location_id', filterParams.location_id);
      if (filterParams.warehouse_id)
        params.set('warehouse_id', filterParams.warehouse_id);
      if (filterParams.customer_id)
        params.set('customer_id', filterParams.customer_id);
      if (filterParams.start_date)
        params.set('start_date', filterParams.start_date);
      if (filterParams.end_date) params.set('end_date', filterParams.end_date);
      if (filterParams.filter_by)
        params.set('filter_by', filterParams.filter_by);
      if (filterParams.marketing_type)
        params.set('marketing_type', filterParams.marketing_type);
      if (filterParams.sort_by) params.set('sort_by', filterParams.sort_by);

      await MarketingReportApi.exportDailyMarketingToPDF(params.toString());

      toast.success('PDF berhasil dibuat dan diunduh.');
    } catch {
      toast.error('Gagal membuat PDF. Silakan coba lagi.');
    } finally {
      setIsPdfExportLoading(false);
    }
  }, [filterParams, searchValue]);

  // ===== TAB ACTIONS COMPONENT =====
  const TabActions = useMemo(() => {
    return function TabActionsComponent() {
      const setTabActions = useTabActionsStore((state) => state.setTabActions);
      const clearTabActions = useTabActionsStore(
        (state) => state.clearTabActions
      );

      useEffectHook(() => {
        setTabActions(
          tabId,
          <div className='flex flex-row gap-3 items-center'>
            <DebouncedTextInput
              name='search'
              placeholder='Search'
              value={searchValue}
              onChange={searchChangeHandler}
              startAdornment={
                <Icon
                  icon='heroicons:magnifying-glass'
                  width={20}
                  height={20}
                />
              }
              className={{
                wrapper: 'w-full min-w-48 max-w-3xs',
                inputWrapper: 'rounded-xl! shadow-button-soft',
                input:
                  'placeholder:font-semibold placeholder:text-base-content/50',
              }}
            />

            <ButtonFilter
              values={filterParams}
              fieldGroups={[['start_date', 'end_date']]}
              onClick={() => handleFilterModalOpenRef.current()}
              variant='outline'
              className='px-3 py-2.5'
            />

            <Dropdown
              align='end'
              direction='bottom'
              className={{
                content:
                  'mt-1 rounded-xl border border-base-content/5 shadow-sm overflow-hidden',
              }}
              trigger={
                <Button
                  variant='outline'
                  color='none'
                  isLoading={isAnyExportLoading}
                  className='px-3 py-2.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
                >
                  <div className='flex flex-row items-center gap-1.5'>
                    <Icon
                      icon='heroicons:cloud-arrow-down'
                      width={20}
                      height={20}
                    />

                    <span>Export</span>

                    <div className='w-px self-stretch bg-base-content/10' />

                    <Icon
                      icon='heroicons:chevron-down'
                      width={14}
                      height={14}
                    />
                  </div>
                </Button>
              }
            >
              <Button
                variant='ghost'
                color='none'
                onClick={handleExportExcel}
                isLoading={isExcelExportLoading}
                className='w-full p-3 justify-start text-sm text-base-content/50 font-semibold text-nowrap'
              >
                <Icon icon='heroicons:table-cells' width={20} height={20} />
                Export to Excel
              </Button>
              <Button
                variant='ghost'
                color='none'
                onClick={handleExportPDF}
                isLoading={isPdfExportLoading}
                className='w-full p-3 justify-start text-sm text-base-content/50 font-semibold text-nowrap'
              >
                <Icon icon='heroicons:document' width={20} height={20} />
                Export to PDF
              </Button>
            </Dropdown>
          </div>
        );
      }, [setTabActions]);

      useEffectHook(() => {
        return () => {
          clearTabActions(tabId);
        };
      }, [clearTabActions]);

      return null;
    };
  }, [
    tabId,
    filterParams,
    searchValue,
    isAnyExportLoading,
    handleExportExcel,
    handleExportPDF,
    isExcelExportLoading,
    isPdfExportLoading,
    searchChangeHandler,
  ]);

  const TabActionsElement = useMemo(() => <TabActions />, [TabActions]);

  const getTableColumns = (): ColumnDef<DailyMarketingRow>[] => {
    const tableColumns: ColumnDef<DailyMarketingRow>[] = [
      {
        id: 'no',
        header: 'No',
        cell: (props) => props.row.index + 1,
        footer: () => <div className='font-semibold text-gray-900'>TOTAL</div>,
      },
      {
        id: 'so_date',
        header: 'Tanggal Jual',
        accessorKey: 'so_date',
        cell: (props) => formatDate(props.row.original.so_date, 'DD-MMM-YYYY'),
        footer: () => <div className='font-semibold text-gray-900'>ALL</div>,
      },
      {
        id: 'realization_date',
        header: 'Tanggal Realisasi',
        accessorKey: 'realization_date',
        cell: (props) =>
          formatDate(props.row.original.realization_date, 'DD-MMM-YYYY'),
        footer: () => <div className='font-semibold text-gray-900'>-</div>,
      },
      {
        id: 'aging_days',
        header: 'Aging',
        accessorKey: 'aging_days',
        cell: (props) => `${props.row.original.aging_days} hari`,
        footer: () => <div className='font-semibold text-gray-900'>-</div>,
      },
      {
        id: 'warehouse',
        header: 'Gudang Fisik',
        accessorKey: 'warehouse',
        cell: ({ row }) => row.original.warehouse.name,
        footer: () => <div className='font-semibold text-gray-900'>-</div>,
      },
      {
        id: 'customer',
        header: 'Pelanggan',
        accessorKey: 'customer',
        cell: ({ row }) => row.original.customer.name,
        footer: () => <div className='font-semibold text-gray-900'>-</div>,
      },
      {
        id: 'do_number',
        header: 'No. DO',
        accessorKey: 'do_number',
        footer: () => <div className='font-semibold text-gray-900'>-</div>,
      },
      {
        id: 'sales_person',
        header: 'Sales/Marketing',
        accessorKey: 'sales',
        cell: (props) => props.row.original.sales.name,
        footer: () => <div className='font-semibold text-gray-900'>-</div>,
      },
      {
        id: 'vehicle_number',
        header: 'No. Polisi',
        accessorKey: 'vehicle_number',
        cell: (props) => (
          <span className='text-nowrap'>
            {formatVechicleNumber(props.row.original.vehicle_number)}
          </span>
        ),
        footer: () => <div className='font-semibold text-gray-900'>-</div>,
      },
      {
        id: 'marketing_type',
        header: 'Marketing Type',
        accessorKey: 'marketing_type',
        cell: (props) => (
          <span className='text-nowrap'>
            {formatTitleCase(props.row.original.marketing_type || '-')}
          </span>
        ),
        footer: () => <div className='font-semibold text-gray-900'>-</div>,
      },
      {
        id: 'product',
        header: 'Produk',
        accessorKey: 'product',
        cell: ({ row }) => row.original.product.name,
        footer: () => <div className='font-semibold text-gray-900'>-</div>,
      },
      {
        id: 'qty',
        header: 'Kuantitas',
        accessorKey: 'qty',
        cell: (props) => formatNumber(props.row.original.qty),
        footer: () => (
          <div className='font-semibold text-gray-900'>
            {summaryTotal?.total_qty
              ? formatNumber(summaryTotal.total_qty)
              : '-'}
          </div>
        ),
      },
      {
        id: 'average_weight',
        header: 'Bobot Rata-Rata (Kg)',
        accessorKey: 'average_weight_kg',
        cell: (props) => formatNumber(props.row.original.average_weight_kg),
        footer: () => (
          <div className='font-semibold text-gray-900'>
            {summaryTotal?.average_weight_kg
              ? formatNumber(summaryTotal.average_weight_kg)
              : '-'}
          </div>
        ),
      },
      {
        id: 'total_weight',
        header: 'Bobot Total (Kg)',
        accessorKey: 'total_weight_kg',
        cell: (props) => formatNumber(props.row.original.total_weight_kg),
        footer: () => (
          <div className='font-semibold text-gray-900'>
            {summaryTotal?.total_weight_kg
              ? formatNumber(summaryTotal.total_weight_kg)
              : '-'}
          </div>
        ),
      },
      {
        id: 'sales_price',
        header: 'Harga Jual (Rp)',
        accessorKey: 'sales_price_per_kg',
        cell: (props) => formatCurrency(props.row.original.sales_price_per_kg),
        footer: () => (
          <div className='font-semibold text-gray-900'>
            {summaryTotal?.average_sales_price
              ? formatCurrency(summaryTotal.average_sales_price)
              : '-'}
          </div>
        ),
      },
      {
        id: 'hpp_price',
        header: 'HPP (Rp)',
        accessorKey: 'hpp_price_per_kg',
        cell: (props) => formatCurrency(props.row.original.hpp_price_per_kg),
        footer: () => (
          <div className='font-semibold text-gray-900'>
            {summaryTotal?.total_hpp_price_per_kg
              ? formatCurrency(summaryTotal.total_hpp_price_per_kg)
              : '-'}
          </div>
        ),
      },
      {
        id: 'sales_amount',
        header: 'Total (Rp)',
        accessorKey: 'sales_amount',
        cell: (props) => formatCurrency(props.row.original.sales_amount),
        footer: () => (
          <div className='font-semibold text-gray-900'>
            {summaryTotal?.total_sales_amount
              ? formatCurrency(summaryTotal.total_sales_amount)
              : '-'}
          </div>
        ),
      },
    ];
    return tableColumns;
  };

  return (
    <>
      {TabActionsElement}
      <div className='w-full p-0 sm:p-3 flex flex-col gap-3'>
        {isLoading && (
          <DailyMarketingReportSkeleton
            columns={getTableColumns()}
            icon={
              <Icon
                icon='heroicons:document-report'
                className='text-white'
                width={20}
                height={20}
              />
            }
            title='Memuat Data Penjualan Harian'
            subtitle='Silakan tunggu sebentar...'
          />
        )}

        {!isLoading && data.length === 0 && (
          <DailyMarketingReportSkeleton
            columns={getTableColumns()}
            icon={
              <Icon
                icon='heroicons:chart-bar'
                className='text-white'
                width={20}
                height={20}
              />
            }
            title='Data Not Yet Available'
            subtitle='Please change your filters to get the data.'
          />
        )}

        {!isLoading && data.length > 0 && (
          <Table
            data={data}
            columns={getTableColumns()}
            pageSize={filterParams.pageSize}
            page={
              isResponseSuccess(dailyMarketings)
                ? dailyMarketings?.meta?.page
                : 0
            }
            totalItems={
              isResponseSuccess(dailyMarketings)
                ? dailyMarketings?.meta?.total_results
                : 0
            }
            onPageChange={(newPage) =>
              setFilterParams((prevVal) => ({ ...prevVal, page: newPage }))
            }
            onPageSizeChange={(newPageSize) =>
              setFilterParams((prevVal) => ({
                ...prevVal,
                pageSize: newPageSize,
              }))
            }
            isLoading={isLoading}
            renderFooter={data.length > 0}
            className={{
              containerClassName: 'w-full mb-0!',
              tableWrapperClassName: 'overflow-x-auto',
              tableClassName: 'w-full table-auto text-sm',
              headerRowClassName: 'border-b border-b-gray-200 bg-gray-50',
              headerColumnClassName:
                'px-4 py-3 text-xs font-semibold text-gray-700 text-left border border-gray-200 text-nowrap',
              bodyRowClassName:
                'hover:bg-gray-50 transition-colors border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200',
              bodyColumnClassName:
                'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
              tableFooterClassName:
                'bg-gray-100 font-semibold border border-gray-200',
              footerRowClassName: 'border-t-2 border-gray-300',
              footerColumnClassName:
                'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
            }}
          />
        )}
      </div>

      {/* Filter Modal */}
      <Modal
        ref={filterModal.ref}
        className={{
          modal: 'p-0',
          modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
        }}
      >
        {/* Modal Header */}
        <div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
          <div className='flex items-center gap-2 text-primary'>
            <Icon icon='heroicons:funnel' width={20} height={20} />
            <h3 className='font-medium text-sm'>Filter Data</h3>
          </div>
          <Button
            variant='link'
            onClick={filterModal.closeModal}
            className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
          >
            <Icon icon='heroicons:x-mark' width={20} height={20} />
          </Button>
        </div>
        <form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
          <div className='p-4 flex flex-col gap-3'>
            {/* Date Range Filter */}
            <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='start_date'
                  placeholder='Tanggal Awal'
                  value={formik.values.start_date || ''}
                  onChange={(e) => {
                    const value = e.target.value;
                    formik.setFieldValue('start_date', value || null);

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

                      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);
                    }
                  }}
                  className={{ wrapper: 'w-full' }}
                  errorMessage={formik.errors.start_date}
                  isError={
                    !!formik.errors.start_date && formik.touched.start_date
                  }
                />
                <hr className='w-full max-w-3 h-px border-base-content/10' />
                <DateInput
                  name='end_date'
                  placeholder='Tanggal Akhir'
                  value={formik.values.end_date || ''}
                  onChange={(e) => {
                    const value = e.target.value;
                    formik.setFieldValue('end_date', value || null);

                    if (value && formik.values.start_date) {
                      const startDateObj = new Date(formik.values.start_date);
                      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);
                    }
                  }}
                  className={{ wrapper: 'w-full' }}
                  errorMessage={formik.errors.end_date}
                  isError={
                    (formik.errors.end_date && formik.touched.end_date) ||
                    hasDateError
                  }
                />
              </div>
            </div>

            {/* Area Filter */}
            <SelectInput
              label='Area'
              placeholder='Pilih Area'
              options={areaOptions}
              isLoading={isLoadingAreas}
              value={areaValue}
              onChange={(val) => {
                formik.setFieldValue(
                  'area_id',
                  val && !Array.isArray(val) ? String(val.value) : null
                );
              }}
              isClearable
              className={{ wrapper: 'w-full' }}
              onInputChange={setAreaInputValue}
              onMenuScrollToBottom={loadMoreArea}
            />

            {/* Location Filter */}
            <SelectInput
              label='Lokasi'
              placeholder='Pilih Lokasi'
              options={locationOptions}
              isLoading={isLoadingLocations}
              value={locationValue}
              onChange={(val) => {
                formik.setFieldValue(
                  'location_id',
                  val && !Array.isArray(val) ? String(val.value) : null
                );
              }}
              isClearable
              className={{ wrapper: 'w-full' }}
              onInputChange={setLocationInputValue}
              onMenuScrollToBottom={loadMoreLocation}
            />

            {/* Warehouse Filter */}
            <SelectInput
              label='Gudang Fisik'
              placeholder='Pilih Gudang Fisik'
              options={warehouseOptions}
              isLoading={isLoadingWarehouses}
              value={warehouseValue}
              onChange={(val) => {
                formik.setFieldValue(
                  'warehouse_id',
                  val && !Array.isArray(val) ? String(val.value) : null
                );
              }}
              isClearable
              className={{ wrapper: 'w-full' }}
              onInputChange={setWarehouseInputValue}
              onMenuScrollToBottom={loadMoreWarehouse}
            />

            {/* Customer Filter */}
            <SelectInput
              label='Customer'
              placeholder='Pilih Customer'
              options={customerOptions}
              isLoading={isLoadingCustomers}
              value={customerValue}
              onChange={(val) => {
                formik.setFieldValue(
                  'customer_id',
                  val && !Array.isArray(val) ? String(val.value) : null
                );
              }}
              isClearable
              className={{ wrapper: 'w-full' }}
              onInputChange={setCustomerInputValue}
              onMenuScrollToBottom={loadMoreCustomer}
            />

            {/* Filter By Date Type */}
            <SelectInputRadio
              label='Filter Tanggal'
              placeholder='Pilih Filter Tanggal'
              options={MARKETING_DATE_FILTER_TYPE_OPTIONS}
              value={filterByValue}
              onChange={(val) => {
                formik.setFieldValue(
                  'filter_by',
                  val && !Array.isArray(val) ? (val.value as string) : null
                );
              }}
              isClearable
              className={{ wrapper: 'w-full' }}
            />

            {/* Marketing Type Filter */}
            <SelectInputRadio
              label='Tipe Marketing'
              placeholder='Pilih Tipe Marketing'
              options={MARKETING_TYPE_OPTIONS}
              value={marketingTypeValue}
              onChange={(val) => {
                formik.setFieldValue(
                  'marketing_type',
                  val && !Array.isArray(val) ? (val.value as string) : null
                );
              }}
              isClearable
              className={{ wrapper: 'w-full' }}
            />
          </div>

          {/* Modal Footer */}
          <div className='flex justify-between items-center gap-4 p-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.isSubmitting}
            >
              Apply Filter
            </Button>
          </div>
        </form>
      </Modal>
    </>
  );
};

export default DailyMarketingTab;
