'use client';

import React, { useCallback, useState, useEffect, useMemo } from 'react';
import { useRouter, useSearchParams, usePathname } from 'next/navigation';
import { useUiStore } from '@/stores/ui/ui.store';
import useSWR from 'swr';
import { Icon } from '@iconify/react';
import { ColumnDef, SortingState } from '@tanstack/react-table';
import { cn, formatDate } from '@/lib/helper';
import Button from '@/components/Button';
import UniformityChart from '@/components/pages/production/uniformity/UniformityChart';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { UniformityApi } from '@/services/api/uniformity';
import {
  DetailOptionType,
  type Uniformity,
  type UniformityDetail,
} from '@/types/api/production/uniformity';
import { isResponseSuccess } from '@/lib/api-helper';
import { type BaseApiResponse } from '@/types/api/api-general';
import Table from '@/components/Table';
import StatusBadge from '@/components/helper/StatusBadge';
import CheckboxInput from '@/components/input/CheckboxInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import toast from 'react-hot-toast';
import UniformityTableSkeleton from '@/components/pages/production/uniformity/skeleton/UniformityTableSkeleton';
import RequirePermission from '@/components/helper/RequirePermission';
import { useUniformityStore } from '@/stores/production/uniformity/uniformity.store';
import FloatingActionsButton from '@/components/FloatingActionsButton';
import Modal from '@/components/Modal';
import SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import DateInput from '@/components/input/DateInput';
import { LocationApi } from '@/services/api/master-data';
import { ProjectFlockApi } from '@/services/api/production';
import { Kandang } from '@/types/api/master-data/kandang';
import {
  ProjectFlockKandangLookup,
  ProjectFlock,
} from '@/types/api/production/project-flock';
import {
  getStatusText,
  getStatusBadgeColor,
} from '@/components/pages/production/uniformity/uniformity-utils';
import { generateUniformityPDF } from '@/components/pages/production/uniformity/export/UniformityExportPDF';
import { generateUniformityExcel } from '@/components/pages/production/uniformity/export/UniformityExportExcel';
import Dropdown from '@/components/Dropdown';
import ButtonFilter from '@/components/helper/ButtonFilter';
import { useFormik } from 'formik';
import {
  UniformityTableFilterSchema,
  type UniformityTableFilterValues,
} from '@/components/pages/production/uniformity/filter/UniformityTableFilter';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';

const UniformityConfirmationPreview = ({
  uniformity,
  uniformityDetail,
}: {
  uniformity?: Uniformity;
  uniformityDetail?: UniformityDetail;
}) => {
  const data: DetailOptionType[] = [
    {
      id: 'tanggal',
      label: 'Tanggal',
      value: uniformity
        ? formatDate(uniformity.applied_at, 'DD MMM YYYY')
        : uniformityDetail
          ? formatDate(uniformityDetail.info_umum.tanggal, 'DD MMM YYYY')
          : '-',
    },
    {
      id: 'lokasi-farm',
      label: 'Lokasi Farm',
      value:
        uniformity?.location_name ||
        uniformityDetail?.info_umum?.lokasi_farm ||
        '-',
    },
    {
      id: 'project-flock',
      label: 'Project Flock',
      value:
        uniformity?.flock_name ||
        uniformityDetail?.info_umum?.project_flock ||
        '-',
    },
    {
      id: 'kandang',
      label: 'Kandang',
      value:
        uniformity?.kandang_name || uniformityDetail?.info_umum?.kandang || '-',
    },
    {
      id: 'file-uniformity',
      label: 'File Uniformity',
      value:
        uniformity?.file_name || uniformityDetail?.info_umum?.file_name || '-',
    },
    {
      id: 'status',
      label: 'Status',
      value: uniformity?.status || (uniformityDetail ? 'CREATED' : '-'),
    },
  ];

  const columns: ColumnDef<DetailOptionType>[] = [
    {
      accessorKey: 'label',
      enableSorting: false,
      header: () => (
        <span className='font-medium text-sm leading-[150%]'>Label</span>
      ),
      cell: (props) => props.row.original.label,
    },
    {
      accessorKey: 'value',
      enableSorting: false,
      header: () => (
        <span className='font-medium text-sm leading-[150%]'>Value</span>
      ),
      cell: (props) => {
        const id = props.row.original.id;
        const value = props.row.original.value;

        if (id === 'status') {
          return (
            <div className='w-full'>
              <StatusBadge
                color={getStatusBadgeColor(value)}
                text={getStatusText(value)}
              />
            </div>
          );
        }

        return <span>{value}</span>;
      },
    },
  ];

  return (
    <Table
      data={data}
      columns={columns}
      pageSize={6}
      className={{
        containerClassName: 'mb-0',
        paginationClassName: 'hidden',
      }}
    />
  );
};

const UniformityChartWrapper = ({
  uniformitySwrKey,
  isFiltered,
}: {
  uniformitySwrKey: string;
  isFiltered: boolean;
}) => {
  const { data: uniformities } = useSWR(
    uniformitySwrKey,
    UniformityApi.getAllFetcher
  );

  const uniformityData = useMemo(() => {
    if (isResponseSuccess(uniformities) && uniformities?.data?.length > 0) {
      return uniformities.data[0];
    }
    return null;
  }, [uniformities]);

  return (
    <UniformityChart uniformityData={uniformityData} isFiltered={isFiltered} />
  );
};

