'use client';

import React, {
  useCallback,
  useState,
  useMemo,
  useEffect,
  useRef,
} from 'react';
import { RefObject } from 'react';
import useSWR from 'swr';
import { Icon } from '@iconify/react';
import { SortingState, CellContext } from '@tanstack/react-table';
import { cn, formatDate, formatNumber } from '@/lib/helper';
import RequirePermission from '@/components/helper/RequirePermission';
import { useModal } from '@/components/Modal';
import Modal 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 from '@/components/input/SelectInput';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import { ROWS_OPTIONS } from '@/config/constant';
import Table from '@/components/Table';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import { type Recording } from '@/types/api/production/recording';
import { RecordingApi } from '@/services/api/production';
import { ApprovalApi } from '@/services/api/approval';
import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import toast from 'react-hot-toast';
import Badge from '@/components/Badge';
import CheckboxInput from '@/components/input/CheckboxInput';
import { useUiStore } from '@/stores/ui/ui.store';
import { BaseApproval, BaseApiResponse } from '@/types/api/api-general';

const RowOptionsMenu = ({
  type = 'dropdown',
  props,
  deleteClickHandler,
  approveClickHandler,
  rejectClickHandler,
}: {
  type: 'dropdown' | 'collapse';
  props: CellContext<Recording, unknown>;
  deleteClickHandler: () => void;
  approveClickHandler: () => void;
  rejectClickHandler: () => void;
}) => {
  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 isApproved = isRecordingApproved(props.row.original);
  const isRejected = isRecordingRejected(props.row.original);

  return (
    <RowOptionsMenuWrapper type={type}>
      <RequirePermission permissions='lti.production.recording.detail'>
        <Button
          href={`/production/recording/detail/?recordingId=${props.row.original.id}`}
          variant='ghost'
          color='primary'
          className='justify-start text-sm'
        >
          <Icon icon='mdi:eye-outline' width={16} height={16} />
          Detail
        </Button>
      </RequirePermission>
      <RequirePermission permissions='lti.production.recording.update'>
        <Button
          href={`/production/recording/detail/edit/?recordingId=${props.row.original.id}`}
          variant='ghost'
          color='warning'
          className='justify-start text-sm'
        >
          <Icon icon='mdi:pencil-outline' width={16} height={16} />
          Edit
        </Button>
      </RequirePermission>
      {!isApproved && !isRejected && (
        <RequirePermission permissions='lti.production.recording.approve'>
          <Button
            onClick={approveClickHandler}
            variant='ghost'
            color='success'
            className='justify-start text-sm'
          >
            <Icon icon='material-symbols:check' width={16} height={16} />
            Approve
          </Button>
        </RequirePermission>
      )}
      {!isApproved && !isRejected && (
        <RequirePermission permissions='lti.production.recording.approve'>
          <Button
            onClick={rejectClickHandler}
            variant='ghost'
            color='error'
            className='justify-start text-sm'
          >
            <Icon icon='material-symbols:close' width={16} height={16} />
            Reject
          </Button>
        </RequirePermission>
      )}
      <RequirePermission permissions='lti.production.recording.delete'>
        <Button
          onClick={deleteClickHandler}
          variant='ghost'
          color='error'
          className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
        >
          <Icon
            icon='mdi:delete-outline'
            width={16}
            height={16}
            className='justify-start text-sm'
          />
          Delete
        </Button>
      </RequirePermission>
    </RowOptionsMenuWrapper>
  );
};

