'use client';

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

import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } 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';

import { Warehouse } from '@/types/api/master-data/warehouse';
import { WarehouseApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';

const RowOptionsMenu = ({
  type = 'dropdown',
  props,
  deleteClickHandler,
}: {
  type: 'dropdown' | 'collapse';
  props: CellContext<Warehouse, unknown>;
  deleteClickHandler: () => void;
}) => {
  return (
    <RowOptionsMenuWrapper type={type}>
      <RequirePermission permissions='lti.master.warehouses.detail'>
        <Button
          href={`/master-data/warehouse/detail/?warehouseId=${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>

      <RequirePermission permissions='lti.master.warehouses.update'>
        <Button
          href={`/master-data/warehouse/detail/edit/?warehouseId=${props.row.original.id}`}
          variant='ghost'
          color='warning'
          className='justify-start text-sm'
        >
          <Icon icon='material-symbols:edit-outline' width={16} height={16} />
          Edit
        </Button>
      </RequirePermission>

      <RequirePermission permissions='lti.master.warehouses.delete'>
        <Button
          onClick={deleteClickHandler}
          variant='ghost'
          color='error'
          className='text-error hover:text-inherit'
        >
          <Icon
            icon='material-symbols:delete-outline-rounded'
            width={16}
            height={16}
            className='justify-start text-sm'
          />
          Delete
        </Button>
      </RequirePermission>
    </RowOptionsMenuWrapper>
  );
};

const WarehousesTable = () => {
  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      search: '',
      nameSort: '',
      typeSort: '',
      areaSort: '',
      locationSort: '',
      kandangSort: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      nameSort: 'sort_name',
      typeSort: 'sort_type',
      areaSort: ' sort_area',
      locationSort: ' sort_location',
      kandangSort: ' sort_kandang',
    },
  });

  const {
    data: warehouses,
    isLoading,
    mutate: refreshWarehouses,
  } = useSWR(
    `${WarehouseApi.basePath}${getTableFilterQueryString()}`,
    WarehouseApi.getAllFetcher
  );

  const deleteModal = useModal();

  const [selectedWarehouse, setSelectedWarehouse] = useState<
    Warehouse | undefined
  >(undefined);
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

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

  const warehousesColumns: ColumnDef<Warehouse>[] = [
    {
      header: '#',
      cell: (props) =>
        tableFilterState.pageSize * (tableFilterState.page - 1) +
        props.row.index +
        1,
    },
    {
      accessorKey: 'name',
      header: 'Nama',
    },
    {
      accessorKey: 'type',
      header: 'Tipe',
    },
    {
      accessorKey: 'area',
      header: 'Area',
      cell: (props) => props.row.original.area.name,
    },
    {
      accessorKey: 'location',
      header: 'Lokasi',
      cell: (props) => {
        if (
          props.row.original.type === 'LOKASI' ||
          props.row.original.type === 'KANDANG'
        ) {
          return props.row.original.location.name;
        } else {
          return '-';
        }
      },
    },
    {
      accessorKey: 'kandang',
      header: 'Kandang',
      cell: (props) => {
        if (props.row.original.type === 'KANDANG') {
          return props.row.original.kandang.name;
        } else {
          return '-';
        }
      },
    },
    {
      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;

        const deleteClickHandler = () => {
          setSelectedWarehouse(props.row.original);
          deleteModal.openModal();
        };

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

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

  const confirmationModalDeleteClickHandler = async () => {
    setIsDeleteLoading(true);

    const deleteResponse = await WarehouseApi.delete(
      selectedWarehouse?.id as number
    );

    if (isResponseError(deleteResponse)) {
      toast.error(deleteResponse.message);
      setIsDeleteLoading(false);
      return;
    }

    refreshWarehouses();

    deleteModal.closeModal();
    toast.success('Successfully delete Warehouse!');
    setIsDeleteLoading(false);
  };

  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);
  };

  const updateSortingFilter = useCallback(
    (
      sortName: Exclude<keyof typeof tableFilterState, 'page' | 'pageSize'>,
      sortFilter: ColumnSort | undefined
    ) => {
      if (!sortFilter) {
        updateFilter(sortName, '');
      } else {
        updateFilter(sortName, sortFilter.desc ? 'desc' : 'asc');
      }
    },
    [updateFilter]
  );

  // track sorting
  useEffect(() => {
    const nameSortFilter = sorting.find((sortItem) => sortItem.id === 'name');
    const typeSortFilter = sorting.find((sortItem) => sortItem.id === 'type');
    const areaSortFilter = sorting.find((sortItem) => sortItem.id === 'area');
    const locationSortFilter = sorting.find(
      (sortItem) => sortItem.id === 'location'
    );
    const kandangSortFilter = sorting.find(
      (sortItem) => sortItem.id === 'kandang'
    );

    updateSortingFilter('nameSort', nameSortFilter);
    updateSortingFilter('typeSort', typeSortFilter);
    updateSortingFilter('areaSort', areaSortFilter);
    updateSortingFilter('locationSort', locationSortFilter);
    updateSortingFilter('kandangSort', kandangSortFilter);
  }, [sorting, updateSortingFilter]);

  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'>
              <RequirePermission permissions='lti.master.warehouses.create'>
                <Button
                  href='/master-data/warehouse/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 Warehouse'
              value={tableFilterState.search}
              onChange={searchChangeHandler}
              className={{ wrapper: 'sm:max-w-3xs' }}
            />
          </div>

          <div className='flex flex-row justify-end'>
            <SelectInput
              label='Baris'
              options={ROWS_OPTIONS}
              value={{
                label: String(tableFilterState.pageSize),
                value: tableFilterState.pageSize,
              }}
              onChange={pageSizeChangeHandler}
              className={{ wrapper: 'max-w-28' }}
            />
          </div>
        </div>

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

      <ConfirmationModal
        ref={deleteModal.ref}
        type='error'
        text={`Apakah anda yakin ingin menghapus data Warehouse ini (${selectedWarehouse?.name})?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          isLoading: isDeleteLoading,
          onClick: confirmationModalDeleteClickHandler,
        }}
      />
    </>
  );
};

export default WarehousesTable;