const UniformityTable = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const { searchValue, setTableState } = useUiStore();
  const isSuccess = useUniformityStore((s) => s.isSuccess);
  const setIsSuccess = useUniformityStore((s) => s.setIsSuccess);
  const createdUniformity = useUniformityStore((s) => s.createdUniformity);
  const setCreatedUniformity = useUniformityStore(
    (s) => s.setCreatedUniformity
  );

  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      search: '',
      start_date: '',
      end_date: '',
      location_id: '',
      project_flock_id: '',
      kandang_id: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      search: 'search',
      start_date: 'start_date',
      end_date: 'end_date',
      location_id: 'location_id',
      project_flock_id: 'project_flock_id',
      kandang_id: 'kandang_id',
    },
  });

  useEffect(() => {
    updateFilter('search', searchValue);
  }, [searchValue, updateFilter]);

  useEffect(() => {
    setTableState('uniformity-table', pathname);
  }, [pathname, setTableState]);

  const [sorting, setSorting] = useState<SortingState>([]);
  const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
  const [selectedUniformity, setSelectedUniformity] = useState<
    Uniformity | undefined
  >(undefined);
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);
  const [isBulkActionLoading, setIsBulkActionLoading] = useState(false);
  const [isPdfExportLoading, setIsPdfExportLoading] = useState(false);
  const [isExcelExportLoading, setIsExcelExportLoading] = useState(false);

  const singleDeleteModal = useModal();
  const successModal = useModal();
  const singleApproveModal = useModal();
  const singleRejectModal = useModal();
  const bulkApproveModal = useModal();
  const bulkRejectModal = useModal();
  const filterModal = useModal();

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

  // ===== FILTER STATE =====
  const [filterDateValues, setFilterDateValues] = useState({
    start_date: tableFilterState.start_date,
    end_date: tableFilterState.end_date,
  });
  const [filterLocation, setFilterLocation] = useState<OptionType | null>(null);
  const [filterProjectFlock, setFilterProjectFlock] =
    useState<OptionType | null>(null);
  const [filterKandang, setFilterKandang] = useState<OptionType | null>(null);
  const [filterProjectFlockKandangId, setFilterProjectFlockKandangId] =
    useState<number | undefined>(undefined);
  const [filterProjectFlockLocationId, setFilterProjectFlockLocationId] =
    useState<string>('');
  const [, setFilterErrors] = useState<Record<string, string>>({});

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

  const {
    setInputValue: setFilterLocationInputValue,
    options: filterLocationOptions,
    isLoadingOptions: isLoadingFilterLocations,
    loadMore: loadMoreFilterLocations,
  } = useSelect(LocationApi.basePath, 'id', 'name', 'search');

  // ===== FETCH PROJECT FLOCKS DATA FOR FILTER =====
  const {
    setInputValue: setFilterProjectFlockSearchValue,
    options: filterProjectFlockOptions,
    rawData: filterProjectFlocksRawData,
    isLoadingOptions: isLoadingFilterProjectFlocks,
    loadMore: loadMoreFilterProjectFlocks,
  } = useSelect(ProjectFlockApi.basePath, 'id', 'flock_name', 'search', {
    location_id: filterProjectFlockLocationId,
  });

  // ===== KANDANG OPTIONS FOR FILTER =====
  const filterKandangOptions = useMemo(() => {
    let options: OptionType[] = [];

    if (filterProjectFlock && isResponseSuccess(filterProjectFlocksRawData)) {
      const data = filterProjectFlocksRawData.data as unknown as ProjectFlock[];
      const selectedProjectFlockData = data.find(
        (pf) => pf.id === filterProjectFlock.value
      );

      if (selectedProjectFlockData?.kandangs) {
        const kandangOpts = selectedProjectFlockData.kandangs.map(
          (kandang: Kandang) => ({
            value: kandang.id,
            label: kandang.name || '',
          })
        );
        options = options.concat(kandangOpts);
      }
    }

    return options;
  }, [filterProjectFlock, filterProjectFlocksRawData]);

  // ===== PROJECT FLOCK KANDANG LOOKUP =====
  const projectFlockKandangLookupUrl = useMemo(() => {
    if (!filterProjectFlock || !filterKandang) return null;
    const params = new URLSearchParams({
      project_flock_id: filterProjectFlock.value.toString(),
      kandang_id: filterKandang.value.toString(),
      withpopulation: Boolean(true).toString(),
      limit: '100',
    });
    return `${ProjectFlockApi.basePath}/kandangs/lookup?${params.toString()}`;
  }, [filterProjectFlock, filterKandang]);

  const { data: projectFlockKandangLookupData } = useSWR(
    projectFlockKandangLookupUrl,
    projectFlockKandangLookupUrl
      ? () =>
          ProjectFlockApi.getAllFetcher(
            projectFlockKandangLookupUrl
          ) as Promise<BaseApiResponse<ProjectFlockKandangLookup>>
      : null
  );

  const projectFlockKandangLookup =
    projectFlockKandangLookupData?.status === 'success'
      ? projectFlockKandangLookupData.data
      : undefined;

  useEffect(() => {
    if (projectFlockKandangLookup?.id) {
      setFilterProjectFlockKandangId(projectFlockKandangLookup.id);
    } else {
      setFilterProjectFlockKandangId(undefined);
    }
  }, [projectFlockKandangLookup]);

  // ===== FORMIK FILTER =====
  const filterFormik = useFormik<UniformityTableFilterValues>({
    initialValues: {
      start_date: filterDateValues.start_date,
      end_date: filterDateValues.end_date,
      location: filterLocation,
      project_flock: filterProjectFlock,
      project_flock_kandang_id: filterProjectFlockKandangId,
      kandang: filterKandang,
    },
    validationSchema: UniformityTableFilterSchema,
    enableReinitialize: true,
    onSubmit: async (values) => {
      updateFilter('start_date', values.start_date);
      updateFilter('end_date', values.end_date);
      updateFilter(
        'location_id',
        values.location?.value ? String(values.location.value) : ''
      );
      updateFilter(
        'project_flock_id',
        values.project_flock?.value ? String(values.project_flock.value) : ''
      );
      updateFilter(
        'kandang_id',
        values.kandang?.value ? String(values.kandang.value) : ''
      );

      setFilterLocation(values.location ?? null);
      setFilterProjectFlock(values.project_flock ?? null);
      setFilterKandang(values.kandang ?? null);

      setIsSubmitted(true);
      filterModal.closeModal();
    },
  });

  // ===== FORMIK ERROR LIST =====
  const { formErrorList, close, handleFormSubmit } =
    useFormikErrorList(filterFormik);

  useEffect(() => {
    setFilterDateValues({
      start_date: tableFilterState.start_date,
      end_date: tableFilterState.end_date,
    });
  }, [tableFilterState.start_date, tableFilterState.end_date]);

  // ===== BUILD SWR KEY WITH FILTERS =====
  const uniformitySwrKey = useMemo(() => {
    const basePath = UniformityApi.basePath;
    const queryParams = new URLSearchParams();

    if (isSubmitted) {
      if (filterProjectFlockKandangId) {
        queryParams.append(
          'project_flock_kandang_id',
          filterProjectFlockKandangId.toString()
        );
      }
      if (tableFilterState.start_date) {
        queryParams.append('start_date', tableFilterState.start_date);
      }
      if (tableFilterState.end_date) {
        queryParams.append('end_date', tableFilterState.end_date);
      }
      queryParams.append('with_chart', 'true');
    }

    const tableQueryString = getTableFilterQueryString();
    const tableParams = new URLSearchParams(
      tableQueryString.split('?')[1] || ''
    );

    tableParams.forEach((value, key) => {
      queryParams.append(key, value);
    });

    const queryString = queryParams.toString();
    return queryString ? `${basePath}?${queryString}` : basePath;
  }, [
    isSubmitted,
    filterProjectFlockKandangId,
    tableFilterState.start_date,
    tableFilterState.end_date,
    getTableFilterQueryString,
  ]);

  const {
    data: uniformities,
    isLoading,
    mutate: refreshUniformities,
  } = useSWR(uniformitySwrKey, UniformityApi.getAllFetcher);

  useEffect(() => {
    if (isSuccess) {
      refreshUniformities();
    }
  }, [isSuccess, refreshUniformities]);

  // ===== FILTER HANDLERS =====
  const handleFilterLocationChange = useCallback(
    (val: OptionType | OptionType[] | null) => {
      const location = val as OptionType | null;
      const locationId = Number(location?.value) || 0;

      filterFormik.setFieldValue('location', location);
      filterFormik.setFieldValue('location_id', locationId);

      setFilterLocation(location);
      setFilterProjectFlock(null);
      setFilterKandang(null);
      setFilterProjectFlockLocationId(
        location ? location.value.toString() : ''
      );

      filterFormik.setFieldValue('project_flock', null);
      filterFormik.setFieldValue('project_flock_id', 0);
      filterFormik.setFieldValue('kandang', null);
      filterFormik.setFieldValue('kandang_id', 0);
    },
    [filterFormik]
  );

  const handleFilterProjectFlockChange = useCallback(
    (val: OptionType | OptionType[] | null) => {
      const projectFlock = val as OptionType | null;
      const projectFlockId = Number(projectFlock?.value) || 0;

      filterFormik.setFieldValue('project_flock', projectFlock);
      filterFormik.setFieldValue('project_flock_id', projectFlockId);

      setFilterProjectFlock(projectFlock);
      setFilterKandang(null);

      filterFormik.setFieldValue('kandang', null);
      filterFormik.setFieldValue('kandang_id', 0);
    },
    [filterFormik]
  );

  const handleFilterKandangChange = useCallback(
    (val: OptionType | OptionType[] | null) => {
      const kandang = val as OptionType | null;
      const kandangId = Number(kandang?.value) || 0;

      filterFormik.setFieldValue('kandang', kandang);
      filterFormik.setFieldValue('kandang_id', kandangId);

      setFilterKandang(kandang);
    },
    [filterFormik]
  );

  const handleResetFilters = useCallback(() => {
    setIsSubmitted(false);
    setFilterLocation(null);
    setFilterProjectFlock(null);
    setFilterKandang(null);
    setFilterProjectFlockKandangId(undefined);
    setFilterErrors({});
    setFilterDateValues({ start_date: '', end_date: '' });

    updateFilter('start_date', '');
    updateFilter('end_date', '');
    updateFilter('location_id', '');
    updateFilter('project_flock_id', '');
    updateFilter('kandang_id', '');

    filterFormik.resetForm();
    filterModal.closeModal();
  }, [filterFormik, updateFilter, filterModal]);

  const selectedRowIds = useMemo(() => {
    return Object.keys(rowSelection)
      .filter((key) => rowSelection[key])
      .map((key) => parseInt(key));
  }, [rowSelection]);

  const selectedUniformities = useMemo(() => {
    if (!isResponseSuccess(uniformities) || !uniformities.data) return [];
    return uniformities.data.filter((u) => selectedRowIds.includes(u.id));
  }, [uniformities, selectedRowIds]);

  const canApproveReject = useMemo(() => {
    return (
      selectedUniformities.length > 0 &&
      selectedUniformities.every((u) => {
        const approvalAction = u.latest_approval?.action;
        return (
          approvalAction === 'CREATED' ||
          approvalAction === 'Pengajuan' ||
          (!approvalAction &&
            (u.status === 'CREATED' || u.status === 'Pengajuan'))
        );
      })
    );
  }, [selectedUniformities]);

  useEffect(() => {
    const action = searchParams.get('action');
    const id = searchParams.get('id');

    if (action && id) {
      if (isResponseSuccess(uniformities)) {
        const uniformity = uniformities.data.find((u) => u.id === parseInt(id));
        if (uniformity) {
          setSelectedUniformity(uniformity);

          if (action === 'approve') {
            singleApproveModal.openModal();
          } else if (action === 'reject') {
            singleRejectModal.openModal();
          }

          router.replace('/production/uniformity', { scroll: false });
        }
      }
    }
  }, [
    searchParams,
    uniformities,
    router,
    singleApproveModal,
    singleRejectModal,
  ]);

  useEffect(() => {
    if (isSuccess) {
      successModal.openModal();
    }
  }, [isSuccess, successModal]);

  const handleSuccessModalClose = () => {
    successModal.closeModal();
    setIsSuccess(false);
    setCreatedUniformity(null);
  };

  const singleDeleteHandler = useCallback(async () => {
    setIsDeleteLoading(true);

    await UniformityApi.delete(selectedUniformity?.id as number);
    refreshUniformities();

    singleDeleteModal.closeModal();
    toast.success('Successfully delete Uniformity!');
    setIsDeleteLoading(false);
  }, [selectedUniformity?.id, refreshUniformities, singleDeleteModal]);

  const singleApproveHandler = useCallback(async () => {
    setIsDeleteLoading(true);

    try {
      await UniformityApi.approve([selectedUniformity?.id as number]);
      refreshUniformities();

      singleApproveModal.closeModal();
      toast.success('Successfully approved Uniformity!');
    } catch {
      toast.error('Failed to approve Uniformity');
    } finally {
      setIsDeleteLoading(false);
    }
  }, [selectedUniformity?.id, refreshUniformities, singleApproveModal]);

  const singleRejectHandler = useCallback(async () => {
    setIsDeleteLoading(true);

    try {
      await UniformityApi.reject([selectedUniformity?.id as number]);
      refreshUniformities();

      singleRejectModal.closeModal();
      toast.success('Successfully rejected Uniformity!');
    } catch {
      toast.error('Failed to reject Uniformity');
    } finally {
      setIsDeleteLoading(false);
    }
  }, [selectedUniformity?.id, refreshUniformities, singleRejectModal]);

  const handleCloseFab = useCallback(() => {
    setRowSelection({});
  }, []);

  const handleDelete = useCallback(() => {
    if (selectedRowIds.length === 1) {
      const uniformity = selectedUniformities[0];
      setSelectedUniformity(uniformity);
      singleDeleteModal.openModal();
    }
  }, [selectedRowIds, selectedUniformities, singleDeleteModal]);

  const handleBulkApprove = useCallback(() => {
    if (selectedRowIds.length === 1) {
      setSelectedUniformity(selectedUniformities[0]);
    }
    bulkApproveModal.openModal();
  }, [bulkApproveModal, selectedRowIds, selectedUniformities]);

  const handleBulkReject = useCallback(() => {
    if (selectedRowIds.length === 1) {
      setSelectedUniformity(selectedUniformities[0]);
    }
    bulkRejectModal.openModal();
  }, [bulkRejectModal, selectedRowIds, selectedUniformities]);

  const bulkApproveHandler = useCallback(async () => {
    setIsBulkActionLoading(true);

    try {
      await UniformityApi.approve(selectedRowIds);

      setRowSelection({});
      refreshUniformities();

      bulkApproveModal.closeModal();
      toast.success(
        `Successfully approved ${selectedRowIds.length} Uniformity data!`
      );
    } catch {
      toast.error('Failed to approve Uniformity data');
    } finally {
      setIsBulkActionLoading(false);
    }
  }, [selectedRowIds, refreshUniformities, bulkApproveModal]);

  const bulkRejectHandler = useCallback(async () => {
    setIsBulkActionLoading(true);

    try {
      await UniformityApi.reject(selectedRowIds);

      setRowSelection({});
      refreshUniformities();

      bulkRejectModal.closeModal();
      toast.success(
        `Successfully rejected ${selectedRowIds.length} Uniformity data!`
      );
    } catch {
      toast.error('Failed to reject Uniformity data');
    } finally {
      setIsBulkActionLoading(false);
    }
  }, [selectedRowIds, refreshUniformities, bulkRejectModal]);

  // ===== EXPORT HANDLERS =====
  const uniformityExport = useCallback(async (): Promise<
    Uniformity[] | null
  > => {
    const queryParams = new URLSearchParams();

    if (filterProjectFlockKandangId) {
      queryParams.append(
        'project_flock_kandang_id',
        filterProjectFlockKandangId.toString()
      );
    }
    if (tableFilterState.start_date) {
      queryParams.append('start_date', tableFilterState.start_date);
    }
    if (tableFilterState.end_date) {
      queryParams.append('end_date', tableFilterState.end_date);
    }
    queryParams.append('limit', '100');
    queryParams.append('page', '1');

    const queryString = queryParams.toString();
    const url = `${UniformityApi.basePath}${queryString ? `?${queryString}` : ''}`;

    const response = await UniformityApi.getAllFetcher(url);

    return isResponseSuccess(response) ? response.data : null;
  }, [
    filterProjectFlockKandangId,
    tableFilterState.start_date,
    tableFilterState.end_date,
  ]);

  const handleExportExcel = useCallback(async () => {
    setIsExcelExportLoading(true);
    try {
      const allDataForExport = await uniformityExport();

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

      const locationName = filterLocation?.label || 'Semua Lokasi';
      const projectFlockName =
        filterProjectFlock?.label || 'Semua Project Flock';
      const kandangName = filterKandang?.label || 'Semua Kandang';

      generateUniformityExcel(allDataForExport, {
        location_name: locationName,
        project_flock_name: projectFlockName,
        kandang_name: kandangName,
        start_date: tableFilterState.start_date,
        end_date: tableFilterState.end_date,
      });

      toast.success('Excel berhasil dibuat dan diunduh.');
    } catch {
      toast.error('Gagal membuat Excel. Silakan coba lagi.');
    } finally {
      setIsExcelExportLoading(false);
    }
  }, [
    uniformityExport,
    filterLocation,
    filterProjectFlock,
    filterKandang,
    tableFilterState.start_date,
    tableFilterState.end_date,
  ]);

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

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

      const locationName = filterLocation?.label || 'Semua Lokasi';
      const projectFlockName =
        filterProjectFlock?.label || 'Semua Project Flock';
      const kandangName = filterKandang?.label || 'Semua Kandang';

      await generateUniformityPDF(allDataForExport, {
        location_name: locationName,
        project_flock_name: projectFlockName,
        kandang_name: kandangName,
        start_date: tableFilterState.start_date,
        end_date: tableFilterState.end_date,
      });

      toast.success('PDF berhasil dibuat dan diunduh.');
    } catch {
      toast.error('Gagal membuat PDF. Silakan coba lagi.');
    } finally {
      setIsPdfExportLoading(false);
    }
  }, [
    uniformityExport,
    filterLocation,
    filterProjectFlock,
    filterKandang,
    tableFilterState.start_date,
    tableFilterState.end_date,
  ]);

  useEffect(() => {
    if (isResponseSuccess(uniformities) && uniformities.data) {
      const newSelection: Record<string, boolean> = {};

      Object.entries(rowSelection).forEach(([rowId, isSelected]) => {
        if (isSelected) {
          const uniformity = uniformities.data.find(
            (r) => r.id === parseInt(rowId)
          );
          if (uniformity) {
            newSelection[rowId] = true;
          }
        }
      });

      if (
        Object.keys(newSelection).length !== Object.keys(rowSelection).length
      ) {
        setRowSelection(newSelection);
      }
    }
  }, [uniformities, rowSelection]);

  useEffect(() => {
    return () => {
      if (dateErrorShown) {
        toast.dismiss();
      }
    };
  }, [dateErrorShown]);

  useEffect(() => {
    return () => {
      if (dateErrorShown) {
        toast.dismiss();
        setDateErrorShown(false);
      }
    };
  }, [filterModal.open, dateErrorShown]);

  // ===== TABLE COLUMNS DEFINITION =====
  const uniformityColumns: ColumnDef<Uniformity>[] = useMemo(
    () => [
      {
        id: 'select',
        header: ({ table }) => {
          const allRows = table.getRowModel().rows;
          const selectableRows = allRows;

          const hasNoSelectableRows = selectableRows.length === 0;

          const handleSelectAll = () => {
            const isAllSelected = selectableRows.every((row) =>
              row.getIsSelected()
            );

            selectableRows.forEach((row) => {
              row.toggleSelected(!isAllSelected);
            });
          };

          const isAllSelected =
            selectableRows.length > 0 &&
            selectableRows.every((row) => row.getIsSelected());

          const isSomeSelected = selectableRows.some((row) =>
            row.getIsSelected()
          );

          return (
            <div className='w-full flex flex-row xl:justify-center justify-end'>
              <CheckboxInput
                name='allRow'
                checked={isAllSelected}
                indeterminate={isSomeSelected && !isAllSelected}
                onChange={handleSelectAll}
                disabled={hasNoSelectableRows}
              />
            </div>
          );
        },
        cell: ({ row }) => {
          return (
            <div className='w-full flex flex-row xl:justify-center justify-end'>
              <CheckboxInput
                name='row'
                checked={row.getIsSelected()}
                indeterminate={row.getIsSomeSelected()}
                onChange={row.getToggleSelectedHandler()}
                disabled={false}
              />
            </div>
          );
        },
      },
      {
        accessorKey: 'location_name',
        header: 'Lokasi',
        cell: (props) => props.row.original.location_name || '-',
      },
      {
        accessorKey: 'flock_name',
        header: 'Flock',
        cell: (props) => props.row.original.flock_name || '-',
      },
      {
        accessorKey: 'kandang_name',
        header: 'Kandang',
        cell: (props) => props.row.original.kandang_name || '-',
      },
      {
        accessorKey: 'week',
        header: 'Tanggal (Week)',
        cell: (props) => (
          <span className='text-nowrap'>
            {`${formatDate(props.row.original.applied_at, 'DD MMM YYYY')} (${props.row.original.week})`}
          </span>
        ),
      },
      {
        accessorKey: 'status',
        header: 'Status',
        cell: (props) => {
          const uniformity = props.row.original;
          const status =
            uniformity.latest_approval?.action ?? uniformity.status;

          const badgeColor = getStatusBadgeColor(status);
          const statusText = getStatusText(status);

          return <StatusBadge color={badgeColor} text={statusText} />;
        },
      },
      {
        accessorKey: 'uniformity',
        header: 'Uniformity',
        cell: (props) => {
          const uniformity = props.row.original.uniformity;
          return <span>{uniformity}%</span>;
        },
      },
    ],
    []
  );

  return (
    <>
      <div className='@container w-full'>
        <div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
          <div className='w-fit flex flex-row gap-3 flex-wrap'>
            <RequirePermission permissions='lti.production.uniformity.create'>
              <Button
                href='/production/uniformity/add'
                color='primary'
                className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
              >
                <Icon icon='heroicons:plus' width={20} height={20} />
                Add Uniformity
              </Button>
            </RequirePermission>
          </div>

          <div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
            <ButtonFilter
              values={tableFilterState}
              excludeFields={['page', 'pageSize', 'search']}
              fieldGroups={[['start_date', 'end_date']]}
              onClick={filterModal.openModal}
              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'
                  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 hover:bg-base-content/5'
              >
                <Icon icon='heroicons:document-text' width={20} height={20} />
                Export to PDF
              </Button>
            </Dropdown>
          </div>
        </div>

        <section className='p-3'>
          <UniformityChartWrapper
            uniformitySwrKey={uniformitySwrKey}
            isFiltered={isSubmitted}
          />
        </section>
      </div>

      <div className='flex flex-col mb-4'>
        {isLoading ? (
          <div className='w-full flex flex-row justify-center items-center p-4'>
            <span className='loading loading-spinner loading-xl' />
          </div>
        ) : !isResponseSuccess(uniformities) ||
          uniformities.data?.length === 0 ? (
          <div className='p-3 pt-0'>
            <UniformityTableSkeleton
              columns={uniformityColumns}
              icon={
                <Icon
                  icon='heroicons:document-text'
                  className='text-white'
                  width={20}
                  height={20}
                />
              }
            />
          </div>
        ) : (
          <Table<Uniformity>
            data={isResponseSuccess(uniformities) ? uniformities?.data : []}
            columns={uniformityColumns}
            pageSize={tableFilterState.pageSize}
            page={
              isResponseSuccess(uniformities) ? uniformities?.meta?.page : 0
            }
            totalItems={
              isResponseSuccess(uniformities)
                ? uniformities?.meta?.total_results
                : 0
            }
            onPageChange={setPage}
            isLoading={isLoading}
            sorting={sorting}
            setSorting={setSorting}
            rowSelection={rowSelection}
            setRowSelection={setRowSelection}
            className={{
              containerClassName: cn('p-3 pt-0 mb-0'),
              headerColumnClassName:
                'first:pl-3 first:pr-0 xl:first:pl-3 py-3 text-nowrap',
              bodyColumnClassName:
                'first:pl-3 first:pr-0 xl:first:pl-3 py-3 text-nowrap',
            }}
          />
        )}
      </div>

      <ConfirmationModal
        ref={successModal.ref}
        type='success'
        iconPosition='left'
        text='Data Berhasil Ditambahkan'
        subtitleText='Data uniformity telah berhasil disimpan.'
        closeOnBackdrop={true}
        primaryButton={{
          text: 'Ok',
          color: 'primary',
          onClick: handleSuccessModalClose,
        }}
        className={{
          modalBox: 'rounded-2xl',
        }}
      >
        <div className='flex flex-col gap-4'>
          {createdUniformity ? (
            <UniformityConfirmationPreview
              uniformityDetail={createdUniformity}
            />
          ) : selectedRowIds.length === 1 ? (
            <UniformityConfirmationPreview
              uniformity={selectedUniformities[0]}
            />
          ) : (
            <div className='text-center text-gray-500'>
              {selectedRowIds.length} data dipilih
            </div>
          )}
        </div>
      </ConfirmationModal>

      <ConfirmationModal
        ref={singleDeleteModal.ref}
        type='error'
        iconPosition='left'
        closeOnBackdrop={true}
        text={`Delete This Data?`}
        subtitleText='Are you sure you want to delete this data?'
        secondaryButton={{
          text: 'Cancel',
        }}
        primaryButton={{
          text: 'Delete',
          color: 'primary',
          isLoading: isDeleteLoading,
          onClick: singleDeleteHandler,
        }}
        className={{
          modalBox: 'rounded-2xl',
        }}
      >
        <div className='flex flex-col gap-4'>
          <UniformityConfirmationPreview uniformity={selectedUniformity} />
        </div>
      </ConfirmationModal>

      <ConfirmationModal
        ref={singleApproveModal.ref}
        type='success'
        iconPosition='left'
        closeOnBackdrop={true}
        text='Approve This Submission?'
        subtitleText='Are you sure you want to approve this submission?'
        secondaryButton={{
          text: 'Cancel',
        }}
        primaryButton={{
          text: 'Approve',
          color: 'primary',
          isLoading: isDeleteLoading,
          onClick: singleApproveHandler,
        }}
        className={{
          modalBox: 'rounded-2xl',
        }}
      >
        <div className='flex flex-col gap-4'>
          {selectedUniformities.map((uniformity) => (
            <UniformityConfirmationPreview
              key={uniformity.id}
              uniformity={uniformity}
            />
          ))}
        </div>
      </ConfirmationModal>

      <ConfirmationModal
        ref={bulkApproveModal.ref}
        type='success'
        iconPosition='left'
        closeOnBackdrop={true}
        text={`Approve This Submission?`}
        subtitleText={
          selectedRowIds.length === 1
            ? 'Are you sure you want to approve this submission?'
            : `Are you sure you want to approve these submissions? (${selectedRowIds.length} data)`
        }
        secondaryButton={{
          text: 'Cancel',
        }}
        primaryButton={{
          text: 'Approve',
          color: 'primary',
          isLoading: isBulkActionLoading,
          onClick: bulkApproveHandler,
        }}
        className={{
          modalBox: 'rounded-2xl',
        }}
      >
        <div className='flex flex-col gap-4'>
          {selectedUniformities.map((uniformity) => (
            <UniformityConfirmationPreview
              key={uniformity.id}
              uniformity={uniformity}
            />
          ))}
        </div>
      </ConfirmationModal>

      <ConfirmationModal
        ref={singleRejectModal.ref}
        type='error'
        iconPosition='left'
        closeOnBackdrop={true}
        text='Reject This Submission?'
        subtitleText='Are you sure you want to reject this submission?'
        secondaryButton={{
          text: 'Cancel',
        }}
        primaryButton={{
          text: 'Reject',
          color: 'primary',
          isLoading: isDeleteLoading,
          onClick: singleRejectHandler,
        }}
        className={{
          modalBox: 'rounded-2xl',
        }}
      >
        <div className='flex flex-col gap-4'>
          {selectedUniformities.map((uniformity) => (
            <UniformityConfirmationPreview
              key={uniformity.id}
              uniformity={uniformity}
            />
          ))}
        </div>
      </ConfirmationModal>

      <ConfirmationModal
        ref={bulkRejectModal.ref}
        type='error'
        iconPosition='left'
        closeOnBackdrop={true}
        text={`Reject This Submission?`}
        subtitleText={
          selectedRowIds.length === 1
            ? 'Are you sure you want to reject this submission?'
            : `Are you sure you want to reject these submissions? (${selectedRowIds.length} data)`
        }
        secondaryButton={{
          text: 'Cancel',
        }}
        primaryButton={{
          text: 'Reject',
          color: 'primary',
          isLoading: isBulkActionLoading,
          onClick: bulkRejectHandler,
        }}
        className={{
          modalBox: 'rounded-2xl',
        }}
      >
        <div className='flex flex-col gap-4'>
          {selectedUniformities.map((uniformity) => (
            <UniformityConfirmationPreview
              key={uniformity.id}
              uniformity={uniformity}
            />
          ))}
        </div>
      </ConfirmationModal>

      {/* Filter Modal */}
      <Modal
        ref={filterModal.ref}
        className={{
          modal: 'p-0',
          modalBox: 'p-0 rounded-[0.875rem]',
        }}
      >
        <div className='flex flex-col'>
          {/* Modal Header */}
          <div className='flex items-center justify-between p-4 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='font-medium text-sm'>Filter Data</h3>
            </div>
            <Button
              variant='link'
              onClick={filterModal.closeModal}
              className='text-gray-500 hover:text-gray-700'
            >
              <Icon icon='heroicons:x-mark' width={20} height={20} />
            </Button>
          </div>

          <form
            className='flex flex-col'
            onSubmit={handleFormSubmit}
            onReset={handleResetFilters}
          >
            <div className='flex flex-col p-4 gap-1.5'>
              {/* Rentang Waktu */}
              <div>
                <label className='flex text-xs items-center gap-1 py-2 font-semibold after:content-["*"] after:text-red-500'>
                  Tanggal
                </label>
                <div className='flex items-center gap-2'>
                  <DateInput
                    name='start_date'
                    placeholder='Tanggal Mulai'
                    value={filterFormik.values.start_date}
                    errorMessage={filterFormik.errors.start_date}
                    onChange={(e) => {
                      const value = e.target.value;
                      filterFormik.setFieldValue('start_date', value);
                      setFilterDateValues((prev) => ({
                        ...prev,
                        start_date: value,
                      }));

                      if (value && filterFormik.values.end_date) {
                        const startDate = new Date(value);
                        const endDateObj = new Date(
                          filterFormik.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);
                      }
                    }}
                    isError={
                      filterFormik.touched.start_date &&
                      Boolean(filterFormik.errors.start_date)
                    }
                  />
                  <hr className='w-full max-w-3 h-px border-base-content/10'></hr>
                  <DateInput
                    name='end_date'
                    placeholder='Tanggal Akhir'
                    value={filterFormik.values.end_date}
                    errorMessage={filterFormik.errors.end_date}
                    onChange={(e) => {
                      const value = e.target.value;
                      filterFormik.setFieldValue('end_date', value);
                      setFilterDateValues((prev) => ({
                        ...prev,
                        end_date: value,
                      }));

                      if (value && filterFormik.values.start_date) {
                        const startDateObj = new Date(
                          filterFormik.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);
                      }
                    }}
                    isError={hasDateError}
                  />
                </div>
              </div>

              <div>
                <SelectInput
                  required
                  label='Lokasi'
                  placeholder='Pilih Lokasi...'
                  value={filterFormik.values.location}
                  onChange={(value) => {
                    handleFilterLocationChange(value);
                  }}
                  options={filterLocationOptions}
                  onInputChange={setFilterLocationInputValue}
                  isLoading={isLoadingFilterLocations}
                  onMenuScrollToBottom={loadMoreFilterLocations}
                  isError={
                    filterFormik.touched.location &&
                    Boolean(filterFormik.errors.location)
                  }
                  errorMessage={filterFormik.errors.location}
                  isClearable
                  className={{ wrapper: 'w-full' }}
                />
              </div>

              <div>
                <SelectInput
                  required
                  label='Project Flock'
                  placeholder='Pilih Project Flock...'
                  value={filterFormik.values.project_flock}
                  onChange={(value) => {
                    handleFilterProjectFlockChange(value);
                  }}
                  options={filterProjectFlockOptions}
                  onInputChange={setFilterProjectFlockSearchValue}
                  isLoading={isLoadingFilterProjectFlocks}
                  onMenuScrollToBottom={loadMoreFilterProjectFlocks}
                  isDisabled={!filterFormik.values.location}
                  isError={
                    filterFormik.touched.project_flock &&
                    Boolean(filterFormik.errors.project_flock)
                  }
                  errorMessage={filterFormik.errors.project_flock}
                  isClearable
                  className={{ wrapper: 'w-full' }}
                />
              </div>

              <div>
                <SelectInput
                  required
                  label='Kandang'
                  placeholder='Pilih Kandang...'
                  value={filterFormik.values.kandang}
                  onChange={(value) => {
                    handleFilterKandangChange(value);
                  }}
                  options={filterKandangOptions}
                  isDisabled={!filterFormik.values.project_flock}
                  isError={
                    filterFormik.touched.kandang &&
                    Boolean(filterFormik.errors.kandang)
                  }
                  errorMessage={filterFormik.errors.kandang}
                  isClearable
                  className={{ wrapper: 'w-full' }}
                />
              </div>

              {formErrorList.length > 0 && (
                <div className='w-full'>
                  <AlertErrorList
                    formErrorList={formErrorList}
                    onClose={close}
                  />
                </div>
              )}
            </div>

            {/* Action Buttons */}
            <div className='flex justify-between gap-4 p-4 border-t border-base-content/10 bg-gray-100'>
              <Button
                type='reset'
                variant='soft'
                className='rounded-lg p-3 bg-gray-100 border-gray-100 text-base-content/65 hover:bg-base-content/10'
              >
                Reset Filter
              </Button>
              <Button
                type='submit'
                className='min-w-40 text-sm p-3 text-white rounded-lg'
              >
                Apply Filter
              </Button>
            </div>
          </form>
        </div>
      </Modal>

      {/* Floating Actions Button */}
      <FloatingActionsButton
        actions={[
          {
            action: 'DETAIL',
            icon: 'mdi:eye-outline',
            label: 'Lihat Detail',
            hidden: selectedRowIds.length !== 1,
            onClick() {
              router.push(
                `/production/uniformity/detail?uniformityId=${selectedRowIds[0]}`
              );
              setRowSelection({});
            },
            permissions: 'lti.production.uniformity.detail',
          },
          {
            action: 'DELETE',
            icon: 'mdi:delete-outline',
            label: 'Delete',
            hidden: selectedRowIds.length !== 1,
            onClick: handleDelete,
            permissions: 'lti.production.uniformity.delete',
          },
        ]}
        approvals={[
          {
            action: 'APPROVED',
            icon: 'mdi:check-circle-outline',
            label: 'Approve',
            onClick: handleBulkApprove,
            permissions: 'lti.production.uniformity.approve',
            disabled: !canApproveReject,
          },
          {
            action: 'REJECTED',
            icon: 'mdi:close-circle-outline',
            label: 'Reject',
            onClick: handleBulkReject,
            permissions: 'lti.production.uniformity.approve',
            disabled: !canApproveReject,
          },
        ]}
        selectedRowIds={selectedRowIds}
        onClose={handleCloseFab}
      />
    </>
  );
};

export default UniformityTable;
