'use client';

import Button from '@/components/Button';
import Table from '@/components/Table';
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
import {
  cn,
  formatCurrency,
  formatNumber,
  formatVechicleNumber,
} from '@/lib/helper';
import { Icon } from '@iconify/react';
import { useMemo, useRef, useState } from 'react';
import * as TanStack from '@tanstack/react-table';
import CheckboxInput from '@/components/input/CheckboxInput';

type SalesOrderProductTableProps = {
  data: SalesOrderProductFormValues[];
  formType: 'add' | 'edit' | 'add_deliver' | 'edit_deliver';
  rowSelection: Record<string, boolean>;
  setRowSelection: React.Dispatch<
    React.SetStateAction<Record<string, boolean>>
  >;
  selectedRowIds: number[];
  onDelete: (id: number) => void;
  onEdit: (id: number) => void;
  onBulkDelete: () => void;
  onAddProductClick: () => void;
};

const SalesOrderProductTable = ({
  data,
  formType,
  rowSelection,
  setRowSelection,
  selectedRowIds,
  onDelete,
  onEdit,
  onBulkDelete,
  onAddProductClick,
}: SalesOrderProductTableProps) => {
  const onDeleteRef = useRef(onDelete);
  onDeleteRef.current = onDelete;
  const onEditRef = useRef(onEdit);
  onEditRef.current = onEdit;

  const columns = useMemo(
    () => [
      {
        id: 'select',
        header: ({
          table,
        }: {
          table: TanStack.Table<SalesOrderProductFormValues>;
        }) => (
          <div className='w-full flex flex-row justify-center'>
            <CheckboxInput
              name='allRow'
              checked={table.getIsAllRowsSelected()}
              indeterminate={table.getIsSomeRowsSelected()}
              onChange={table.getToggleAllRowsSelectedHandler()}
            />
          </div>
        ),
        cell: ({ row }: { row: TanStack.Row<SalesOrderProductFormValues> }) => (
          <div>
            <CheckboxInput
              name='row'
              checked={row.getIsSelected()}
              disabled={!row.getCanSelect()}
              indeterminate={row.getIsSomeSelected()}
              onChange={row.getToggleSelectedHandler()}
              value={`${row.original.product_warehouse_id}${row.original.kandang_id}`}
            />
          </div>
        ),
      },
      {
        accessorFn: (row: SalesOrderProductFormValues) =>
          formatVechicleNumber(row.vehicle_number as string),
        header: 'No. Polisi',
      },
      {
        accessorFn: (row: SalesOrderProductFormValues) => row.kandang?.label,
        header: 'Kandang',
      },
      {
        accessorFn: (row: SalesOrderProductFormValues) =>
          row.product_warehouse?.label,
        header: 'Produk',
      },
      {
        accessorFn: (row: SalesOrderProductFormValues) =>
          formatCurrency(parseFloat(row.unit_price as string)),
        header: 'Harga Satuan (Rp)',
      },
      {
        accessorFn: (row: SalesOrderProductFormValues) =>
          formatNumber(parseFloat(row.total_weight as string), undefined, 0, 5),
        header: 'Total Bobot (Kg)',
      },
      {
        accessorFn: (row: SalesOrderProductFormValues) =>
          formatNumber(parseFloat(row.qty as string)),
        header: 'Kuantitas',
        cell: ({ row }: { row: TanStack.Row<SalesOrderProductFormValues> }) =>
          formatNumber(
            parseFloat(row.original.qty as string),
            undefined,
            0,
            5
          ) +
          ' ' +
          (row.original.uom ?? ''),
      },
      {
        accessorFn: (row: SalesOrderProductFormValues) =>
          formatNumber(parseFloat(row.avg_weight as string), undefined, 0, 5),
        header: 'Avg. Bobot (Kg)',
      },
      {
        accessorFn: (row: SalesOrderProductFormValues) =>
          formatCurrency(parseFloat(row.total_price as string)),
        header: 'Total Penjualan (Rp)',
      },
      {
        header: 'Aksi',
        cell: (
          props: TanStack.CellContext<SalesOrderProductFormValues, unknown>
        ) => (
          <div className='flex flex-row gap-1 items-center justify-end h-full mt-2'>
            <Button
              color='warning'
              className='p-1'
              onClick={() => onEditRef.current(props.row.original.id as number)}
              type='button'
            >
              <Icon icon='mdi:pencil' width={16} height={16} /> Edit
            </Button>
            <Button
              color='error'
              className='p-1'
              onClick={() =>
                onDeleteRef.current(props.row.original.id as number)
              }
              type='button'
            >
              <Icon icon='mdi:trash' width={16} height={16} /> Hapus
            </Button>
          </div>
        ),
      },
    ],
    []
  );

  return (
    <>
      <Table<SalesOrderProductFormValues>
        rowSelection={rowSelection}
        setRowSelection={setRowSelection}
        data={data}
        columns={
          formType == 'add_deliver' || formType == 'edit_deliver'
            ? columns.filter(
                (col) => col.header != 'Aksi' && col.id != 'select'
              )
            : 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 first:flex first:flex-row first:justify-start',
          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 penjualan</span>
          </div>
        }
      />
      {formType != 'add_deliver' && formType != 'edit_deliver' && (
        <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}
          >
            <Icon icon='mdi:plus' width={16} height={16} />
            Tambah Produk
          </Button>
          {selectedRowIds.length > 0 && (
            <Button
              type='button'
              variant='outline'
              color='error'
              className='justify-start w-fit py-1 text-sm'
              onClick={onBulkDelete}
            >
              <Icon icon='mdi:trash' width={16} height={16} />
              Hapus
              {selectedRowIds.length > 0
                ? ` (${selectedRowIds.length})`
                : ''}{' '}
              Produk
            </Button>
          )}
        </div>
      )}
    </>
  );
};

export default SalesOrderProductTable;
