'use client';

import Button from '@/components/Button';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import Table from '@/components/Table';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission';
import { ROWS_OPTIONS } from '@/config/constant';
import { isResponseSuccess } from '@/lib/api-helper';
import { cn, formatCurrency, formatNumber } from '@/lib/helper';
import { InventoryProductApi } from '@/services/api/inventory';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { InventoryProduct } from '@/types/api/inventory/product';
import { Icon } from '@iconify/react';
import {
  CellContext,
  ColumnDef,
  Row,
  SortingState,
} from '@tanstack/react-table';
import { ChangeEventHandler, useMemo, useState } from 'react';
import useSWR from 'swr';

const RowOptionsMenu = ({
  type = 'dropdown',
  props,
}: {
  type: 'dropdown' | 'collapse';
  props: CellContext<InventoryProduct, unknown>;
}) => (
  <RowOptionsMenuWrapper type={type}>
    <RequirePermission permissions='lti.inventory.product_stock.detail'>
      <Button
        href={`/inventory/product/detail?inventoryProductId=${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>
  </RowOptionsMenuWrapper>
);

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

  const [sorting, setSorting] = useState<SortingState>([]);

  const { data: inventoryProducts, isLoading } = useSWR(
    `${InventoryProductApi.basePath}${getTableFilterQueryString()}`,
    InventoryProductApi.getAllFetcher
  );

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

  const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
    const newVal = val as OptionType;
    setPageSize(newVal.value as number);
    setPage(1);
  };

  const columns: ColumnDef<InventoryProduct>[] = useMemo(
    () => [
      {
        header: '#',
        cell: (props) =>
          tableFilterState.pageSize * (tableFilterState.page - 1) +
          props.row.index +
          1,
      },
      {
        accessorKey: 'name',
        header: 'Nama',
      },
      {
        accessorKey: 'product_price',
        header: 'Harga Beli',
        cell: (props) => {
          return props.row.original.product_price
            ? formatCurrency(props.row.original.product_price)
            : '-';
        },
      },
      {
        accessorKey: 'selling_price',
        header: 'Harga Jual',
        cell: (props) => {
          return props.row.original.selling_price
            ? formatCurrency(props.row.original.selling_price)
            : '-';
        },
      },
      {
        accessorFn: (row) => row.product_category.name,
        header: 'Kategori',
      },
      {
        accessorFn: (row) => row.total_stock,
        header: 'Stok',
        cell: (props) => {
          return props.row.original.total_stock
            ? formatNumber(props.row.original.total_stock)
            : '0';
        },
      },
      {
        accessorFn: (row) => row.uom.name,
        header: 'Satuan',
      },
      {
        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;

          return (
            <>
              {currentPageSize > 2 && (
                <RowDropdownOptions isLast2Rows={isLast2Rows}>
                  <RowOptionsMenu type='dropdown' props={props} />
                </RowDropdownOptions>
              )}

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

  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 sm:flex-row justify-between items-end sm:items-center gap-2'>
            <div className='w-full flex flex-row gap-2'></div>
          </div>

          <div className='flex justify-between items-end gap-4'>
            <DebouncedTextInput
              name='search'
              placeholder='Cari Produk'
              value={tableFilterState.search}
              onChange={searchChangeHandler}
              className={{ wrapper: 'sm:max-w-3xs' }}
            />
            <SelectInput
              label='Baris'
              options={ROWS_OPTIONS}
              value={{
                label: String(tableFilterState.pageSize),
                value: tableFilterState.pageSize,
              }}
              onChange={pageSizeChangeHandler}
              className={{
                wrapper:
                  'col-span-6 sm:col-span-4 max-w-28 sm:justify-self-end',
              }}
            />
          </div>
        </div>

        <Table<InventoryProduct>
          data={
            isResponseSuccess(inventoryProducts) ? inventoryProducts?.data : []
          }
          columns={columns}
          pageSize={tableFilterState.pageSize}
          page={
            isResponseSuccess(inventoryProducts)
              ? inventoryProducts?.meta?.page
              : 0
          }
          totalItems={
            isResponseSuccess(inventoryProducts)
              ? inventoryProducts?.meta?.total_results
              : 0
          }
          onPageChange={setPage}
          isLoading={isLoading}
          sorting={sorting}
          setSorting={setSorting}
          className={{
            containerClassName: cn({
              'mb-20':
                isResponseSuccess(inventoryProducts) &&
                inventoryProducts?.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>
    </>
  );
};

export default InventoryProductTable;
