'use client';

import { ChangeEventHandler, useCallback, useMemo, useState } from 'react';
import useSWR from 'swr';
import {
  CellContext,
  ColumnDef,
  SortingState,
  Updater,
} from '@tanstack/react-table';
import toast from 'react-hot-toast';

import Link from 'next/link';
import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DateInput from '@/components/input/DateInput';
import Button from '@/components/Button';
import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import RequirePermission from '@/components/helper/RequirePermission';
import StatusBadge from '@/components/helper/StatusBadge';
import PurchaseTableSkeleton from '@/components/pages/purchase/skeleton/PurchaseTableSkeleton';
import PurchaseInlineFilter from '@/components/pages/purchase/PurchaseInlineFilter';
import Dropdown from '@/components/dropdown/Dropdown';
import { OptionType } from '@/components/input/SelectInput';

import { cn, formatCurrency, formatDate, formatNumber } from '@/lib/helper';
import { getErrorMessage, isResponseSuccess } from '@/lib/api-helper';

import { useTableFilter } from '@/services/hooks/useTableFilter';
import { Purchase, PurchaseFilter } from '@/types/api/purchase/purchase';
import { PurchaseApi } from '@/services/api/purchase';
import { Color } from '@/types/theme';
import { PURCHASE_ORDER_APPROVAL_LINE } from '@/config/approval-line';

type PurchaseTableFilters = {
  search: string;
  sort_by: string;
  order_by: string;
  start_date: string;
  end_date: string;
  filter_by: string;
  po_date: string;
  approval_status: string;
  product_category_id: string;
  product_category_name: string;
  supplier_id: string;
  supplier_name: string;
  area_id: string;
  area_name: string;
  location_id: string;
  location_name: string;
  project_flock_id: string;
  project_flock_name: string;
  project_flock_kandang_id: string;
  project_flock_kandang_name: string;
};

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

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

const statusBadgeColorMap: Record<string, Color> = {
  APPROVED: 'success',
  Disetujui: 'success',
  approved: 'success',
  disetujui: 'success',
  REJECTED: 'error',
  Ditolak: 'error',
  rejected: 'error',
  ditolak: 'error',
  CREATED: 'neutral',
  Dibuat: 'neutral',
  created: 'neutral',
  dibuat: 'neutral',
  UPDATED: 'warning',
  Diperbarui: 'warning',
  updated: 'warning',
  diperbarui: 'warning',
};

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