const ApprovalHistoryModal = ({
  ref,
  currentApproval,
  module_name = 'RECORDINGS',
  module_id,
}: {
  ref: RefObject<HTMLDialogElement | null>;
  currentApproval?: BaseApproval;
  module_name?: string;
  module_id?: number | undefined;
}) => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const approvalHistoryUrl = useMemo(() => {
    if (!isModalOpen) return null;
    const params = new URLSearchParams({
      module_name: module_name,
      group_step_number: 'true',
    });

    if (module_id) {
      params.append('module_id', module_id.toString());
    }

    return `${ApprovalApi.basePath}?${params.toString()}`;
  }, [module_name, module_id, isModalOpen]);

  type GroupedApprovalResponse = {
    step_number: number;
    step_name: string;
    approvals: BaseApproval[];
  };

  const fetchGroupedApprovals = async (
    url: string
  ): Promise<BaseApiResponse<GroupedApprovalResponse[]>> => {
    return (await ApprovalApi.getAllFetcher(url)) as BaseApiResponse<
      GroupedApprovalResponse[]
    >;
  };

  const { data: approvalHistoryData, isLoading } = useSWR<
    BaseApiResponse<GroupedApprovalResponse[]>
  >(approvalHistoryUrl, fetchGroupedApprovals);

  useEffect(() => {
    const checkModalOpen = () => {
      const isOpen = ref.current?.open || false;
      setIsModalOpen(isOpen);
    };

    checkModalOpen();

    const observer = new MutationObserver(checkModalOpen);
    if (ref.current) {
      observer.observe(ref.current, {
        attributes: true,
        attributeFilter: ['open'],
      });
    }

    return () => observer.disconnect();
  }, [ref]);

  const approvalHistory = useMemo(() => {
    if (!approvalHistoryData || approvalHistoryData.status !== 'success')
      return [];

    const groupedData = approvalHistoryData.data || [];
    const flattenedApprovals: BaseApproval[] = [];

    groupedData.forEach((group) => {
      group.approvals.forEach((approval) => {
        flattenedApprovals.push(approval);
      });
    });

    return flattenedApprovals;
  }, [approvalHistoryData]);

  const closeModalHandler = () => {
    ref.current?.close();
  };

  return (
    <Modal ref={ref} className={{ modalBox: 'max-w-2xl' }}>
      <div className='w-full flex flex-col gap-6'>
        {/* Header */}
        <div className='flex items-center justify-between'>
          <h2 className='text-xl font-bold'>Riwayat Approval</h2>
          <Button
            onClick={closeModalHandler}
            variant='ghost'
            className='btn-circle btn-sm p-0'
          >
            <Icon icon='mdi:close' width={20} height={20} />
          </Button>
        </div>

        {isLoading ? (
          <div className='flex justify-center py-8'>
            <span className='loading loading-spinner loading-lg'></span>
          </div>
        ) : (
          <>
            {/* Current Status */}
            {currentApproval && (
              <div className='bg-base-200 rounded-lg p-4'>
                <h3 className='font-semibold mb-2'>Status Saat Ini</h3>
                <div className='flex items-center gap-3'>
                  <Badge
                    variant='soft'
                    color={
                      currentApproval.action === 'APPROVED'
                        ? 'success'
                        : currentApproval.action === 'REJECTED'
                          ? 'error'
                          : currentApproval.action === 'UPDATED'
                            ? 'warning'
                            : 'info'
                    }
                  >
                    {currentApproval.step_name}
                  </Badge>
                  <span className='text-sm text-gray-600'>
                    {currentApproval.action === 'APPROVED' && 'Disetujui'}
                    {currentApproval.action === 'REJECTED' && 'Ditolak'}
                    {currentApproval.action === 'CREATED' && 'Dibuat'}
                    {currentApproval.action === 'UPDATED' && 'Diperbarui'}
                  </span>
                </div>
                {currentApproval.notes && (
                  <p className='mt-2 text-sm text-gray-600'>
                    <span className='font-medium'>Catatan:</span>{' '}
                    {currentApproval.notes}
                  </p>
                )}
                <p className='mt-1 text-xs text-gray-500'>
                  Oleh: {currentApproval.action_by.name} •{' '}
                  {formatDate(currentApproval.action_at, 'DD MMMM YYYY HH:mm')}
                </p>
              </div>
            )}

            {/* Full History */}
            {approvalHistory.length > 0 && (
              <div className='space-y-4'>
                <h3 className='font-semibold'>Riwayat Lengkap</h3>
                <div className='overflow-x-auto'>
                  <table className='table table-sm'>
                    <thead>
                      <tr>
                        <th>Tahap</th>
                        <th>Aksi</th>
                        <th>Catatan</th>
                        <th>Oleh</th>
                        <th>Waktu</th>
                      </tr>
                    </thead>
                    <tbody>
                      {approvalHistory
                        .sort(
                          (a: BaseApproval, b: BaseApproval) =>
                            new Date(b.action_at).getTime() -
                            new Date(a.action_at).getTime()
                        )
                        .map((approval: BaseApproval, index: number) => (
                          <tr key={index}>
                            <td>{approval.step_name}</td>
                            <td>
                              <Badge
                                variant='soft'
                                color={
                                  approval.action === 'APPROVED'
                                    ? 'success'
                                    : approval.action === 'REJECTED'
                                      ? 'error'
                                      : approval.action === 'UPDATED'
                                        ? 'warning'
                                        : 'info'
                                }
                                size='sm'
                              >
                                {approval.action === 'APPROVED' && 'Disetujui'}
                                {approval.action === 'REJECTED' && 'Ditolak'}
                                {approval.action === 'CREATED' && 'Dibuat'}
                                {approval.action === 'UPDATED' && 'Diperbarui'}
                              </Badge>
                            </td>
                            <td className='max-w-xs'>
                              <div className='truncate'>
                                {approval.notes || '-'}
                              </div>
                            </td>
                            <td>{approval.action_by.name}</td>
                            <td className='text-xs'>
                              {formatDate(
                                approval.action_at,
                                'DD MMMM YYYY HH:mm'
                              )}
                            </td>
                          </tr>
                        ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </Modal>
  );
};

const RecordingTable = () => {
  const { searchValue, setSearchValue, resetSearchValue } = useUiStore();
  const previousPathRef = useRef<string | null>(null);

  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      search: searchValue,
      areaFilter: '',
      locationFilter: '',
      kandangFilter: '',
      periodFilter: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      search: 'search',
      areaFilter: 'area_id',
      locationFilter: 'location_id',
      kandangFilter: 'kandang_id',
      periodFilter: 'period',
    },
  });

  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 singleDeleteModal = useModal();
  const approveModal = useModal();
  const rejectModal = useModal();
  const approvalHistoryModal = useModal();

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

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

  useEffect(() => {
    // Store current path on mount
    previousPathRef.current = window.location.pathname;

    return () => {
      const currentPath = window.location.pathname;

      // if both paths are within /production/recording module
      const isCurrentPathRecording = currentPath.includes(
        '/production/recording'
      );
      const isPreviousPathRecording = previousPathRef.current?.includes(
        '/production/recording'
      );

      // reset if we outside recording module entirely
      if (isPreviousPathRecording && !isCurrentPathRecording) {
        resetSearchValue();
      }
    };
  }, [resetSearchValue]);

  const searchChangeHandler = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      updateFilter('search', e.target.value);
      setSearchValue(e.target.value);
      setPage(1);
    },
    [updateFilter, setSearchValue, setPage]
  );

  const pageSizeChangeHandler = useCallback(
    (val: OptionType | OptionType[] | null) => {
      const newVal = val as OptionType;
      setPageSize(newVal.value as number);
      setPage(1);
    },
    [setPageSize, setPage]
  );

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

    await RecordingApi.delete(selectedRecording?.id as number);
    refreshRecordings();

    singleDeleteModal.closeModal();
    toast.success('Successfully delete Recording!');
    setIsDeleteLoading(false);
  };

  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]);

  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]);

  return (
    <div className='w-full p-0 sm:p-4'>
      <div className='flex flex-col gap-2 mb-4'>
        <div className='w-full flex flex-col xl:flex-row justify-between items-end xl:items-center gap-2'>
          <div className='w-full sm:w-fit flex flex-col sm:flex-row self-start gap-2'>
            <RequirePermission permissions='lti.production.recording.create'>
              <Button
                href='/production/recording/add'
                variant='outline'
                color='primary'
                className='w-full sm:w-fit'
              >
                <Icon icon='ic:round-plus' width={24} height={24} />
                Tambah
              </Button>
            </RequirePermission>

            {selectedRowIds.length > 0 && (
              <>
                <RequirePermission permissions='lti.production.recording.approve'>
                  <Button
                    variant='outline'
                    color='success'
                    onClick={() => {
                      setApprovalNotes('');
                      approveModal.openModal();
                    }}
                    disabled={
                      selectedRowIds.length === 0 || eligibleRowIds.length === 0
                    }
                    className='w-full sm:w-fit'
                  >
                    <Icon
                      icon='material-symbols:check'
                      width={24}
                      height={24}
                    />
                    Approve
                  </Button>
                </RequirePermission>

                <RequirePermission permissions='lti.production.recording.approve'>
                  <Button
                    variant='outline'
                    color='error'
                    onClick={() => {
                      setApprovalNotes('');
                      rejectModal.openModal();
                    }}
                    disabled={
                      selectedRowIds.length === 0 || eligibleRowIds.length === 0
                    }
                    className='w-full sm:w-fit'
                  >
                    <Icon
                      icon='material-symbols:close'
                      width={24}
                      height={24}
                    />
                    Reject
                  </Button>
                </RequirePermission>
              </>
            )}
          </div>

          <DebouncedTextInput
            name='search'
            placeholder='Cari Recording'
            value={tableFilterState.search}
            onChange={searchChangeHandler}
            className={{ wrapper: 'sm:max-w-3xs' }}
          />
        </div>

        <div className='flex justify-end gap-4'>
          <SelectInput
            label='Baris'
            options={ROWS_OPTIONS}
            value={{
              label: String(tableFilterState.pageSize),
              value: tableFilterState.pageSize,
            }}
            onChange={pageSizeChangeHandler}
            className={{
              wrapper: 'col-span-6 sm:col-span-4 max-w-28 sm:justify-self-end',
            }}
          />
        </div>
      </div>

      <Table<Recording>
        data={isResponseSuccess(recordings) ? recordings?.data : []}
        columns={[
          {
            id: 'select',
            header: ({ table }) => {
              const allRows = table.getRowModel().rows;
              const selectableRows = allRows.filter((row) => {
                const recording = row.original;
                return !isRecordingApproved(recording);
              });

              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 isDisabled = isRecordingApproved(recording);

              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 category =
                props.row.original.project_flock?.project_flock_category;
              if (!category) return '-';
              const color = category === 'LAYING' ? 'info' : 'warning';
              return (
                <Badge variant='soft' color={color}>
                  {category}
                </Badge>
              );
            },
          },
          {
            header: 'Umur (hari)',
            cell: (props) => {
              return (
                <>
                  <span>
                    {props.row.original.day} (Minggu ke-
                    {props.row.original.project_flock.production_standart.week})
                  </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)}%`
                        : '-'}
                    </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)}%`
                        : '-'}
                    </div>
                  );
                },
              },
            ],
          },
          {
            header: 'Status Approval',
            cell: (props) => {
              const approval = props.row.original.approval;
              if (!approval) return '-';

              const statusColor =
                approval.action === 'APPROVED'
                  ? 'success'
                  : approval.action === 'REJECTED'
                    ? 'error'
                    : approval.action === 'UPDATED'
                      ? 'warning'
                      : 'info';

              const openApprovalHistory = () => {
                setSelectedRecording(props.row.original);
                approvalHistoryModal.openModal();
              };

              return (
                <Badge
                  variant='soft'
                  color={statusColor}
                  className={{
                    badge:
                      'cursor-pointer hover:opacity-80 transition-opacity whitespace-nowrap',
                  }}
                  onClick={openApprovalHistory}
                >
                  {approval.step_name || approval.action}
                </Badge>
              );
            },
          },
          {
            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: 'Status Grading Telur',
          //   cell: (props) => {
          //     const status = props.row.original.egg_grading_status;
          //     if (!status) return '-';
          //     const color = status === 'COMPLETED' ? 'success' : 'warning';
          //     return (
          //       <Badge variant='soft' color={color}>
          //         {status}
          //       </Badge>
          //     );
          //   },
          // },
          {
            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 (
                <>
                  {currentPageSize > 2 && (
                    <RowDropdownOptions isLast2Rows={isLast2Rows}>
                      <RowOptionsMenu
                        type='dropdown'
                        props={props}
                        deleteClickHandler={deleteClickHandler}
                        approveClickHandler={approveClickHandler}
                        rejectClickHandler={rejectClickHandler}
                      />
                    </RowDropdownOptions>
                  )}

                  {currentPageSize <= 2 && (
                    <RowCollapseOptions>
                      <RowOptionsMenu
                        type='collapse'
                        props={props}
                        deleteClickHandler={deleteClickHandler}
                        approveClickHandler={approveClickHandler}
                        rejectClickHandler={rejectClickHandler}
                      />
                    </RowCollapseOptions>
                  )}
                </>
              );
            },
          },
        ]}
        pageSize={tableFilterState.pageSize}
        page={isResponseSuccess(recordings) ? recordings?.meta?.page : 0}
        totalItems={
          isResponseSuccess(recordings) ? recordings?.meta?.total_results : 0
        }
        onPageChange={setPage}
        isLoading={isLoading}
        sorting={sorting}
        setSorting={setSorting}
        rowSelection={rowSelection}
        setRowSelection={setRowSelection}
        className={{
          containerClassName: cn({
            'mb-20':
              isResponseSuccess(recordings) && recordings?.data?.length === 0,
          }),
          tableWrapperClassName: 'overflow-x-auto',
          tableClassName: 'w-full table-auto text-sm',
          headerRowClassName: 'border-b border-b-gray-200',
          headerColumnClassName:
            'px-4 py-3 text-xs font-semibold text-gray-500 whitespace-nowrap border-l border-l-gray-200 border-r border-r-gray-200 border-t border-t-gray-200 border-gray-200 border-b-0',
          bodyRowClassName:
            'hover:bg-gray-50 transition-colors border-b border-gray-200 first:border-t first:border-t-gray-200 border-l border-l-gray-200 border-r border-r-gray-200',
          bodyColumnClassName:
            'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
        }}
      />

      <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,
        }}
      />

      <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(''),
        }}
        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(''),
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          isLoading: isRejectLoading,
          onClick: rejectHandler,
        }}
        placeholder='(Opsional) Tambahkan catatan untuk reject ini...'
        rows={3}
      />

      <ApprovalHistoryModal
        ref={approvalHistoryModal.ref}
        currentApproval={selectedRecording?.approval}
        module_name={'RECORDINGS'}
        module_id={selectedRecording?.id}
      />
    </div>
  );
};

export default RecordingTable;
