import { useState, useMemo, useCallback, useRef } from 'react';
import useSWR from 'swr';
import { useSelect } from '@/components/input/SelectInput';
import DateInput from '@/components/input/DateInput';
import NumberInput from '@/components/input/NumberInput';
import { AreaApi } from '@/services/api/master-data';
import { LocationApi } from '@/services/api/master-data';
import { ProjectFlockKandangApi } from '@/services/api/production';
import { SaleReportApi } from '@/services/api/report/marketing-sale';
import Table from '@/components/Table';
import { ColumnDef, Row, flexRender } from '@tanstack/react-table';
import { formatCurrency, formatNumber } from '@/lib/helper';
import {
  HppPerKandangReport,
  HppPerKandangRow,
  HppPerKandangPerWeightRange,
} from '@/types/api/report/hpp-per-kandang';
import { isResponseSuccess } from '@/lib/api-helper';
import Button from '@/components/Button';
import ButtonFilter from '@/components/helper/ButtonFilter';
import Dropdown from '@/components/Dropdown';
import { generateHppPerKandangPDF } from '@/components/pages/report/marketing/export/HppPerkandangExportPDF';
import { generateHppPerKandangExcel } from '@/components/pages/report/marketing/export/HppPerkandangExportXLSX';
import toast from 'react-hot-toast';
import { Icon } from '@iconify/react';
import { useFormik } from 'formik';
import {
  HppPerKandangFilterSchema,
  HppPerKandangFilterType,
} from '@/components/pages/report/marketing/filter/HppPerKandangFilter';
import SelectInputCheckbox from '@/components/input/SelectInputCheckbox';
import SelectInputRadio from '@/components/input/SelectInputRadio';
import Modal, { useModal } from '@/components/Modal';
import { useTabActionsStore } from '@/stores/tab-actions/tab-actions.store';
import HppPerKandangSkeleton from '@/components/pages/report/marketing/skeleton/HppPerKandangSkeleton';
import { useEffect as useEffectHook } from 'react';

interface HppPerKandangTabProps {
  tabId: string;
}

