'use client';

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

import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import StatusBadge from '@/components/helper/StatusBadge';

import { cn, formatDate } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { BaseApiResponse } from '@/types/api/api-general';

import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { Purchase } from '@/types/api/purchase/purchase';
import { PurchaseApi } from '@/services/api/purchase';
import { ExpenseApi } from '@/services/api/expense';
import { Expense } from '@/types/api/expense';
import { Color } from '@/types/theme';
import Link from 'next/link';

// ===== 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';
};

// ===== INTERFACES =====
interface RowOptionsMenuProps {
  type: 'dropdown' | 'collapse';
  props: CellContext<Purchase, unknown>;
  deleteClickHandler: () => void;
}

const RowOptionsMenu = ({
  type = 'dropdown',
  props,
  deleteClickHandler,
}: RowOptionsMenuProps) => {
  return (
    <RowOptionsMenuWrapper type={type}>
      <RequirePermission permissions='lti.purchase.detail'>
        <Button
          href={`/purchase/detail/?purchaseId=${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>

      {/*<Button*/}
      {/*  href={`/purchase/detail/edit/?purchaseId=${props.row.original.id}`}*/}
      {/*  variant='ghost'*/}
      {/*  color='warning'*/}
      {/*  className='justify-start text-sm'*/}
      {/*>*/}
      {/*  <Icon icon='material-symbols:edit-outline' width={16} height={16} />*/}
      {/*  Edit*/}
      {/*</Button>*/}

      <RequirePermission permissions='lti.purchase.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='material-symbols:delete-outline-rounded'
            width={16}
            height={16}
            className='justify-start text-sm'
          />
          Delete
        </Button>
      </RequirePermission>
    </RowOptionsMenuWrapper>
  );
};

const PurchaseTable = () => {
  // ===== STATE MANAGEMENT =====
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);
  const [selectedPurchase, setSelectedPurchase] = useState<Purchase | null>(
    null
  );
  const [sorting, setSorting] = useState<SortingState>([]);

  // ===== TABLE FILTER STATE =====
  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      search: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
    },
  });

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

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

  const getKey = (
    pageIndex: number,
    previousPageData: BaseApiResponse<Expense>[] | null
  ) => {
    if (pageIndex > 0 && !previousPageData) return null;
    return `${ExpenseApi.basePath}?page=${pageIndex + 1}&limit=100`;
  };

  const { data: expensesPages } = useSWRInfinite(
    getKey,
    ExpenseApi.getAllFetcher
  );

  const expenseMap = useMemo(() => {
    const map = new Map<string, number>();
    if (!expensesPages) return map;

    expensesPages.forEach((page) => {
      if (isResponseSuccess(page)) {
        page.data.forEach((expense: Expense) => {
          map.set(expense.reference_number, expense.id);
        });
      }
    });
    return map;
  }, [expensesPages]);

  // ===== TABLE COLUMNS DEFINITION =====
  const purchaseColumns: ColumnDef<Purchase>[] = [
    {
      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) => {
              const expenseId = expenseMap.get(exp.refrence);
              if (expenseId) {
                return (
                  <li key={index}>
                    <Link
                      href={`/expense/detail/?expenseId=${expenseId}`}
                      className='p-0 h-auto text-primary underline'
                    >
                      {exp.refrence}
                    </Link>
                  </li>
                );
              }
              return <li key={index}>{exp.refrence}</li>;
            })}
          </ul>
        );
      },
    },
    {
      accessorKey: 'supplier',
      header: 'Vendor',
      cell: (props) => props.row.original.supplier.name,
    },
    {
      accessorKey: 'requester_name',
      header: 'Nama Pengaju',
      cell: (props) => props.row.original.requester_name || '-',
    },
    {
      accessorKey: 'products.name',
      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: 'location.name',
      header: 'Lokasi',
      cell: (props) => props.row.original.location?.name || '-',
    },
    {
      accessorKey: 'po_date',
      header: 'Tgl. PO',
      cell: (props) =>
        props.row.original.po_date
          ? formatDate(props.row.original.po_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',
      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`;
      },
    },
    {
      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',
            }}
          />
        );
      },
    },
    {
      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 (
          <>
            {currentPageSize > 2 && (
              <RowDropdownOptions isLast2Rows={isLast2Rows}>
                <RowOptionsMenu
                  type='dropdown'
                  props={props}
                  deleteClickHandler={deleteClickHandler}
                />
              </RowDropdownOptions>
            )}

            {currentPageSize <= 2 && (
              <RowCollapseOptions>
                <RowOptionsMenu
                  type='collapse'
                  props={props}
                  deleteClickHandler={deleteClickHandler}
                />
              </RowCollapseOptions>
            )}
          </>
        );
      },
    },
  ];

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

    try {
      await PurchaseApi.delete(selectedPurchase?.id as number);
      refreshPurchaseRequests();
      deleteModal.closeModal();
      toast.success('Berhasil menghapus data permintaan pembelian!');
    } 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 pageSizeChangeHandler = useCallback(
    (val: OptionType | OptionType[] | null) => {
      const newVal = val as OptionType;
      setPageSize(newVal.value as number);
    },
    [setPageSize]
  );

  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 flex flex-row gap-2'>
              <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-lg shadow-sm'
                >
                  <Icon icon='heroicons:plus' width={20} height={20} />
                  Add Purchase
                </Button>
              </RequirePermission>
            </div>

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

          <div className='flex flex-wrap justify-end gap-4'>
            <SelectInput
              label='Baris'
              options={ROWS_OPTIONS}
              value={{
                label: String(tableFilterState.pageSize),
                value: tableFilterState.pageSize,
              }}
              onChange={pageSizeChangeHandler}
              className={{
                wrapper: 'w-full sm:w-24',
              }}
            />
          </div>
        </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}
          isLoading={isLoading}
          sorting={sorting}
          setSorting={setSorting}
          className={{
            containerClassName: cn({
              'mb-20':
                isResponseSuccess(purchaseRequests) &&
                purchaseRequests?.data?.length === 0,
            }),
            tableWrapperClassName: 'overflow-x-auto min-h-full!',
            tableClassName: 'font-inter w-full table-auto min-h-full!',
            headerRowClassName: 'border-b border-b-gray-200',
            headerColumnClassName:
              'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
            bodyRowClassName: 'border-b border-b-gray-200',
            bodyColumnClassName:
              'px-6 py-3 last:flex last:flex-row last:justify-end',
          }}
        />
      </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,
        }}
      />
    </>
  );
};

export default PurchaseTable;
