import Table from '@/components/Table';
import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
import Button from '@/components/Button';
import { Icon } from '@iconify/react';
import * as TanStack from '@tanstack/react-table';
import { useMemo, useRef } from 'react';
import {
  cn,
  formatCurrency,
  formatDate,
  formatNumber,
  formatVechicleNumber,
} from '@/lib/helper';

type DeliveryOrderProductTableProps = {
  data: DeliveryOrderProductFormValues[];
  formType?: 'add' | 'edit' | 'add_deliver' | 'edit_deliver';
  onEdit: (id: number) => void;
  onDelete: (id: number) => void;
  onAddProductClick: () => void;
};

const DeliveryOrderProductTable = ({
  data,
  formType,
  onEdit,
  onDelete,
  onAddProductClick,
}: DeliveryOrderProductTableProps) => {
  const onEditRef = useRef(onEdit);
  onEditRef.current = onEdit;
  const onDeleteRef = useRef(onDelete);
  onDeleteRef.current = onDelete;

  const canAddData = data.filter((item) => !Boolean(item.qty));

  const columns = useMemo(() => {
    const cols = [
      {
        accessorFn: (row: DeliveryOrderProductFormValues) => row.do_number,
        header: 'No. Pengiriman',
        cell: (
          props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
        ) => (
          <>
            {props.row.original.do_number ? props.row.original.do_number : '-'}
          </>
        ),
      },
      {
        accessorFn: (row: DeliveryOrderProductFormValues) => row.vehicle_number,
        header: 'No. Polisi',
        cell: (
          props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
        ) =>
          props.row.original.vehicle_number
            ? formatVechicleNumber(props.row.original.vehicle_number as string)
            : '-',
      },
      {
        accessorFn: (row: DeliveryOrderProductFormValues) =>
          row.marketing_product?.kandang?.label,
        header: 'Kandang',
      },
      {
        accessorFn: (row: DeliveryOrderProductFormValues) =>
          row.marketing_product?.product_warehouse?.label,
        header: 'Produk',
      },
      {
        accessorFn: (row: DeliveryOrderProductFormValues) =>
          row.delivery_date
            ? formatDate(row.delivery_date as string, 'DD MMM YYYY')
            : '-',
        header: 'Tanggal Delivery',
        cell: (
          props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
        ) =>
          props.row.original.delivery_date
            ? formatDate(
                props.row.original.delivery_date as string,
                'DD MMM YYYY'
              )
            : '-',
      },
      {
        accessorFn: (row: DeliveryOrderProductFormValues) => row.unit_price,
        header: 'Harga Satuan (Rp)',
        cell: (
          props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
        ) =>
          props.row.original.unit_price
            ? formatCurrency(
                parseFloat(props.row.original.unit_price as string)
              )
            : '-',
      },
      {
        accessorFn: (row: DeliveryOrderProductFormValues) => row.total_weight,
        header: 'Total Bobot (Kg)',
        cell: (
          props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
        ) =>
          props.row.original.total_weight
            ? formatNumber(
                parseFloat(props.row.original.total_weight as string)
              )
            : '-',
      },
      {
        accessorFn: (row: DeliveryOrderProductFormValues) => row.qty,
        header: 'Kuantitas',
        cell: (
          props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
        ) =>
          props.row.original.qty
            ? formatNumber(parseFloat(props.row.original.qty as string))
            : '-',
      },
      {
        accessorFn: (row: DeliveryOrderProductFormValues) => row.avg_weight,
        header: 'Avg. Bobot (Kg)',
        cell: (
          props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
        ) =>
          props.row.original.avg_weight
            ? formatNumber(parseFloat(props.row.original.avg_weight as string))
            : '-',
      },
      {
        accessorFn: (row: DeliveryOrderProductFormValues) => row.total_price,
        header: 'Total Penjualan (Rp)',
        cell: (
          props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
        ) =>
          props.row.original.total_price
            ? formatCurrency(
                parseFloat(props.row.original.total_price as string)
              )
            : '-',
      },

      {
        header: 'Aksi',
        cell: (
          props: TanStack.CellContext<DeliveryOrderProductFormValues, unknown>
        ) => (
          <div className='flex flex-row gap-1 items-center justify-end h-full mt-2'>
            <>
              {props.row.original.qty && (
                <>
                  <Button
                    color='warning'
                    className='px-2 py-1 text-sm'
                    onClick={() =>
                      onEditRef.current(props.row.original.id as number)
                    }
                    type='button'
                  >
                    <Icon icon='mdi:edit' width={16} height={16} /> Edit
                  </Button>
                  <Button
                    color='error'
                    className='px-2 py-1 text-sm'
                    onClick={() =>
                      onDeleteRef.current(props.row.original.id as number)
                    }
                    type='button'
                    disabled={!!props.row.original.do_number}
                  >
                    <Icon icon='mdi:delete' width={16} height={16} /> Hapus
                  </Button>
                </>
              )}
              {!props.row.original.qty && '-'}
            </>
          </div>
        ),
      },
    ];
    if (formType == 'add_deliver') {
      return cols.filter((col) => col.header != 'No. Pengiriman');
    }
    return cols;
  }, [formType, onEditRef]);

  return (
    <>
      <Table<DeliveryOrderProductFormValues>
        data={data}
        columns={columns}
        className={{
          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-2 py-2 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end first:flex first:flex-row first:justify-start',
          bodyRowClassName: 'border-b border-b-gray-200',
          bodyColumnClassName:
            'px-2 py-2 last:flex last:flex-row last:justify-end',
          paginationClassName: 'hidden',
        }}
        emptyContent={
          <div
            className={cn(
              'w-full h-16 flex flex-col justify-center items-center gap-2'
            )}
          >
            <span className='text-gray-500'>Belum ada data pengiriman</span>
          </div>
        }
      />
      <div className='flex flex-row gap-3 mt-3'>
        <Button
          type='button'
          variant='outline'
          className='justify-start w-fit py-1 text-sm'
          onClick={onAddProductClick}
          disabled={!canAddData}
        >
          <Icon icon='mdi:plus' width={16} height={16} />
          Tambah Pengiriman
        </Button>
      </div>
    </>
  );
};

export default DeliveryOrderProductTable;