// ===== ROW OPTIONS MENU =====
const RowOptionsMenu = ({
  popoverPosition = 'bottom',
  props,
  deleteClickHandler,
}: {
  popoverPosition: 'bottom' | 'top';
  props: CellContext<Purchase, unknown>;
  deleteClickHandler: () => void;
}) => {
  const popoverId = `purchase#${props.row.original.id}`;
  const popoverAnchorName = `--anchor-purchase#${props.row.original.id}`;

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

  return (
    <div className='relative'>
      <PopoverButton
        tabIndex={0}
        variant='ghost'
        color='none'
        popoverTarget={popoverId}
        anchorName={popoverAnchorName}
      >
        <Icon icon='material-symbols:more-vert' width={16} height={16} />
      </PopoverButton>

      <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.purchase.detail'>
            <Button
              href={`/purchase/detail/?purchaseId=${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} />
              Detail
            </Button>
          </RequirePermission>

          <RequirePermission permissions='lti.purchase.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 PurchaseTable = () => {
  // ===== TABLE FILTER STATE =====
  const {
    state: tableFilterState,
    setFilters,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter<PurchaseTableFilters>({
    initial: {
      search: '',
      sort_by: '',
      order_by: '',
      start_date: '',
      end_date: '',
      filter_by: '',
      po_date: '',
      approval_status: '',
      product_category_id: '',
      product_category_name: '',
      supplier_id: '',
      supplier_name: '',
      area_id: '',
      area_name: '',
      location_id: '',
      location_name: '',
      project_flock_id: '',
      project_flock_name: '',
      project_flock_kandang_id: '',
      project_flock_kandang_name: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      sort_by: 'sort_by',
      order_by: 'sort_order',
      start_date: 'start_date',
      end_date: 'end_date',
      filter_by: 'filter_by',
      po_date: 'po_date',
      approval_status: 'approval_status',
      product_category_id: 'product_category_id',
      supplier_id: 'supplier_id',
      area_id: 'area_id',
      location_id: 'location_id',
      project_flock_id: 'project_flock_id',
      project_flock_kandang_id: 'project_flock_kandang_id',
    },
    excludeKeysFromUrl: [
      'product_category_name',
      'supplier_name',
      'area_name',
      'location_name',
      'project_flock_name',
      'project_flock_kandang_name',
    ],
    persist: true,
    storeName: 'purchase-table',
  });

  // ===== STATE MANAGEMENT =====
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);
  const [isLoadingExportingToExcel, setIsLoadingExportingToExcel] =
    useState(false);
  const [isExportProgressLoading, setIsExportProgressLoading] = useState(false);
  const [selectedPurchase, setSelectedPurchase] = useState<Purchase | null>(
    null
  );
  const [exportProgressStartDate, setExportProgressStartDate] = useState('');
  const [exportProgressEndDate, setExportProgressEndDate] = useState('');
  const sorting: SortingState = tableFilterState.sort_by
    ? [
        {
          id: tableFilterState.sort_by,
          desc: tableFilterState.order_by === 'desc',
        },
      ]
    : [];

  const handleSortingChange = (updater: Updater<SortingState>) => {
    const next = typeof updater === 'function' ? updater(sorting) : updater;
    if (next.length > 0) {
      updateFilter('sort_by', next[0].id, true);
      updateFilter('order_by', next[0].desc ? 'desc' : 'asc', true);
    } else {
      updateFilter('sort_by', '', true);
      updateFilter('order_by', '', true);
    }
  };

  // ===== MODAL HOOKS =====
  const deleteModal = useModal();
  const exportProgressInputModal = useModal();

  // ===== API DATA FETCHING =====
  const {
    data: purchaseRequests,
    isLoading,
    mutate: refreshPurchaseRequests,
  } = useSWR(
    `${PurchaseApi.basePath}${getTableFilterQueryString()}`,
    PurchaseApi.getAllFetcher
  );

  // ===== TABLE COLUMNS DEFINITION =====
  const purchaseColumns: ColumnDef<Purchase>[] = [
    {
      accessorKey: 'po_number',
      header: 'No. PR/PO',
      cell: (props) => {
        const { pr_number, po_number } = props.row.original;
        return po_number ? po_number : pr_number;
      },
    },
    {
      accessorKey: 'po_expedition',
      header: 'Ekspedisi PO',
      cell: (props) => {
        const poExpedition = props.row.original.po_expedition;
        if (!poExpedition || poExpedition.length === 0) return '-';
        return (
          <ul className='list-disc pl-4'>
            {poExpedition.map((exp, index) => {
              return (
                <li key={index}>
                  <Link
                    href={`/expense/detail/?expenseId=${exp.id}`}
                    className='p-0 h-auto text-primary underline'
                  >
                    {exp.refrence}
                  </Link>
                </li>
              );
            })}
          </ul>
        );
      },
    },
    {
      accessorKey: 'requester_name',
      header: 'Nama Pengaju',
      cell: (props) => props.row.original.requester_name || '-',
    },
    {
      accessorKey: 'po_date',
      header: 'Tgl. PO',
      cell: (props) =>
        props.row.original.po_date
          ? formatDate(props.row.original.po_date, 'DD MMM YYYY')
          : '-',
    },
    {
      accessorKey: 'received_date',
      header: 'Tgl. Terima',
      cell: (props) =>
        props.row.original.received_date
          ? formatDate(props.row.original.received_date, 'DD MMM YYYY')
          : '-',
    },
    {
      accessorKey: 'due_date',
      header: 'Jatuh Tempo',
      cell: (props) =>
        props.row.original.due_date
          ? formatDate(props.row.original.due_date, 'DD MMM YYYY')
          : '-',
    },
    {
      header: 'Aging',
      enableSorting: false,
      cell: (props) => {
        const purchase = props.row.original;
        if (!purchase.po_date) return '-';
        const poDate = new Date(purchase.po_date);
        const today = new Date();
        const diffTime = Math.abs(today.getTime() - poDate.getTime());
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        return `${diffDays} hari`;
      },
    },
    {
      accessorKey: 'supplier',
      header: 'Vendor',
      cell: (props) => props.row.original.supplier.name,
    },
    {
      accessorKey: 'location',
      header: 'Lokasi',
      cell: (props) => props.row.original.location?.name || '-',
    },
    {
      accessorKey: 'warehouse',
      header: 'Gudang',
      enableSorting: false,
      cell: (props) => {
        const items = props.row.original.items;
        if (!items || items.length === 0) return '-';
        return (
          <ul className='list-disc pl-4'>
            {items.map((item, index) => (
              <li key={index}>{item.warehouse?.name ?? '-'}</li>
            ))}
          </ul>
        );
      },
    },
    {
      accessorKey: 'products',
      header: 'Produk',
      cell: (props) => {
        const products = props.row.original.products;
        if (!products || products.length === 0) return '-';
        return (
          <ul className='list-disc pl-4'>
            {products.map((product, index) => (
              <li key={index}>{product.name}</li>
            ))}
          </ul>
        );
      },
    },
    {
      accessorKey: 'total_qty',
      header: 'Kuantitas',
      enableSorting: false,
      cell: (props) => {
        const items = props.row.original.items;
        if (!items || items.length === 0) return '-';
        return (
          <ul className='list-disc pl-4'>
            {items.map((item, index) => (
              <li key={index}>{formatNumber(item.total_qty ?? 0)}</li>
            ))}
          </ul>
        );
      },
    },
    {
      accessorKey: 'uom',
      header: 'Satuan',
      enableSorting: false,
      cell: (props) => {
        const items = props.row.original.items;
        if (!items || items.length === 0) return '-';
        return (
          <ul className='list-disc pl-4'>
            {items.map((item, index) => (
              <li key={index}>{item.product?.uom?.name ?? '-'}</li>
            ))}
          </ul>
        );
      },
    },
    {
      accessorKey: 'price',
      header: 'Harga',
      enableSorting: false,
      cell: (props) => {
        const items = props.row.original.items;
        if (!items || items.length === 0) return '-';
        return (
          <ul className='list-disc pl-4'>
            {items.map((item, index) => (
              <li key={index}>{formatCurrency(item.price ?? 0)}</li>
            ))}
          </ul>
        );
      },
    },
    {
      accessorKey: 'total_price',
      header: 'Total Harga',
      enableSorting: false,
      cell: (props) => {
        const items = props.row.original.items;
        if (!items || items.length === 0) return '-';
        return (
          <ul className='list-disc pl-4'>
            {items.map((item, index) => (
              <li key={index}>{formatCurrency(item.total_price ?? 0)}</li>
            ))}
          </ul>
        );
      },
    },
    {
      accessorKey: 'products_total',
      header: 'Total Harga Produk',
      cell: (props) => formatCurrency(props.row.original.products_total ?? 0),
    },
    {
      accessorKey: 'expedition_vendor',
      header: 'Vendor Ekspedisi',
      enableSorting: false,
      cell: (props) => {
        const items = props.row.original.items;
        if (!items || items.length === 0) return '-';
        return (
          <ul className='list-disc pl-4'>
            {items.map((item, index) => (
              <li key={index}>{item.expedition_vendor?.name ?? '-'}</li>
            ))}
          </ul>
        );
      },
    },
    {
      accessorKey: 'expedition_qty',
      header: 'Qty Ekspedisi',
      enableSorting: false,
      cell: (props) => {
        const items = props.row.original.items;
        if (!items || items.length === 0) return '-';
        return (
          <ul className='list-disc pl-4'>
            {items.map((item, index) => (
              <li key={index}>
                {item.expedition_qty != null
                  ? formatNumber(item.expedition_qty)
                  : '-'}
              </li>
            ))}
          </ul>
        );
      },
    },
    {
      accessorKey: 'transport_per_item',
      header: 'Harga Ekspedisi',
      enableSorting: false,
      cell: (props) => {
        const items = props.row.original.items;
        if (!items || items.length === 0) return '-';
        return (
          <ul className='list-disc pl-4'>
            {items.map((item, index) => (
              <li key={index}>
                {item.transport_per_item != null
                  ? formatCurrency(item.transport_per_item)
                  : '-'}
              </li>
            ))}
          </ul>
        );
      },
    },
    {
      accessorKey: 'item_expedition_total',
      header: 'Total Ekspedisi',
      enableSorting: false,
      cell: (props) => {
        const items = props.row.original.items;
        if (!items || items.length === 0) return '-';
        return (
          <ul className='list-disc pl-4'>
            {items.map((item, index) => (
              <li key={index}>
                {item.expedition_total != null
                  ? formatCurrency(item.expedition_total)
                  : '-'}
              </li>
            ))}
          </ul>
        );
      },
    },
    {
      accessorKey: 'expedition_total',
      header: 'Total Ekspedisi Semua Produk',
      cell: (props) => formatCurrency(props.row.original.expedition_total ?? 0),
    },
    {
      accessorKey: 'grand_total_all',
      header: 'Grand Total All',
      cell: (props) => formatCurrency(props.row.original.grand_total_all ?? 0),
    },
    {
      accessorKey: 'status',
      header: 'Status Approval',
      cell: (props) => {
        const approval = props.row.original.latest_approval;
        if (!approval) return '-';

        const status = approval.action;

        let statusColor: Color = 'neutral';

        if (status === 'REJECTED') {
          statusColor = getStatusBadgeColor(status);
        } else {
          switch (approval.step_number) {
            case 1:
              statusColor = 'neutral';
              break;
            case 2:
              statusColor = 'primary';
              break;
            case 3:
              statusColor = 'info';
              break;
            case 4:
              statusColor = 'warning';
              break;
            case 5:
              statusColor = 'success';
              break;
          }
        }

        const statusText = approval.step_name || getStatusText(status);

        return (
          <StatusBadge
            color={statusColor}
            text={statusText}
            className={{
              badge: 'whitespace-nowrap max-w-max w-fit',
            }}
          />
        );
      },
    },
    {
      accessorKey: 'notes',
      header: 'Notes',
      cell: (props) => props.row.original.notes || '-',
    },
    {
      accessorKey: 'created_at',
      header: 'Tanggal Dibuat',
      cell: (props) =>
        props.row.original.created_at
          ? formatDate(props.row.original.created_at, 'DD MMM YYYY')
          : '-',
    },
    {
      header: 'Aksi',
      cell: (props) => {
        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 = () => {
          setSelectedPurchase(props.row.original);
          deleteModal.openModal();
        };

        return (
          <RowOptionsMenu
            popoverPosition={isLast2Rows ? 'top' : 'bottom'}
            props={props}
            deleteClickHandler={deleteClickHandler}
          />
        );
      },
    },
  ];

  // ===== EVENT HANDLERS =====
  const confirmationModalDeleteClickHandler = useCallback(async () => {
    setIsDeleteLoading(true);

    try {
      const deleteResponse = await PurchaseApi.delete(
        selectedPurchase?.id as number
      );

      if (isResponseSuccess(deleteResponse)) {
        refreshPurchaseRequests();
        deleteModal.closeModal();
        toast.success('Berhasil menghapus data permintaan pembelian!');
      } else {
        toast.error(deleteResponse?.message ?? 'Gagal menghapus data!');
      }
    } catch {
      toast.error('Gagal menghapus data permintaan pembelian!');
    }

    setIsDeleteLoading(false);
  }, [selectedPurchase?.id, refreshPurchaseRequests, deleteModal]);

  const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = useCallback(
    (e) => {
      updateFilter('search', e.target.value);
    },
    [updateFilter]
  );

  const filterSubmitHandler = (values: PurchaseFilter) => {
    setFilters({
      start_date: values.start_date || '',
      end_date: values.end_date || '',
      filter_by: values.filterBy?.value || '',
      po_date: values.poDate,
      product_category_id: values.category.join(','),
      product_category_name:
        values.category_labels?.map((item) => item.label).join(',') || '',
      approval_status: values.status.join(','),
      supplier_id: values.supplier_id ? String(values.supplier_id) : '',
      supplier_name: values.supplier_label || '',
      area_id: values.area_id ? String(values.area_id) : '',
      area_name: values.area_label || '',
      location_id: values.location_id ? String(values.location_id) : '',
      location_name: values.location_label || '',
      project_flock_id: values.project_flock_id
        ? String(values.project_flock_id)
        : '',
      project_flock_name: values.project_flock_label || '',
      project_flock_kandang_id: values.project_flock_kandang_id
        ? String(values.project_flock_kandang_id)
        : '',
      project_flock_kandang_name: values.project_flock_kandang_label || '',
    });
  };

  const filterResetHandler = () => {
    setFilters({
      start_date: '',
      end_date: '',
      filter_by: '',
      po_date: '',
      product_category_id: '',
      product_category_name: '',
      approval_status: '',
      supplier_id: '',
      supplier_name: '',
      area_id: '',
      area_name: '',
      location_id: '',
      location_name: '',
      project_flock_id: '',
      project_flock_name: '',
      project_flock_kandang_id: '',
      project_flock_kandang_name: '',
    });
  };

  const purchaseFilterInitialValues = useMemo(() => {
    const filterByLabelMap: Record<string, string> = {
      po_date: 'Tanggal PO',
      received_date: 'Tanggal Terima',
      due_date: 'Tanggal Jatuh Tempo',
      created_at: 'Tanggal Dibuat',
    };

    const categoryIds = tableFilterState.product_category_id
      ? tableFilterState.product_category_id
          .split(',')
          .map((item) => item.trim())
          .filter(Boolean)
      : [];
    const categoryLabels = tableFilterState.product_category_name
      ? tableFilterState.product_category_name
          .split(',')
          .map((item) => item.trim())
          .filter(Boolean)
      : [];
    const approvalStatuses = tableFilterState.approval_status
      ? tableFilterState.approval_status
          .split(',')
          .map((item) => item.trim())
          .filter(Boolean)
      : [];

    return {
      poDate: tableFilterState.po_date,
      start_date: tableFilterState.start_date,
      end_date: tableFilterState.end_date,
      filterBy: tableFilterState.filter_by
        ? {
            value: tableFilterState.filter_by,
            label:
              filterByLabelMap[tableFilterState.filter_by] ||
              tableFilterState.filter_by,
          }
        : undefined,
      category: categoryIds.map((value, index) => ({
        value: Number(value),
        label: categoryLabels[index] || value,
      })),
      status: approvalStatuses.map((value) => ({
        value,
        label:
          PURCHASE_ORDER_APPROVAL_LINE.find((item) => item.step_name === value)
            ?.step_name || value,
      })),
      supplier: tableFilterState.supplier_id
        ? ({
            value: Number(tableFilterState.supplier_id),
            label:
              tableFilterState.supplier_name || tableFilterState.supplier_id,
          } as OptionType<number>)
        : null,
      area: tableFilterState.area_id
        ? ({
            value: Number(tableFilterState.area_id),
            label: tableFilterState.area_name || tableFilterState.area_id,
          } as OptionType<number>)
        : null,
      location: tableFilterState.location_id
        ? ({
            value: Number(tableFilterState.location_id),
            label:
              tableFilterState.location_name || tableFilterState.location_id,
          } as OptionType<number>)
        : null,
      project_flock: tableFilterState.project_flock_id
        ? ({
            value: Number(tableFilterState.project_flock_id),
            label:
              tableFilterState.project_flock_name ||
              tableFilterState.project_flock_id,
          } as OptionType<number>)
        : null,
      project_flock_kandang: tableFilterState.project_flock_kandang_id
        ? ({
            value: Number(tableFilterState.project_flock_kandang_id),
            label:
              tableFilterState.project_flock_kandang_name ||
              tableFilterState.project_flock_kandang_id,
          } as OptionType<number>)
        : null,
    };
  }, [tableFilterState]);

  const exportToExcel = useCallback(async () => {
    setIsLoadingExportingToExcel(true);

    try {
      await PurchaseApi.exportToExcel(getTableFilterQueryString());
    } catch (error) {
      toast.error(
        await getErrorMessage(error, 'Gagal mengekspor data pembelian')
      );
    } finally {
      setIsLoadingExportingToExcel(false);
    }
  }, [getTableFilterQueryString]);

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

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

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

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

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

    setIsExportProgressLoading(true);

    try {
      await PurchaseApi.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,
  ]);

  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'>
          <div className='w-fit flex flex-row gap-3 flex-wrap'>
            <RequirePermission permissions='lti.purchase.create'>
              <Button
                href='/purchase/add'
                color='primary'
                className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-xl shadow-button-soft'
              >
                <Icon icon='heroicons:plus' width={20} height={20} />
                Add Purchase
              </Button>
            </RequirePermission>
          </div>

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

                    <span>Export</span>

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

                    <Icon
                      icon='heroicons:chevron-down'
                      width={14}
                      height={14}
                    />
                  </div>
                </Button>
              }
            >
              <Button
                variant='ghost'
                color='none'
                onClick={exportToExcel}
                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} />
                Ekspor ke 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>

        <PurchaseInlineFilter
          initialValues={purchaseFilterInitialValues}
          searchValue={tableFilterState.search}
          onSearchChange={searchChangeHandler}
          onSubmit={filterSubmitHandler}
          onReset={filterResetHandler}
        />

        {/* 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(purchaseRequests) ||
            purchaseRequests.data?.length === 0 ? (
            <div className='p-3'>
              <PurchaseTableSkeleton
                columns={purchaseColumns}
                icon={
                  <Icon
                    icon='heroicons:document-text'
                    className='text-white'
                    width={20}
                    height={20}
                  />
                }
              />
            </div>
          ) : (
            <Table<Purchase>
              data={
                isResponseSuccess(purchaseRequests)
                  ? purchaseRequests?.data
                  : []
              }
              columns={purchaseColumns}
              pageSize={tableFilterState.pageSize}
              page={
                isResponseSuccess(purchaseRequests)
                  ? purchaseRequests?.meta?.page
                  : 0
              }
              totalItems={
                isResponseSuccess(purchaseRequests)
                  ? purchaseRequests?.meta?.total_results
                  : 0
              }
              onPageChange={setPage}
              onPageSizeChange={setPageSize}
              isLoading={isLoading}
              sorting={sorting}
              setSorting={handleSortingChange}
              manualSorting
              className={{
                containerClassName: cn('p-3 mb-0'),
                headerColumnClassName: 'text-nowrap',
              }}
            />
          )}
        </div>
      </div>

      {/* ===== MODAL COMPONENTS ===== */}

      <ConfirmationModal
        ref={deleteModal.ref}
        type='error'
        text={`Apakah anda yakin ingin menghapus data permintaan pembelian ini?`}
        secondaryButton={{
          text: 'Tidak',
          onClick: () => deleteModal.closeModal(),
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          isLoading: isDeleteLoading,
          onClick: confirmationModalDeleteClickHandler,
        }}
      />

      <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>
    </>
  );
};

export default PurchaseTable;
