'use client';

import { ChangeEventHandler, useState } from 'react';
import useSWR from 'swr';
import { SortingState, CellContext, ColumnDef } from '@tanstack/react-table';

import Table from '@/components/Table';
import { Icon } from '@iconify/react';
import { Movement } from '@/types/api/inventory/movement';
import { MovementApi } from '@/services/api/inventory';
import { cn } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
import { OptionType } from '@/components/input/SelectInput';
import Button from '@/components/Button';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import SelectInput 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';

const RowOptionsMenu = ({
  type = 'dropdown',
  props,
}: {
  type: 'dropdown' | 'collapse';
  props: CellContext<Movement, unknown>;
}) => (
  <RowOptionsMenuWrapper type={type}>
    <RequirePermission permissions='lti.inventory.transfer.detail'>
      <Button
        href={`/inventory/movement/detail/?movementId=${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 MovementTable = () => {
  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      search: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
    },
  });

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

  const { data: movements, isLoading } = useSWR(
    `${MovementApi.basePath}${getTableFilterQueryString()}`,
    MovementApi.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 movementColumns: ColumnDef<Movement>[] = [
    {
      header: '#',
      cell: (props) =>
        tableFilterState.pageSize * (tableFilterState.page - 1) +
        props.row.index +
        1,
    },
    {
      accessorFn: (row) => row.source_warehouse?.name,
      header: 'Gudang Asal',
    },
    {
      accessorFn: (row) => row.destination_warehouse?.name,
      header: 'Gudang Tujuan',
    },
    {
      accessorKey: 'transfer_reason',
      header: 'Catatan',
    },
    {
      accessorKey: 'transfer_date',
      header: 'Tanggal',
      cell: (props) =>
        new Date(props.row.original.transfer_date).toLocaleDateString('id-ID'),
    },
    {
      accessorFn: (row) => {
        const totalCost = row.deliveries?.reduce(
          (sum, d) => sum + (d.shipping_cost_total || 0),
          0
        );
        return totalCost?.toLocaleString('id-ID');
      },
      header: 'Biaya Pengiriman',
    },
    {
      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'>
              <RequirePermission permissions='lti.inventory.transfer.create'>
                <Button
                  href='/inventory/movement/add'
                  variant='outline'
                  color='primary'
                  className='w-full sm:w-fit'
                >
                  <Icon icon='ic:round-plus' width={24} height={24} />
                  Tambah
                </Button>
              </RequirePermission>
            </div>

            <DebouncedTextInput
              name='search'
              placeholder='Cari Movement'
              value={tableFilterState.search}
              onChange={searchChangeHandler}
              className={{ wrapper: 'sm:max-w-3xs' }}
            />
          </div>

          <div className='flex justify-end gap-4'>
            <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<Movement>
          data={isResponseSuccess(movements) ? movements?.data : []}
          columns={movementColumns}
          pageSize={tableFilterState.pageSize}
          page={isResponseSuccess(movements) ? movements?.meta?.page : 0}
          totalItems={
            isResponseSuccess(movements) ? movements?.meta?.total_results : 0
          }
          onPageChange={setPage}
          isLoading={isLoading}
          sorting={sorting}
          setSorting={setSorting}
          className={{
            containerClassName: cn({
              'mb-20':
                isResponseSuccess(movements) && movements?.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 MovementTable;
