'use client';

import React, { useCallback, useState, useMemo, useEffect } from 'react';
import useSWR from 'swr';
import { Icon } from '@iconify/react';
import { SortingState, CellContext, ColumnDef } from '@tanstack/react-table';
import { cn, formatDate, formatNumber, formatTitleCase } from '@/lib/helper';
import RequirePermission from '@/components/helper/RequirePermission';
import Modal, { useModal } from '@/components/Modal';
import Button from '@/components/Button';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
import { OptionType } from '@/components/input/SelectInput';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import DateInput from '@/components/input/DateInput';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import Tooltip from '@/components/Tooltip';
import { useFormik } from 'formik';
import { AreaApi } from '@/services/api/master-data';
import { LocationApi } from '@/services/api/master-data';
import { ProjectFlockApi } from '@/services/api/production';
import { Location } from '@/types/api/master-data/location';
import { Area } from '@/types/api/master-data/area';
import { ProjectFlock } from '@/types/api/production/project-flock';
import { type BaseApiResponse } from '@/types/api/api-general';
import {
  RecordingFilterSchema,
  RecordingFilterType,
} from '@/components/pages/production/recording/filter/RecordingFilter';
import RecordingTableSkeleton from '@/components/pages/production/recording/skeleton/RecordingTableSkeleton';
import Table from '@/components/Table';
import { type Recording } from '@/types/api/production/recording';
import { getRecordingRestriction } from './recording-utils';
import { RecordingApi } from '@/services/api/production';
import { getErrorMessage, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import toast from 'react-hot-toast';
import StatusBadge from '@/components/helper/StatusBadge';
import CheckboxInput from '@/components/input/CheckboxInput';
import { Color } from '@/types/theme';
import ButtonFilter from '@/components/helper/ButtonFilter';
import Dropdown from '@/components/Dropdown';

// ===== STATUS BADGE UTILITIES =====
const statusTextMap: Record<string, string> = {
  APPROVED: 'Disetujui',
  REJECTED: 'Ditolak',
  CREATED: 'Pengajuan',
  UPDATED: 'Diperbarui',
};

const getStatusText = (status: string): string => {
  const normalizedStatus = status.toUpperCase();
  return statusTextMap[normalizedStatus] || status;
};

const statusBadgeColorMap: Record<string, Color> = {
  APPROVED: 'success',
  REJECTED: 'error',
  CREATED: 'neutral',
  UPDATED: 'warning',
};

const getStatusBadgeColor = (status: string): Color => {
  const normalizedStatus = status.toUpperCase();
  return statusBadgeColorMap[normalizedStatus] || 'neutral';
};

const isRecordingApproved = (recording: Recording): boolean => {
  return (
    recording.approval?.action === 'APPROVED' &&
    recording.approval?.step_name === 'Disetujui'
  );
};

// ===== FILTER HELPERS =====
const recordingApprovalStatusOptions: OptionType<string>[] = [
  { value: 'CREATED', label: 'Pengajuan' },
  { value: 'UPDATED', label: 'Diperbarui' },
  { value: 'APPROVED', label: 'Disetujui' },
  { value: 'REJECTED', label: 'Ditolak' },
];

const projectFlockCategoryOptions: OptionType<string>[] = [
  { value: 'GROWING', label: 'Growing' },
  { value: 'LAYING', label: 'Laying' },
];

const RowOptionsMenu = ({
  popoverPosition = 'bottom',
  props,
  deleteClickHandler,
  approveClickHandler,
  rejectClickHandler,
}: {
  popoverPosition: 'bottom' | 'top';
  props: CellContext<Recording, unknown>;
  deleteClickHandler: () => void;
  approveClickHandler: () => void;
  rejectClickHandler: () => void;
}) => {
  const popoverId = `recording#${props.row.original.id}`;
  const popoverAnchorName = `--anchor-recording#${props.row.original.id}`;

  const closePopover = () => {
    document.getElementById(popoverId)?.hidePopover();
  };

  const isRecordingApproved = (recording: Recording) => {
    return (
      recording.approval?.action === 'APPROVED' &&
      recording.approval?.step_number === 2 &&
      recording.approval?.step_name === 'Disetujui'
    );
  };

  const isRecordingRejected = (recording: Recording) => {
    return recording.approval?.action === 'REJECTED';
  };

  const isRecordingEditable = (recording: Recording) => {
    const isGrowingCategory =
      recording.project_flock?.project_flock_category === 'GROWING';
    const isGrowingLockedByLaying = isGrowingCategory && recording.is_laying;
    if (isGrowingLockedByLaying) {
      return false;
    }

    const currentIsLaying =
      recording.project_flock?.project_flock_category === 'LAYING';

    const restriction = getRecordingRestriction(
      recording.is_laying,
      recording.is_transition,
      currentIsLaying
    );

    if (restriction.isLocked) {
      return false;
    }
    return true;
  };

  const getRecordingRestrictionInfo = (recording: Recording) => {
    const isGrowingCategory =
      recording.project_flock?.project_flock_category === 'GROWING';
    const isGrowingLockedByLaying = isGrowingCategory && recording.is_laying;
    if (isGrowingLockedByLaying) {
      return {
        canEditStock: false,
        canEditDepletion: false,
        canEditEgg: false,
        isLocked: true,
        lockReason:
          'Recording Growing tidak dapat diubah karena sudah masuk fase laying dan dipakai pada recording laying',
      };
    }

    const currentIsLaying =
      recording.project_flock?.project_flock_category === 'LAYING';

    return getRecordingRestriction(
      recording.is_laying,
      recording.is_transition,
      currentIsLaying
    );
  };

  const isApproved = isRecordingApproved(props.row.original);
  const isRejected = isRecordingRejected(props.row.original);
  const isEditable = isRecordingEditable(props.row.original);
  const restrictionInfo = getRecordingRestrictionInfo(props.row.original);

  return (
    <div className='relative'>
      <Tooltip
        content={restrictionInfo.isLocked ? restrictionInfo.lockReason : ''}
        position='top'
      >
        <PopoverButton
          tabIndex={0}
          variant='ghost'
          color='none'
          popoverTarget={popoverId}
          anchorName={popoverAnchorName}
          className={restrictionInfo.isLocked ? 'text-error' : ''}
        >
          <Icon icon='material-symbols:more-vert' width={16} height={16} />
        </PopoverButton>
      </Tooltip>

      <PopoverContent
        id={popoverId}
        anchorName={popoverAnchorName}
        position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
        className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
      >
        <div className='flex flex-col bg-base-100 rounded-xl'>
          <RequirePermission permissions='lti.production.recording.detail'>
            <Button
              href={`/production/recording/detail/?recordingId=${props.row.original.id}`}
              variant='ghost'
              color='none'
              className='p-3 justify-start text-sm font-semibold w-full'
              onClick={closePopover}
            >
              <Icon icon='heroicons:eye' width={20} height={20} />
              View Details
            </Button>
          </RequirePermission>
          {isEditable && (
            <RequirePermission permissions='lti.production.recording.update'>
              <Button
                href={`/production/recording/detail/edit/?recordingId=${props.row.original.id}`}
                variant='ghost'
                color='none'
                className='p-3 justify-start text-sm font-semibold w-full'
                onClick={closePopover}
              >
                <Icon icon='mdi:pencil-outline' width={20} height={20} />
                Edit
              </Button>
            </RequirePermission>
          )}
          {!isApproved && !isRejected && (
            <RequirePermission permissions='lti.production.recording.approve'>
              <Button
                onClick={() => {
                  approveClickHandler();
                  closePopover();
                }}
                variant='ghost'
                color='none'
                className='p-3 justify-start text-sm font-semibold w-full'
              >
                <Icon icon='material-symbols:check' width={20} height={20} />
                Approve
              </Button>
            </RequirePermission>
          )}
          {!isApproved && !isRejected && (
            <RequirePermission permissions='lti.production.recording.approve'>
              <Button
                onClick={() => {
                  rejectClickHandler();
                  closePopover();
                }}
                variant='ghost'
                color='none'
                className='p-3 justify-start text-sm font-semibold w-full'
              >
                <Icon icon='material-symbols:close' width={20} height={20} />
                Reject
              </Button>
            </RequirePermission>
          )}
          {isEditable && (
            <RequirePermission permissions='lti.production.recording.delete'>
              <Button
                onClick={() => {
                  deleteClickHandler();
                  closePopover();
                }}
                variant='ghost'
                color='error'
                className='p-3 justify-start text-sm font-semibold w-full focus-visible:text-error-content hover:text-error-content'
              >
                <Icon icon='mdi:delete-outline' width={20} height={20} />
                Delete
              </Button>
            </RequirePermission>
          )}
        </div>
      </PopoverContent>
    </div>
  );
};

const RecordingTable = () => {
  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter<{
    search: string;
    areaFilter: OptionType<number> | null;
    locationFilter: OptionType<number> | null;
    projectFlockFilter: OptionType<number> | null;
    kandangFilter: OptionType<number> | null;
    projectFlockKandangFilter: number | null;
    approvalStatusFilter: OptionType<string> | null;
    projectFlockCategoryFilter: OptionType<string> | null;
  }>({
    initial: {
      search: '',
      areaFilter: null,
      locationFilter: null,
      projectFlockFilter: null,
      kandangFilter: null,
      projectFlockKandangFilter: null,
      approvalStatusFilter: null,
      projectFlockCategoryFilter: null,
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      search: 'search',
      areaFilter: 'area_id',
      locationFilter: 'location_id',
      projectFlockFilter: 'project_flock_id',
      kandangFilter: 'kandang_id',
      projectFlockKandangFilter: 'project_flock_kandang_id',
      approvalStatusFilter: 'approval_status',
      projectFlockCategoryFilter: 'project_flock_category',
    },

    persist: true,
    storeName: 'recording-table',
  });

  // ===== FILTER MODAL STATE =====
  const filterModal = useModal();

  // ===== FORMIK SETUP =====
  const formik = useFormik<RecordingFilterType>({
    initialValues: {
      area_id: tableFilterState.areaFilter,
      location_id: tableFilterState.locationFilter,
      project_flock_id: tableFilterState.projectFlockFilter,
      kandang_id: tableFilterState.kandangFilter,
      project_flock_kandang_id: tableFilterState.projectFlockKandangFilter,
      approval_status: tableFilterState.approvalStatusFilter,
      project_flock_category: tableFilterState.projectFlockCategoryFilter,
    },
    validationSchema: RecordingFilterSchema,
    onSubmit: (values, { setSubmitting }) => {
      updateFilter('areaFilter', values.area_id, true);
      updateFilter('locationFilter', values.location_id, true);
      updateFilter('projectFlockFilter', values.project_flock_id, true);
      updateFilter('kandangFilter', values.kandang_id, true);
      updateFilter(
        'projectFlockKandangFilter',
        values.project_flock_kandang_id,
        true
      );
      updateFilter('approvalStatusFilter', values.approval_status, true);
      updateFilter(
        'projectFlockCategoryFilter',
        values.project_flock_category,
        true
      );
      filterModal.closeModal();
      setSubmitting(false);
    },
  });

  const formikResetHandler = () => {
    updateFilter('areaFilter', null, true);
    updateFilter('locationFilter', null, true);
    updateFilter('projectFlockFilter', null, true);
    updateFilter('kandangFilter', null, true);
    updateFilter('projectFlockKandangFilter', null, true);
    updateFilter('approvalStatusFilter', null, true);
    updateFilter('projectFlockCategoryFilter', null, true);

    formik.resetForm({
      values: {
        area_id: null,
        location_id: null,
        project_flock_id: null,
        kandang_id: null,
        project_flock_kandang_id: null,
        approval_status: null,
        project_flock_category: null,
      },
    });

    filterModal.closeModal();
  };

  const { project_flock_id, kandang_id } = formik.values;

  const [sorting, setSorting] = useState<SortingState>([]);
  const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
  const selectedRowIds = Object.keys(rowSelection).map((item) =>
    parseInt(item)
  );
  const [selectedRecording, setSelectedRecording] = useState<
    Recording | undefined
  >(undefined);
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);
  const [isApproveLoading, setIsApproveLoading] = useState(false);
  const [isRejectLoading, setIsRejectLoading] = useState(false);
  const [, setApprovalNotes] = useState('');

  const [isLoadingExportingToExcel, setIsLoadingExportingToExcel] =
    useState(false);
  const [isExportProgressLoading, setIsExportProgressLoading] = useState(false);
  const [exportProgressStartDate, setExportProgressStartDate] = useState('');
  const [exportProgressEndDate, setExportProgressEndDate] = useState('');

  const singleDeleteModal = useModal();
  const approveModal = useModal();
  const rejectModal = useModal();
  const exportProgressInputModal = useModal();

  const {
    data: recordings,
    isLoading,
    mutate: refreshRecordings,
  } = useSWR(
    `${RecordingApi.basePath}${getTableFilterQueryString()}`,
    RecordingApi.getAllFetcher
  );

  // ===== LOCATION, AREA, KANDANG OPTIONS =====
  const {
    setInputValue: setLocationInputValue,
    options: locationOptions,
    isLoadingOptions: isLoadingLocationOptions,
    loadMore: loadMoreLocations,
  } = useSelect<Location>(
    filterModal.open ? LocationApi.basePath : null,
    'id',
    'name',
    'search',
    {
      area_id: String(formik.values.area_id?.value),
    }
  );

  const {
    setInputValue: setAreaInputValue,
    options: areaOptions,
    isLoadingOptions: isLoadingAreaOptions,
    loadMore: loadMoreAreas,
  } = useSelect<Area>(
    filterModal.open ? AreaApi.basePath : null,
    'id',
    'name',
    'search'
  );

  const {
    setInputValue: setProjectFlockInputValue,
    options: projectFlockOptions,
    rawData: projectFlocksRawData,
    isLoadingOptions: isLoadingProjectFlocks,
    loadMore: loadMoreProjectFlocks,
  } = useSelect(
    filterModal.open ? ProjectFlockApi.basePath : null,
    'id',
    'flock_name',
    'search',
    {
      location_id: String(formik.values.location_id?.value),
    }
  );

  const kandangOptions = useMemo(() => {
    if (!project_flock_id || !projectFlocksRawData) return [];
    if (!isResponseSuccess(projectFlocksRawData)) return [];

    const data = projectFlocksRawData.data as ProjectFlock[];
    const selectedProjectFlockData = data.find((pf) =>
      pf.id === formik.values.project_flock_id?.value
        ? Number(formik.values.project_flock_id.value)
        : 0
    );

    if (!selectedProjectFlockData?.kandangs) return [];

    return selectedProjectFlockData.kandangs.map((k) => ({
      value: k.id,
      label: k.name || '',
    }));
  }, [project_flock_id, projectFlocksRawData]);

  // ===== PROJECT FLOCK KANDANG LOOKUP =====
  const projectFlockKandangLookupUrl = useMemo(() => {
    if (!project_flock_id?.value || !kandang_id?.value) return null;

    const params = new URLSearchParams({
      project_flock_id: project_flock_id.value.toString(),
      kandang_id: kandang_id.value.toString(),
    });

    return `${ProjectFlockApi.basePath}/kandangs/lookup?${params.toString()}`;
  }, [project_flock_id, kandang_id]);

  const { data: projectFlockKandangLookupData } = useSWR(
    projectFlockKandangLookupUrl,
    projectFlockKandangLookupUrl
      ? () =>
          ProjectFlockApi.getAllFetcher(
            projectFlockKandangLookupUrl
          ) as Promise<
            BaseApiResponse<{
              id: number;
              project_flock: { flock_name: string };
            }>
          >
      : null
  );

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

  useEffect(() => {
    if (projectFlockKandangLookup?.id) {
      const pfkId = String(projectFlockKandangLookup.id);
      formik.setFieldValue('project_flock_kandang_id', pfkId);
    } else {
      formik.setFieldValue('project_flock_kandang_id', null);
    }
  }, [projectFlockKandangLookup]);

  // ===== FILTER HANDLERS =====
  const handleFilterAreaChange = (val: OptionType | OptionType[] | null) => {
    formik.setFieldValue('area_id', val);
    formik.setFieldValue('location_id', null);
    formik.setFieldValue('project_flock_id', null);
    formik.setFieldValue('kandang_id', null);
    formik.setFieldValue('project_flock_kandang_id', null);
  };

  const handleFilterLocationChange = (
    val: OptionType | OptionType[] | null
  ) => {
    formik.setFieldValue('location_id', val);
    formik.setFieldValue('project_flock_id', null);
    formik.setFieldValue('kandang_id', null);
    formik.setFieldValue('project_flock_kandang_id', null);
  };

  const handleFilterProjectFlockChange = (
    val: OptionType | OptionType[] | null
  ) => {
    formik.setFieldValue('project_flock_id', val);
    formik.setFieldValue('kandang_id', null);
    formik.setFieldValue('project_flock_kandang_id', null);
  };

  const handleFilterKandangChange = (val: OptionType | OptionType[] | null) => {
    formik.setFieldValue('kandang_id', val);
    formik.setFieldValue('project_flock_kandang_id', null);
  };

  // ===== HANDLE FILTER MODAL OPEN =====
  const handleFilterModalOpen = () => {
    filterModal.openModal();
    formik.validateForm();
  };

  const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
    updateFilter('search', e.target.value, true);
  };

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

    const response = await RecordingApi.delete(selectedRecording?.id as number);

    singleDeleteModal.closeModal();
    setIsDeleteLoading(false);

    if (isResponseSuccess(response)) {
      toast.success(response?.message || 'Successfully delete Recording!');
      refreshRecordings();
    } else {
      toast.error(response?.message || 'Failed to delete Recording');
    }
  };

  const approveHandler = async (notes: string) => {
    setIsApproveLoading(true);

    if (eligibleRowIds.length === 0) {
      toast.error(
        'Tidak ada recording yang bisa disetujui (sudah disetujui final)'
      );
      setIsApproveLoading(false);
      return;
    }

    const approveResponse = await RecordingApi.approve(eligibleRowIds, notes);

    if (isResponseSuccess(approveResponse)) {
      toast.success(
        `Berhasil approve ${eligibleRowIds.length} data recording!`
      );
      approveModal.closeModal();
      refreshRecordings();
      setApprovalNotes('');
      setRowSelection({});
    } else {
      toast.error(
        (approveResponse?.message as string) || 'Gagal menyetujui recording'
      );
    }

    setIsApproveLoading(false);
  };

  const rejectHandler = async (notes: string) => {
    setIsRejectLoading(true);

    if (eligibleRowIds.length === 0) {
      toast.error(
        'Tidak ada recording yang bisa ditolak (sudah disetujui final)'
      );
      setIsRejectLoading(false);
      return;
    }

    const rejectResponse = await RecordingApi.reject(eligibleRowIds, notes);

    if (isResponseSuccess(rejectResponse)) {
      toast.success(`Berhasil reject ${eligibleRowIds.length} data recording!`);
      rejectModal.closeModal();
      refreshRecordings();
      setApprovalNotes('');
      setRowSelection({});
    } else {
      toast.error(
        (rejectResponse?.message as string) || 'Gagal menolak recording'
      );
    }

    setIsRejectLoading(false);
  };

  const eligibleRowIds = useMemo(() => {
    if (!isResponseSuccess(recordings) || !recordings.data) return [];
    return selectedRowIds.filter((id) => {
      const recording = recordings.data.find((r) => r.id === id);
      return recording && !isRecordingApproved(recording);
    });
  }, [selectedRowIds, recordings, isRecordingApproved]);

  const exportToExcelHandler = async () => {
    setIsLoadingExportingToExcel(true);

    await RecordingApi.exportToExcel(getTableFilterQueryString());

    setIsLoadingExportingToExcel(false);
  };

  const resetExportProgressForm = useCallback(() => {
    setExportProgressStartDate('');
    setExportProgressEndDate('');
  }, []);

  const exportProgressStartDateChangeHandler = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      setExportProgressStartDate(e.target.value);
    },
    []
  );

  const exportProgressEndDateChangeHandler = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      setExportProgressEndDate(e.target.value);
    },
    []
  );

  const exportProgressInputToExcelClickHandler = useCallback(() => {
    resetExportProgressForm();
    exportProgressInputModal.openModal();
  }, [exportProgressInputModal, resetExportProgressForm]);

  const submitExportProgressInputHandler = useCallback(async () => {
    if (!exportProgressStartDate || !exportProgressEndDate) {
      return;
    }

    setIsExportProgressLoading(true);

    try {
      await RecordingApi.exportInputProgressToExcel(
        exportProgressStartDate,
        exportProgressEndDate
      );

      exportProgressInputModal.closeModal();
      resetExportProgressForm();
      toast.success('Ekspor berhasil');
    } catch (error) {
      toast.error(
        await getErrorMessage(error, 'Gagal mengekspor input progress')
      );
    } finally {
      setIsExportProgressLoading(false);
    }
  }, [
    exportProgressEndDate,
    exportProgressInputModal,
    exportProgressStartDate,
    resetExportProgressForm,
  ]);

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

      Object.entries(rowSelection).forEach(([rowId, isSelected]) => {
        if (isSelected) {
          const recording = recordings.data.find(
            (r) => r.id === parseInt(rowId)
          );
          if (recording && !isRecordingApproved(recording)) {
            newSelection[rowId] = true;
          }
        }
      });

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

  // ===== TABLE COLUMNS =====
  const recordingColumns: ColumnDef<Recording>[] = useMemo(
    () => [
      {
        id: 'select',
        header: ({ table }) => {
          const allRows = table.getRowModel().rows;
          const selectableRows = allRows.filter((row) => {
            const recording = row.original;
            const isRecordingApproved =
              recording.approval?.action === 'APPROVED' &&
              recording.approval?.step_number === 2 &&
              recording.approval?.step_name === 'Disetujui';
            const isRecordingRejected =
              recording.approval?.action === 'REJECTED';
            return !isRecordingApproved && !isRecordingRejected;
          });

          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 justify-center'>
              <CheckboxInput
                name='allRow'
                checked={isAllSelected}
                indeterminate={isSomeSelected && !isAllSelected}
                onChange={handleSelectAll}
                disabled={hasNoSelectableRows}
              />
            </div>
          );
        },
        cell: ({ row }) => {
          const recording = row.original;
          const isRecordingApproved =
            recording.approval?.action === 'APPROVED' &&
            recording.approval?.step_number === 2 &&
            recording.approval?.step_name === 'Disetujui';
          const isRecordingRejected = recording.approval?.action === 'REJECTED';
          const isDisabled = isRecordingApproved || isRecordingRejected;

          const handleToggleSelection = (e: unknown) => {
            if (!isDisabled) {
              row.getToggleSelectedHandler()(e);
            }
          };

          return (
            <div className={cn({ 'opacity-50': isDisabled })}>
              <CheckboxInput
                name='row'
                checked={row.getIsSelected()}
                indeterminate={row.getIsSomeSelected()}
                onChange={handleToggleSelection}
                disabled={isDisabled}
              />
            </div>
          );
        },
      },
      {
        header: 'No',
        cell: (props) =>
          tableFilterState.pageSize * (tableFilterState.page - 1) +
          props.row.index +
          1,
      },
      {
        header: 'Lokasi',
        cell: (props) => props.row.original.location?.name || '-',
      },
      {
        header: 'Flock',
        cell: (props) => props.row.original.project_flock?.flock_name || '-',
      },
      {
        header: 'Kandang',
        cell: (props) => props.row.original.kandang?.name || '-',
      },
      {
        header: 'Periode',
        cell: (props) => props.row.original.project_flock?.period || '-',
      },
      {
        header: 'Kategori',
        cell: (props) => {
          const isTransition = props.row.original.is_transition;
          const category =
            props.row.original.project_flock?.project_flock_category ||
            'GROWING';
          const color = category === 'LAYING' ? 'info' : 'warning';

          const isGrowingLocked =
            category === 'GROWING' && props.row.original.is_laying;

          return (
            <div className='flex flex-col gap-1'>
              <StatusBadge color={color} text={formatTitleCase(category)} />
              {isTransition && (
                <span className='text-xs text-warning font-medium'>
                  (Transisi)
                </span>
              )}
              {isGrowingLocked && (
                <span className='text-xs text-error font-medium'>
                  (Penguncian)
                </span>
              )}
            </div>
          );
        },
      },
      {
        header: 'Umur (hari)',
        cell: (props) => {
          return (
            <>
              <span>
                {props.row.original.day} (Minggu ke-
                {props.row.original.week} hari ke-
                {props.row.original.excess_days})
              </span>
            </>
          );
        },
      },
      {
        header: 'Waktu Recording',
        cell: (props) =>
          formatDate(props.row.original.record_datetime, 'DD MMMM YYYY'),
      },
      {
        header: 'Populasi Akhir',
        cell: (props) =>
          props.row.original.project_flock?.total_chick_qty != null
            ? formatNumber(props.row.original.project_flock.total_chick_qty)
            : '-',
      },
      {
        id: 'fcr',
        header: 'FCR',
        columns: [
          {
            id: 'fcr_actual',
            header: 'Actual',
            cell: (props) => {
              const value = props.row.original.fcr_value;
              return (
                <div className='text-center'>
                  {value !== null && value !== undefined
                    ? formatNumber(value)
                    : '-'}
                </div>
              );
            },
          },
          {
            id: 'fcr_standard',
            header: 'Standard',
            cell: (props) => {
              const value = props.row.original.project_flock?.fcr?.fcr_std;
              return (
                <div className='text-center text-gray-600'>
                  {value !== null && value !== undefined
                    ? formatNumber(value)
                    : '-'}
                </div>
              );
            },
          },
        ],
      },
      {
        id: 'feed_intake',
        header: 'Feed Intake (KG)',
        columns: [
          {
            id: 'feed_intake_actual',
            header: 'Actual',
            cell: (props) => {
              const value = props.row.original.feed_intake;
              return (
                <div className='text-center'>
                  {value !== null && value !== undefined
                    ? formatNumber(value)
                    : '-'}
                </div>
              );
            },
          },
          {
            id: 'feed_intake_standard',
            header: 'Standard',
            cell: (props) => {
              const value =
                props.row.original.project_flock?.production_standart
                  ?.feed_intake_std;
              return (
                <div className='text-center text-gray-600'>
                  {value !== null && value !== undefined
                    ? formatNumber(value)
                    : '-'}
                </div>
              );
            },
          },
        ],
      },
      {
        id: 'mortality',
        header: 'Mortality',
        columns: [
          {
            id: 'cum_depletion_rate_actual',
            header: 'Cum Depletion Rate',
            cell: (props) => {
              const value = props.row.original.cum_depletion_rate;
              return (
                <div className='text-center'>
                  {value !== null && value !== undefined
                    ? `${value.toFixed(2)}%`
                    : '-'}
                </div>
              );
            },
          },
          {
            id: 'max_depletion_std',
            header: 'Max Depletion Std',
            cell: (props) => {
              const value =
                props.row.original.project_flock?.production_standart
                  ?.max_depletion_std;
              return (
                <div className='text-center text-gray-600'>
                  {value !== null && value !== undefined
                    ? `${value.toFixed(2)}%`
                    : '-'}
                </div>
              );
            },
          },
          {
            id: 'total_depletion',
            header: 'Total Depletion',
            cell: (props) => {
              const value = props.row.original.total_depletion_qty;
              return (
                <div className='text-center'>
                  {value !== null && value !== undefined
                    ? formatNumber(value)
                    : '-'}
                </div>
              );
            },
          },
        ],
      },
      {
        id: 'egg_production',
        header: 'Egg Production',
        columns: [
          {
            id: 'egg_mass_actual',
            header: 'Egg Mass Actual',
            cell: (props) => {
              const value = props.row.original.egg_mass;
              return (
                <div className='text-center'>
                  {value !== null && value !== undefined
                    ? formatNumber(value)
                    : '-'}
                </div>
              );
            },
          },
          {
            id: 'egg_mass_standard',
            header: 'Egg Mass Standar',
            cell: (props) => {
              const value =
                props.row.original.project_flock?.production_standart
                  ?.egg_mass_std;
              return (
                <div className='text-center text-gray-600'>
                  {value !== null && value !== undefined
                    ? formatNumber(value)
                    : '-'}
                </div>
              );
            },
          },
          {
            id: 'egg_weight_actual',
            header: 'Egg Weight Actual',
            cell: (props) => {
              const value = props.row.original.egg_weight;
              return (
                <div className='text-center'>
                  {value !== null && value !== undefined
                    ? formatNumber(value)
                    : '-'}
                </div>
              );
            },
          },
          {
            id: 'egg_weight_standard',
            header: 'Egg Weight Standar',
            cell: (props) => {
              const value =
                props.row.original.project_flock?.production_standart
                  ?.egg_weight_std;
              return (
                <div className='text-center text-gray-600'>
                  {value !== null && value !== undefined
                    ? formatNumber(value)
                    : '-'}
                </div>
              );
            },
          },
        ],
      },
      {
        id: 'hen_performance',
        header: 'Hen Performance',
        columns: [
          {
            id: 'hen_day_actual',
            header: 'Hen Day Actual',
            cell: (props) => {
              const value = props.row.original.hen_day;
              return (
                <div className='text-center'>
                  {value !== null && value !== undefined
                    ? `${value.toFixed(2)}%`
                    : '-'}
                </div>
              );
            },
          },
          {
            id: 'hen_day_standard',
            header: 'Hen Day Standar',
            cell: (props) => {
              const value =
                props.row.original.project_flock?.production_standart
                  ?.hen_day_std;
              return (
                <div className='text-center text-gray-600'>
                  {value !== null && value !== undefined
                    ? `${value.toFixed(2)}%`
                    : '-'}
                </div>
              );
            },
          },
          {
            id: 'hen_house_actual',
            header: 'Hen House Actual',
            cell: (props) => {
              const value = props.row.original.hen_house;
              return (
                <div className='text-center'>
                  {value !== null && value !== undefined
                    ? `${value.toFixed(2)} butir`
                    : '-'}
                </div>
              );
            },
          },
          {
            id: 'hen_house_standard',
            header: 'Hen House Standar',
            cell: (props) => {
              const value =
                props.row.original.project_flock?.production_standart
                  ?.hen_house_std;
              return (
                <div className='text-center text-gray-600'>
                  {value !== null && value !== undefined
                    ? `${value.toFixed(2)} btr`
                    : '-'}
                </div>
              );
            },
          },
        ],
      },
      {
        header: 'Status Approval',
        cell: (props) => {
          const approval = props.row.original.approval;
          if (!approval) return '-';

          const status = approval.action;
          const statusColor = getStatusBadgeColor(status);
          const statusText = getStatusText(status);

          return (
            <StatusBadge
              color={statusColor}
              text={statusText}
              className={{
                badge: 'whitespace-nowrap',
              }}
            />
          );
        },
      },
      {
        header: 'Catatan Approval',
        cell: (props) => {
          const approval = props.row.original.approval;
          if (!approval?.notes) return '-';

          return (
            <div className='max-w-xs'>
              <p className='text-sm truncate'>{approval.notes}</p>
            </div>
          );
        },
      },
      {
        header: 'Dibuat Oleh',
        cell: (props) => props.row.original.created_user?.name || '-',
      },
      {
        header: 'Tanggal Submit',
        cell: (props) =>
          formatDate(props.row.original.created_at, 'DD MMMM YYYY'),
      },
      {
        header: 'Aksi',
        cell: (props: CellContext<Recording, unknown>) => {
          const currentPageSize =
            props.table.getPaginationRowModel().rows.length;
          const currentPageRows = props.table.getPaginationRowModel().flatRows;
          const currentRowRelativeIndex =
            currentPageRows.findIndex((r) => r.id === props.row.id) + 1;

          const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;

          const deleteClickHandler = () => {
            setSelectedRecording(props.row.original);
            singleDeleteModal.openModal();
          };

          const approveClickHandler = () => {
            setRowSelection({
              [String(props.row.original.id)]: true,
            });
            setApprovalNotes('');
            approveModal.openModal();
          };

          const rejectClickHandler = () => {
            setRowSelection({
              [String(props.row.original.id)]: true,
            });
            setApprovalNotes('');
            rejectModal.openModal();
          };

          return (
            <RowOptionsMenu
              props={props}
              deleteClickHandler={deleteClickHandler}
              approveClickHandler={approveClickHandler}
              rejectClickHandler={rejectClickHandler}
              popoverPosition={isLast2Rows ? 'top' : 'bottom'}
            />
          );
        },
      },
    ],
    [
      tableFilterState.pageSize,
      tableFilterState.page,
      singleDeleteModal,
      approveModal,
      rejectModal,
      setRowSelection,
      setApprovalNotes,
      setSelectedRecording,
    ]
  );

  return (
    <>
      <div className='w-full'>
        <div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
          {/* Action Buttons */}
          <div className='w-fit flex flex-row gap-3 flex-wrap'>
            <RequirePermission permissions='lti.production.recording.create'>
              <Button
                href='/production/recording/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 Recording
              </Button>
            </RequirePermission>

            {selectedRowIds.length > 0 && (
              <>
                <hr className='w-px h-full border-none bg-base-content/10 sm:block hidden' />

                <RequirePermission permissions='lti.production.recording.approve'>
                  <Button
                    variant='outline'
                    color='none'
                    onClick={() => {
                      setApprovalNotes('');
                      rejectModal.openModal();
                    }}
                    disabled={
                      selectedRowIds.length === 0 || eligibleRowIds.length === 0
                    }
                    className='px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
                  >
                    <Icon
                      icon='heroicons:x-mark'
                      width={20}
                      height={20}
                      className='text-error'
                    />
                    Reject
                  </Button>
                </RequirePermission>

                <RequirePermission permissions='lti.production.recording.approve'>
                  <Button
                    variant='outline'
                    color='none'
                    onClick={() => {
                      setApprovalNotes('');
                      approveModal.openModal();
                    }}
                    disabled={
                      selectedRowIds.length === 0 || eligibleRowIds.length === 0
                    }
                    className='px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
                  >
                    <Icon
                      icon='heroicons:check'
                      width={20}
                      height={20}
                      className='text-success'
                    />
                    Approve
                  </Button>
                </RequirePermission>
              </>
            )}
          </div>

          {/* Search and Filter */}
          <div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
            <DebouncedTextInput
              name='search'
              placeholder='Search'
              value={tableFilterState.search ?? ''}
              onChange={searchChangeHandler}
              startAdornment={
                <Icon
                  icon='heroicons:magnifying-glass'
                  width={20}
                  height={20}
                />
              }
              className={{
                wrapper: 'w-full min-w-24 max-w-3xs',
                inputWrapper: 'rounded-xl! shadow-button-soft',
                input:
                  'placeholder:font-semibold placeholder:text-base-content/50',
              }}
            />

            <ButtonFilter
              values={tableFilterState}
              excludeFields={['page', 'pageSize', 'search']}
              onClick={handleFilterModalOpen}
              className='px-3 py-2.5'
            />

            <Dropdown
              align='end'
              direction='bottom'
              trigger={
                <Button
                  variant='outline'
                  color='none'
                  className={cn(
                    'px-3 py-2.5 rounded-lg font-semibold text-sm gap-1.5',
                    'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft'
                  )}
                >
                  <Icon
                    width={20}
                    height={20}
                    icon='heroicons:cloud-arrow-down'
                  />
                  Export
                  <div className='w-6.5 h-5 flex items-center justify-center border-l border-base-content/10'>
                    <Icon
                      width={14}
                      height={14}
                      icon='heroicons:chevron-down'
                    />
                  </div>
                </Button>
              }
              className={{
                content:
                  'mt-1 rounded-xl border border-base-content/5 shadow-sm overflow-hidden',
              }}
            >
              <Button
                variant='ghost'
                color='none'
                onClick={exportToExcelHandler}
                isLoading={isLoadingExportingToExcel}
                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={exportProgressInputToExcelClickHandler}
                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} />
                Ekspor Input Progress (Excel)
              </Button>
            </Dropdown>
          </div>
        </div>

        {/* Table Section */}
        <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(recordings) ||
            recordings.data?.length === 0 ? (
            <RecordingTableSkeleton
              columns={recordingColumns}
              icon={
                <Icon
                  icon='heroicons:chart-bar'
                  className='text-white'
                  width={20}
                  height={20}
                />
              }
              title='Data Recording Belum Tersedia'
              subtitle='Tidak ada data recording untuk saat ini.'
            />
          ) : (
            <Table<Recording>
              data={isResponseSuccess(recordings) ? recordings?.data : []}
              columns={recordingColumns}
              pageSize={tableFilterState.pageSize}
              page={isResponseSuccess(recordings) ? recordings?.meta?.page : 0}
              totalItems={
                isResponseSuccess(recordings)
                  ? recordings?.meta?.total_results
                  : 0
              }
              onPageChange={setPage}
              onPageSizeChange={setPageSize}
              isLoading={isLoading}
              sorting={sorting}
              setSorting={setSorting}
              rowSelection={rowSelection}
              setRowSelection={setRowSelection}
              className={{
                containerClassName: cn('p-3 mb-0', {
                  'w-full':
                    isResponseSuccess(recordings) &&
                    recordings?.data?.length === 0,
                }),
                headerColumnClassName: 'text-nowrap',
              }}
            />
          )}
        </div>
      </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={formikResetHandler}>
          <div className='p-4 flex flex-col gap-1.5'>
            <SelectInput
              label='Area'
              placeholder='Pilih Area'
              options={areaOptions}
              value={formik.values.area_id}
              onChange={handleFilterAreaChange}
              onInputChange={setAreaInputValue}
              isLoading={isLoadingAreaOptions}
              isClearable
              onMenuScrollToBottom={loadMoreAreas}
              className={{ wrapper: 'w-full' }}
            />

            <SelectInput
              label='Lokasi'
              placeholder='Pilih Lokasi'
              options={locationOptions}
              value={formik.values.location_id}
              onChange={handleFilterLocationChange}
              onInputChange={setLocationInputValue}
              isLoading={isLoadingLocationOptions}
              isClearable
              onMenuScrollToBottom={loadMoreLocations}
              isDisabled={!formik.values.area_id?.value}
              className={{ wrapper: 'w-full' }}
            />

            <SelectInput
              label='Project Flock'
              placeholder='Pilih Project Flock'
              options={projectFlockOptions}
              value={formik.values.project_flock_id}
              onChange={handleFilterProjectFlockChange}
              onInputChange={setProjectFlockInputValue}
              isLoading={isLoadingProjectFlocks}
              isClearable
              onMenuScrollToBottom={loadMoreProjectFlocks}
              isDisabled={!formik.values.location_id?.value}
              className={{ wrapper: 'w-full' }}
            />

            <SelectInput
              label='Kandang'
              placeholder='Pilih Kandang'
              options={kandangOptions}
              value={formik.values.kandang_id}
              onChange={handleFilterKandangChange}
              isLoading={!formik.values.project_flock_id?.value}
              isClearable
              isDisabled={!formik.values.project_flock_id?.value}
              className={{ wrapper: 'w-full' }}
            />

            <SelectInput
              label='Kategori'
              placeholder='Pilih Kategori'
              options={projectFlockCategoryOptions}
              value={formik.values.project_flock_category}
              onChange={(val) => {
                formik.setFieldValue('project_flock_category', val);
              }}
              isClearable
              className={{ wrapper: 'w-full' }}
            />

            <SelectInput
              label='Status Approval'
              placeholder='Pilih Status Approval'
              options={recordingApprovalStatusOptions}
              value={formik.values.approval_status}
              onChange={(val) => {
                formik.setFieldValue('approval_status', val);
              }}
              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.isValid || formik.isSubmitting}
            >
              Apply Filter
            </Button>
          </div>
        </form>
      </Modal>

      <ConfirmationModal
        ref={singleDeleteModal.ref}
        type='error'
        text={`Apakah anda yakin ingin menghapus data Recording ini?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          isLoading: isDeleteLoading,
          onClick: singleDeleteHandler,
        }}
      />

      <Modal
        ref={exportProgressInputModal.ref}
        className={{
          modalBox: 'max-w-lg rounded-lg p-0',
        }}
        closeOnBackdrop
      >
        <div className='flex flex-col'>
          <div className='flex items-center justify-between border-b border-base-content/10 p-4'>
            <h4 className='text-sm font-semibold text-base-content'>
              Ekspor Input Progress
            </h4>
            <Button
              variant='ghost'
              color='none'
              onClick={() => {
                exportProgressInputModal.closeModal();
                resetExportProgressForm();
              }}
              className='p-1'
            >
              <Icon icon='mdi:close' width={20} height={20} />
            </Button>
          </div>

          <div className='flex flex-col gap-4 p-4'>
            <DateInput
              name='export_progress_start_date'
              label='Tanggal Mulai'
              value={exportProgressStartDate}
              onChange={exportProgressStartDateChangeHandler}
              isNestedModal
              required
            />

            <DateInput
              name='export_progress_end_date'
              label='Tanggal Selesai'
              value={exportProgressEndDate}
              onChange={exportProgressEndDateChangeHandler}
              isNestedModal
              required
            />
          </div>

          <div className='flex justify-end gap-3 border-t border-base-content/10 p-4'>
            <Button
              variant='outline'
              color='none'
              onClick={() => {
                exportProgressInputModal.closeModal();
                resetExportProgressForm();
              }}
              className='px-3 py-2.5'
            >
              Batal
            </Button>
            <Button
              color='success'
              onClick={submitExportProgressInputHandler}
              isLoading={isExportProgressLoading}
              disabled={!exportProgressStartDate || !exportProgressEndDate}
              className='px-3 py-2.5'
            >
              Submit
            </Button>
          </div>
        </div>
      </Modal>

      <ConfirmationModalWithNotes
        ref={approveModal.ref}
        type='success'
        text={`Apakah anda yakin ingin approve data recording ini (${eligibleRowIds.length} data dari ${selectedRowIds.length} yang dipilih)?`}
        secondaryButton={{
          text: 'Tidak',
          onClick: () => {
            setApprovalNotes('');
            approveModal.closeModal();
          },
        }}
        primaryButton={{
          text: 'Ya',
          color: 'success',
          isLoading: isApproveLoading,
          onClick: approveHandler,
        }}
        placeholder='(Opsional) Tambahkan catatan untuk approval ini...'
        rows={3}
      />

      <ConfirmationModalWithNotes
        ref={rejectModal.ref}
        type='error'
        text={`Apakah anda yakin ingin reject data recording ini (${eligibleRowIds.length} data dari ${selectedRowIds.length} yang dipilih)?`}
        secondaryButton={{
          text: 'Tidak',
          onClick: () => {
            setApprovalNotes('');
            rejectModal.closeModal();
          },
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          isLoading: isRejectLoading,
          onClick: rejectHandler,
        }}
        placeholder='(Opsional) Tambahkan catatan untuk reject ini...'
        rows={3}
      />
    </>
  );
};

export default RecordingTable;
