import Card from '@/components/Card';
import Table, { TABLE_DEFAULT_STYLING } from '@/components/Table';
import { isResponseSuccess } from '@/lib/api-helper';
import { cn, formatCurrency, formatDate, formatNumber } from '@/lib/helper';
import { ClosingApi } from '@/services/api/closing';
import { Overhead, OverheadTotal } from '@/types/api/closing';
import { ColumnDef } from '@tanstack/react-table';
import { useMemo } from 'react';
import useSWR from 'swr';

interface ClosingOverheadTableProps {
  type?: 'detail';
  projectFlockId: number;
}

const ClosingOverheadTable = ({
  type,
  projectFlockId,
}: ClosingOverheadTableProps) => {
  const { data: overhead, isLoading: isLoadingOverhead } = useSWR(
    `${ClosingApi.basePath}/${projectFlockId}/overhead`,
    () => ClosingApi.getOverhead(projectFlockId),
    {
      keepPreviousData: true,
    }
  );

  // Helper function to create columns with footer support
  const createColumns = (total?: OverheadTotal): ColumnDef<Overhead>[] => [
    // Group untuk kolom tanpa footer
    {
      header: 'Nama Item',
      accessorFn: (props) => props.item_name,
      footer: 'Total Pengeluaran Overhead',
    },
    {
      header: 'Satuan',
      accessorFn: (props) => props.uom_name,
    },
    {
      header: 'Budget Pengajuan',
      footer: '',
      columns: [
        {
          id: 'budget_quantity',
          header: 'Jumlah',
          accessorFn: (props) =>
            props.budget_quantity ? formatNumber(props.budget_quantity) : '-',
          footer: total ? () => formatNumber(total.budget_quantity) : '',
        },
        {
          id: 'budget_unit_price',
          header: 'Harga Satuan',
          accessorFn: (props) =>
            props.budget_unit_price
              ? formatCurrency(props.budget_unit_price)
              : '-',
          footer: '',
        },
        {
          id: 'budget_total_amount',
          header: 'Total',
          accessorFn: (props) =>
            props.budget_total_amount
              ? formatCurrency(props.budget_total_amount)
              : '-',
          footer: total ? () => formatCurrency(total.budget_total_amount) : '',
        },
      ],
    },
    {
      header: 'Realisasi',
      footer: '',
      columns: [
        {
          id: 'actual_date',
          header: 'Tanggal',
          accessorFn: (props) =>
            props.actual_date
              ? formatDate(props.actual_date, 'DD MMM, YYYY')
              : '-',
          footer: '',
        },
        {
          id: 'actual_quantity',
          header: 'Jumlah',
          accessorFn: (props) =>
            props.actual_quantity ? formatNumber(props.actual_quantity) : '-',
          footer: total ? () => formatNumber(total.actual_quantity) : '',
        },
        {
          id: 'actual_unit_price',
          header: 'Harga Satuan',
          accessorFn: (props) =>
            props.actual_unit_price
              ? formatCurrency(props.actual_unit_price)
              : '-',
          footer: '',
        },
        {
          id: 'actual_total_amount',
          header: 'Total',
          accessorFn: (props) =>
            props.actual_total_amount
              ? formatCurrency(props.actual_total_amount)
              : '-',
          footer: total ? () => formatCurrency(total.actual_total_amount) : '',
        },
      ],
    },
    {
      id: 'cost_per_bird',
      header: 'Rp/Ekor',
      accessorFn: (props) =>
        props.cost_per_bird ? formatCurrency(props.cost_per_bird) : '-',
      footer: total ? () => formatCurrency(total.cost_per_bird) : '',
    },
  ];

  const columns = useMemo(
    () =>
      isResponseSuccess(overhead)
        ? createColumns(overhead.data?.total)
        : createColumns(),
    [overhead]
  );

  return (
    <>
      <Card
        title='Pengeluaran Overhead'
        collapsible
        defaultCollapsed={false}
        className={{
          wrapper: 'w-full',
          body: 'p-4 shadow',
        }}
      >
        <Table<Overhead>
          data={
            isResponseSuccess(overhead) ? (overhead.data?.overheads ?? []) : []
          }
          columns={columns}
          className={{
            containerClassName: 'my-4',
            headerColumnClassName: cn(
              TABLE_DEFAULT_STYLING.headerColumnClassName,
              'whitespace-nowrap'
            ),
          }}
          renderFooter={
            isResponseSuccess(overhead)
              ? overhead.data?.overheads.length > 0
              : false
          }
        />
      </Card>
    </>
  );
};

export default ClosingOverheadTable;