interface FilterParams {
  page?: number;
  pageSize?: number;
  area_id?: string;
  location_id?: string;
  kandang_id?: string;
  weight_min?: string;
  weight_max?: string;
  period?: string;
  sort_by?: string;
  show_unrecorded?: boolean;
}

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

  // ===== SUBMISSION STATE =====
  const [isSubmitted, setIsSubmitted] = useState(false);

  // ===== VALIDATION STATE =====
  const [weightMaxError, setWeightMaxError] = useState<string>('');
  const [dateErrorShown, setDateErrorShown] = useState(false);

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

  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: kandangOptions,
    isLoadingOptions: isLoadingKandangs,
    setInputValue: setKandangInputValue,
    loadMore: loadMoreKandang,
  } = useSelect(
    ProjectFlockKandangApi.basePath,
    'id',
    'name_with_period',
    'search'
  );

  const showUnrecordedOptions = useMemo(
    () => [
      { value: 'false', label: 'Sembunyikan' },
      { value: 'true', label: 'Tampilkan' },
    ],
    []
  );

  // ===== FORMIK SETUP =====
  const formik = useFormik<HppPerKandangFilterType>({
    initialValues: {
      page: 1,
      pageSize: 10,
      area_id: null,
      location_id: null,
      kandang_id: null,
      weight_min: null,
      weight_max: null,
      period: null,
      sort_by: null,
      show_unrecorded: false,
    },
    validationSchema: HppPerKandangFilterSchema,
    onSubmit: (values, { setSubmitting }) => {
      setFilterParams({
        page: values.page || undefined,
        pageSize: values.pageSize || undefined,
        area_id: values.area_id || undefined,
        location_id: values.location_id || undefined,
        kandang_id: values.kandang_id || undefined,
        weight_min: values.weight_min || undefined,
        weight_max: values.weight_max || undefined,
        period: values.period || undefined,
        sort_by: values.sort_by || undefined,
        show_unrecorded: values.show_unrecorded ?? undefined,
      });
      filterModal.closeModal();
      setIsSubmitted(true);
      setSubmitting(false);
    },
    onReset: () => {
      setFilterParams({});
      setIsSubmitted(false);
      setWeightMaxError('');
      if (dateErrorShown) {
        toast.dismiss();
        setDateErrorShown(false);
      }
      filterModal.closeModal();
    },
  });

  handleFilterModalOpenRef.current = () => {
    formik.setValues({
      page: formik.values.page,
      pageSize: formik.values.pageSize,
      area_id: filterParams.area_id || null,
      location_id: filterParams.location_id || null,
      kandang_id: filterParams.kandang_id || null,
      weight_min: filterParams.weight_min || null,
      weight_max: filterParams.weight_max || null,
      period: filterParams.period || null,
      sort_by: filterParams.sort_by || null,
      show_unrecorded: filterParams.show_unrecorded ?? false,
    });
    filterModal.openModal();
  };

  // ===== WEIGHT CHANGE HANDLERS =====
  const handleWeightMinChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value;
      formik.setFieldValue('weight_min', value || null);

      if (value && formik.values.weight_max) {
        const weightMin = parseFloat(value) || 0;
        const weightMax = parseFloat(formik.values.weight_max) || 0;

        if (weightMax < weightMin) {
          setWeightMaxError(
            'Rentang bobot max tidak boleh lebih kecil dari min'
          );
          if (!dateErrorShown) {
            toast.error('Rentang bobot max tidak boleh lebih kecil dari min', {
              duration: Infinity,
            });
            setDateErrorShown(true);
          }
        } else {
          setWeightMaxError('');
          if (dateErrorShown) {
            toast.dismiss();
            setDateErrorShown(false);
          }
        }
      } else {
        setWeightMaxError('');
      }
    },
    [formik, dateErrorShown]
  );

  const handleWeightMaxChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value;
      formik.setFieldValue('weight_max', value || null);

      if (value && formik.values.weight_min) {
        const weightMin = parseFloat(formik.values.weight_min) || 0;
        const weightMax = parseFloat(value) || 0;

        if (weightMax < weightMin) {
          setWeightMaxError(
            'Rentang bobot max tidak boleh lebih kecil dari min'
          );
          if (!dateErrorShown) {
            toast.error('Rentang bobot max tidak boleh lebih kecil dari min', {
              duration: Infinity,
            });
            setDateErrorShown(true);
          }
          return;
        }
      }

      setWeightMaxError('');
      if (dateErrorShown) {
        toast.dismiss();
        setDateErrorShown(false);
      }
    },
    [formik, dateErrorShown]
  );

  // ===== DERIVED VALUES =====
  const areaIdsValue = useMemo(() => {
    if (!formik.values.area_id) return [];
    const ids = formik.values.area_id.split(',');
    return areaOptions.filter((opt) => ids.includes(String(opt.value)));
  }, [formik.values.area_id, areaOptions]);

  const locationIdsValue = useMemo(() => {
    if (!formik.values.location_id) return [];
    const ids = formik.values.location_id.split(',');
    return locationOptions.filter((opt) => ids.includes(String(opt.value)));
  }, [formik.values.location_id, locationOptions]);

  const kandangIdsValue = useMemo(() => {
    if (!formik.values.kandang_id) return [];
    const ids = formik.values.kandang_id.split(',');
    return kandangOptions.filter((opt) => ids.includes(String(opt.value)));
  }, [formik.values.kandang_id, kandangOptions]);

  const showUnrecordedValue = useMemo(() => {
    if (formik.values.show_unrecorded === null) return null;
    return (
      showUnrecordedOptions.find(
        (opt) => opt.value === String(formik.values.show_unrecorded)
      ) || null
    );
  }, [formik.values.show_unrecorded, showUnrecordedOptions]);

  // ===== DATA FETCHING =====
  const { data: hppPerKandang, isLoading } = useSWR(
    isSubmitted
      ? () => {
          const params = {
            area_id: filterParams.area_id,
            location_id: filterParams.location_id,
            kandang_id: filterParams.kandang_id,
            weight_min: filterParams.weight_min,
            weight_max: filterParams.weight_max,
            period: filterParams.period,
            sort_by: filterParams.sort_by,
            show_unrecorded: filterParams.show_unrecorded,
            page: filterParams.page,
            pageSize: filterParams.pageSize,
          };

          return ['hpp-per-kandang-report', params];
        }
      : null,
    ([, params]) =>
      SaleReportApi.getHppPerKandangReport(
        params.area_id,
        params.location_id,
        params.kandang_id,
        params.weight_min,
        params.weight_max,
        params.period,
        params.sort_by,
        params.show_unrecorded,
        params.page,
        params.pageSize
      )
  );

  const data: HppPerKandangReport['rows'] = useMemo(
    () =>
      isResponseSuccess(hppPerKandang)
        ? (hppPerKandang?.data?.rows as HppPerKandangReport['rows']) || []
        : [],
    [hppPerKandang]
  );

  const summaryTotal =
    isResponseSuccess(hppPerKandang) && hppPerKandang?.data?.summary?.total
      ? hppPerKandang.data.summary.total
      : undefined;

  const perWeightRangeSummary = useMemo(
    () =>
      isResponseSuccess(hppPerKandang) &&
      hppPerKandang?.data?.summary?.per_weight_range
        ? hppPerKandang.data.summary.per_weight_range
        : [],
    [hppPerKandang]
  );

  // ===== EXPORT DATA FETCHER =====
  const hppPerKandangExport =
    useCallback(async (): Promise<HppPerKandangReport | null> => {
      const params = {
        area_id: filterParams.area_id,
        location_id: filterParams.location_id,
        kandang_id: filterParams.kandang_id,
        weight_min: filterParams.weight_min,
        weight_max: filterParams.weight_max,
        period: filterParams.period,
        sort_by: filterParams.sort_by,
        show_unrecorded: filterParams.show_unrecorded,
        limit: 10000,
        page: 1,
      };

      const response = await SaleReportApi.getHppPerKandangReport(
        params.area_id,
        params.location_id,
        params.kandang_id,
        params.weight_min,
        params.weight_max,
        params.period,
        params.sort_by,
        params.show_unrecorded,
        params.page,
        params.limit
      );

      return isResponseSuccess(response) ? response.data : null;
    }, [filterParams]);

  // ===== TABLE COLUMNS DEFINITION =====
  const allFeedSuppliers = useMemo(() => {
    const suppliers = new Set<string>();
    data.forEach((item: HppPerKandangRow) => {
      item.feed_suppliers?.forEach((s: { alias?: string; name: string }) => {
        suppliers.add(s.alias || s.name);
      });
    });
    return Array.from(suppliers).join(' | ');
  }, [data]);

  const allDocSuppliers = useMemo(() => {
    const suppliers = new Set<string>();
    data.forEach((item: HppPerKandangRow) => {
      item.doc_suppliers?.forEach((s: { alias?: string; name: string }) => {
        suppliers.add(s.alias || s.name);
      });
    });
    return Array.from(suppliers).join(' | ');
  }, [data]);

  // ===== EXPORT HANDLERS =====
  const handleExportExcel = useCallback(async () => {
    setIsExcelExportLoading(true);
    try {
      const allDataForExport = await hppPerKandangExport();

      if (
        !allDataForExport ||
        !allDataForExport?.rows ||
        allDataForExport.rows.length === 0
      ) {
        toast.error('Tidak ada data untuk diekspor.');
        return;
      }

      await generateHppPerKandangExcel({
        data: allDataForExport,
        allFeedSuppliers,
        allDocSuppliers,
      });
      toast.success('Excel berhasil dibuat dan diunduh.');
    } catch {
      toast.error('Gagal membuat Excel. Silakan coba lagi.');
    } finally {
      setIsExcelExportLoading(false);
    }
  }, [hppPerKandangExport, allFeedSuppliers, allDocSuppliers]);

  const handleExportPDF = useCallback(async () => {
    setIsPdfExportLoading(true);
    try {
      const allDataForExport = await hppPerKandangExport();

      if (
        !allDataForExport ||
        !allDataForExport?.rows ||
        allDataForExport.rows.length === 0
      ) {
        toast.error('Tidak ada data untuk diekspor.');
        return;
      }

      const areaName = filterParams.area_id
        ? areaOptions
            .filter((opt) =>
              filterParams.area_id?.split(',').includes(String(opt.value))
            )
            .map((opt) => opt.label)
            .join(', ') || 'Semua Area'
        : 'Semua Area';

      const locationName = filterParams.location_id
        ? locationOptions
            .filter((opt) =>
              filterParams.location_id?.split(',').includes(String(opt.value))
            )
            .map((opt) => opt.label)
            .join(', ') || 'Semua Lokasi'
        : 'Semua Lokasi';

      const kandangName = filterParams.kandang_id
        ? kandangOptions
            .filter((opt) =>
              filterParams.kandang_id?.split(',').includes(String(opt.value))
            )
            .map((opt) => opt.label)
            .join(', ') || 'Semua Kandang'
        : 'Semua Kandang';

      await generateHppPerKandangPDF(
        {
          data: allDataForExport,
          params: {
            area_name: areaName,
            location_name: locationName,
            kandang_name: kandangName,
            period: filterParams.period,
            weight_min: filterParams.weight_min,
            weight_max: filterParams.weight_max,
            show_unrecorded:
              filterParams.show_unrecorded?.toString() || 'false',
            sort_by: filterParams.sort_by,
          },
        },
        allFeedSuppliers,
        allDocSuppliers
      );

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

  // ===== 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'>
            <ButtonFilter
              values={filterParams}
              excludeFields={['page', 'pageSize']}
              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,
    isAnyExportLoading,
    handleExportExcel,
    handleExportPDF,
    isExcelExportLoading,
    isPdfExportLoading,
  ]);

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

  const getTableColumns = (): ColumnDef<HppPerKandangReport['rows'][0]>[] => {
    const tableColumns: ColumnDef<HppPerKandangReport['rows'][0]>[] = [
      {
        id: 'no',
        header: 'No',
        cell: (props) => props.row.index + 1,
        footer: () => <div className='font-semibold text-gray-900'>TOTAL</div>,
      },
      {
        id: 'kandang_name',
        header: 'Kandang',
        accessorKey: 'kandang.name',
        cell: (props) => {
          const row = props.row.original;
          return row.name_with_periode || row.kandang?.name || '-';
        },
        footer: () => <div className='font-semibold text-gray-900'>ALL</div>,
      },
      {
        id: 'weight_range',
        header: 'Rentang Bobot',
        accessorKey: 'weight_range',
        cell: (props) => {
          const weightRange = props.row.original.weight_range;
          return weightRange
            ? `${formatNumber(weightRange.weight_min)} - ${formatNumber(weightRange.weight_max)}`
            : '-';
        },
        footer: () => <div className='font-semibold text-gray-900'>-</div>,
      },
      {
        id: 'avg_weight_kg',
        header: 'Rata-Rata Bobot (KG)',
        accessorKey: 'avg_weight_kg',
        cell: (props) => {
          const value = props.row.original.avg_weight_kg;
          return <div className='text-right'>{formatNumber(value)}</div>;
        },
        footer: () => (
          <div className='text-right font-semibold text-gray-900'>
            {formatNumber(summaryTotal?.average_weight_kg || 0)}
          </div>
        ),
      },
      {
        id: 'egg_production_pieces',
        header: 'Sisa Telur (Butir)',
        accessorKey: 'egg_production_pieces',
        cell: (props) => {
          const value = props.row.original.egg_production_pieces;
          return <div className='text-right'>{formatNumber(value)}</div>;
        },
        footer: () => (
          <div className='text-right font-semibold text-gray-900'>
            {formatNumber(summaryTotal?.total_egg_production_pieces || 0)}
          </div>
        ),
      },
      {
        id: 'egg_production_kg',
        header: 'Sisa Telur (KG)',
        accessorKey: 'egg_production_kg',
        cell: (props) => {
          const value = props.row.original.egg_production_kg;
          return <div className='text-right'>{formatNumber(value)}</div>;
        },
        footer: () => (
          <div className='text-right font-semibold text-gray-900'>
            {formatNumber(summaryTotal?.total_egg_production_kg || 0)}
          </div>
        ),
      },
      {
        id: 'feed_suppliers',
        header: 'Feed (Supplier)',
        accessorKey: 'feed_suppliers',
        cell: (props) => {
          const suppliers = props.row.original.feed_suppliers;
          return (
            suppliers
              ?.map((s: { alias?: string; name: string }) => s.alias || s.name)
              .join(' | ') || '-'
          );
        },
        footer: () => (
          <div className='font-semibold text-gray-900'>
            {allFeedSuppliers || '-'}
          </div>
        ),
      },
      {
        id: 'doc_suppliers',
        header: 'DOC (Supplier)',
        accessorKey: 'doc_suppliers',
        cell: (props) => {
          const suppliers = props.row.original.doc_suppliers;
          return (
            suppliers
              ?.map((s: { alias?: string; name: string }) => s.alias || s.name)
              .join(' | ') || '-'
          );
        },
        footer: () => (
          <div className='font-semibold text-gray-900'>
            {allDocSuppliers || '-'}
          </div>
        ),
      },
      {
        id: 'average_doc_price_rp',
        header: 'Rata-Rata Harga DOC (RP)',
        accessorKey: 'average_doc_price_rp',
        cell: (props) => {
          const value = props.row.original.average_doc_price_rp;
          return <div className='text-right'>{formatCurrency(value)}</div>;
        },
        footer: () => (
          <div className='text-right font-semibold text-gray-900'>
            {formatCurrency(summaryTotal?.total_average_doc_price_rp || 0)}
          </div>
        ),
      },
      {
        id: 'egg_hpp_rp_per_kg',
        header: 'HPP Telur (RP/KG)',
        accessorKey: 'egg_hpp_rp_per_kg',
        cell: (props) => {
          const value = props.row.original.egg_hpp_rp_per_kg;
          return <div className='text-right'>{formatCurrency(value)}</div>;
        },
        footer: () => (
          <div className='text-right font-semibold text-gray-900'>
            {formatCurrency(summaryTotal?.average_egg_hpp_rp_per_kg || 0)}
          </div>
        ),
      },
      {
        id: 'egg_value_rp',
        header: 'Nilai Nominal Sisa Telur (RP)',
        accessorKey: 'egg_value_rp',
        cell: (props) => {
          const value = props.row.original.egg_value_rp;
          return <div className='text-right'>{formatCurrency(value)}</div>;
        },
        footer: () => (
          <div className='text-right font-semibold text-gray-900'>
            {formatCurrency(summaryTotal?.total_egg_value_rp || 0)}
          </div>
        ),
      },
    ];
    return tableColumns;
  };

  // ===== CUSTOM ROW RENDERER =====
  const renderCustomRow = useCallback(
    (row: Row<HppPerKandangReport['rows'][0]>) => {
      if (row.index === data.length - 1) {
        const defaultRow = (
          <tr
            key={row.id}
            className='hover:bg-gray-50 transition-colors border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200'
          >
            {row.getVisibleCells().map((cell) => (
              <td
                key={cell.id}
                className='px-4 py-3 text-xs text-gray-900 whitespace-nowrap  border-gray-200'
              >
                {flexRender(cell.column.columnDef.cell, cell.getContext())}
              </td>
            ))}
          </tr>
        );

        const customRows = [
          <tr
            className='border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200'
            key={'rekapitulasi-row'}
          >
            <td
              colSpan={11}
              className='px-4 py-3 text-gray-900 text-center font-semibold'
            >
              Rekapitulasi per rentang bobot
            </td>
          </tr>,
        ];

        if (perWeightRangeSummary.length > 0) {
          perWeightRangeSummary.forEach(
            (item: HppPerKandangPerWeightRange, index = 0) => {
              customRows.push(
                <tr
                  key={`summary-${item.id}`}
                  className='hover:bg-gray-50 transition-colors border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200 [&_td]:px-4 [&_td]:py-3 [&_td]:text-xs [&_td]:text-gray-900 [&_td]:whitespace-nowrap'
                >
                  <td className=''>{index + 1}</td>
                  <td className=''>ALL</td>
                  <td className=''>{item.label}</td>
                  <td className='text-right'>
                    {formatNumber(item.avg_weight_kg)}
                  </td>
                  <td className='text-right'>
                    {formatNumber(item.egg_production_pieces)}
                  </td>
                  <td className='text-right'>
                    {formatNumber(item.egg_production_kg)}
                  </td>
                  <td className=''>
                    {item.feed_suppliers
                      ?.map((s) => s.alias || s.name)
                      .join(' | ') || '-'}
                  </td>
                  <td className=''>
                    {item.doc_suppliers
                      ?.map((s) => s.alias || s.name)
                      .join(' | ') || '-'}
                  </td>
                  <td className='text-right'>
                    {formatCurrency(item.average_doc_price_rp)}
                  </td>
                  <td className='text-right'>
                    {formatCurrency(item.egg_hpp_rp_per_kg)}
                  </td>
                  <td className='text-right'>
                    {formatCurrency(item.egg_value_rp)}
                  </td>
                </tr>
              );
            }
          );
        }

        return [defaultRow, ...customRows];
      }

      return null;
    },
    [data, perWeightRangeSummary]
  );

  useEffectHook(() => {
    filterModal.openModal();
  }, []);

  return (
    <>
      {TabActionsElement}
      <div className='w-full p-0 sm:p-3 flex flex-col gap-3'>
        {!isSubmitted ? (
          <HppPerKandangSkeleton
            columns={getTableColumns()}
            icon={
              <Icon
                icon='heroicons:funnel'
                className='text-white'
                width={20}
                height={20}
              />
            }
            title='No Filters Selected'
            subtitle='Please choose filters to narrow down your results and make your search easier.'
          />
        ) : isLoading ? (
          <HppPerKandangSkeleton
            columns={getTableColumns()}
            icon={
              <Icon
                icon='heroicons:document-report'
                className='text-white'
                width={20}
                height={20}
              />
            }
            title='Memuat Data HPP Per Kandang'
            subtitle='Silakan tunggu sebentar...'
          />
        ) : data.length === 0 ? (
          <HppPerKandangSkeleton
            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.'
          />
        ) : (
          <Table
            data={data}
            columns={getTableColumns()}
            pageSize={filterParams.pageSize}
            page={
              isResponseSuccess(hppPerKandang) ? hppPerKandang?.meta?.page : 0
            }
            totalItems={
              isResponseSuccess(hppPerKandang)
                ? hppPerKandang?.meta?.total_results
                : 0
            }
            onPageChange={(newPage) =>
              setFilterParams((prevVal) => ({ ...prevVal, page: newPage }))
            }
            onPageSizeChange={(newPageSize) =>
              setFilterParams((prevVal) => ({
                ...prevVal,
                pageSize: newPageSize,
              }))
            }
            isLoading={isLoading}
            renderFooter={data.length > 0}
            renderCustomRow={renderCustomRow}
            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',
              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'>
            {/* Period Filter */}
            <div>
              <DateInput
                label='Periode'
                name='period'
                value={formik.values.period || ''}
                onChange={(e) => {
                  formik.setFieldValue('period', e.target.value || null);
                }}
                className={{ wrapper: 'w-full' }}
                isNestedModal
                required={true}
                isError={!!formik.errors.period && formik.touched.period}
              />
              {formik.errors.period && formik.touched.period && (
                <div className='text-error text-xs mt-1'>
                  {formik.errors.period}
                </div>
              )}
            </div>

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

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

            {/* Kandang Filter */}
            <SelectInputCheckbox
              label='Kandang'
              placeholder='Pilih Kandang'
              options={kandangOptions}
              value={kandangIdsValue}
              onChange={(val) => {
                formik.setFieldValue(
                  'kandang_id',
                  Array.isArray(val) && val.length > 0
                    ? val.map((v) => String(v.value)).join(',')
                    : null
                );
              }}
              isLoading={isLoadingKandangs}
              isClearable
              className={{ wrapper: 'w-full' }}
              onInputChange={setKandangInputValue}
              onMenuScrollToBottom={loadMoreKandang}
            />

            {/* Weight Range Filter */}
            <div>
              <label className='block text-xs font-semibold text-base-content py-2'>
                Rentang Bobot (Kg)
              </label>
              <div className='flex flex-row gap-1.5 items-center justify-between'>
                <NumberInput
                  name='weight_min'
                  placeholder='Min'
                  value={formik.values.weight_min || ''}
                  onChange={handleWeightMinChange}
                  className={{ wrapper: 'w-full' }}
                />
                <hr className='w-full max-w-3 h-px border-base-content/10' />
                <NumberInput
                  name='weight_max'
                  placeholder='Max'
                  value={formik.values.weight_max || ''}
                  onChange={handleWeightMaxChange}
                  isError={!!weightMaxError}
                  errorMessage={weightMaxError}
                  className={{ wrapper: 'w-full' }}
                />
              </div>
            </div>

            {/* Show Unrecorded Filter */}
            <SelectInputRadio
              label='Tampilkan Kandang Tanpa Recording'
              placeholder='Pilih Opsi'
              options={showUnrecordedOptions}
              value={showUnrecordedValue}
              onChange={(val) => {
                if (!Array.isArray(val)) {
                  formik.setFieldValue(
                    'show_unrecorded',
                    val?.value === 'true'
                      ? true
                      : val?.value === 'false'
                        ? false
                        : null
                  );
                }
              }}
              className={{ wrapper: 'w-full' }}
              isClearable={true}
            />
          </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={!!weightMaxError || formik.isSubmitting}
            >
              Apply Filter
            </Button>
          </div>
        </form>
      </Modal>
    </>
  );
};

export default HppPerKandangTab;
