'use client';

import Button from '@/components/Button';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
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 { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { cn } from '@/lib/helper';
import { SupplierApi } from '@/services/api/master-data';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { Supplier } from '@/types/api/master-data/supplier';
import { Icon } from '@iconify/react';
import { CellContext, ColumnDef } from '@tanstack/react-table';
import { useState } from 'react';
import toast from 'react-hot-toast';
import useSWR from 'swr';

const RowOptions = ({
  type = 'dropdown',
  props,
  deleteClickHandler,
}: {
  type: 'dropdown' | 'collapse';
  props: CellContext<Supplier, unknown>;
  deleteClickHandler: () => void;
}) => {
  return (
    <RowOptionsMenuWrapper type={type}>
      <RequirePermission permissions='lti.master.suppliers.detail'>
        <Button
          href={`/master-data/supplier/detail/?supplierId=${props.row.original.id}`}
          variant='ghost'
          color='primary'
          className='justify-start text-sm'
        >
          <Icon
            icon='mdi:eye-outline'
            width={16}
            height={16}
            className='justify-start text-sm'
          />
          Detail
        </Button>
      </RequirePermission>
      <RequirePermission permissions='lti.master.suppliers.update'>
        <Button
          href={`/master-data/supplier/detail/edit/?supplierId=${props.row.original.id}`}
          variant='ghost'
          color='warning'
          className='justify-start text-sm'
        >
          <Icon
            icon='material-symbols:edit-outline'
            width={16}
            height={16}
            className='justify-start text-sm'
          />
          Edit
        </Button>
      </RequirePermission>
      <RequirePermission permissions='lti.master.suppliers.delete'>
        <Button
          onClick={deleteClickHandler}
          variant='ghost'
          color='error'
          className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content'
        >
          <Icon
            icon='material-symbols:delete-outline-rounded'
            width={16}
            height={16}
            className='justify-start text-sm'
          />
          Delete
        </Button>
      </RequirePermission>
    </RowOptionsMenuWrapper>
  );
};

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

  // Fetch Data
  const {
    data: suppliers,
    isLoading,
    mutate: refreshSuppliers,
  } = useSWR(
    `${SupplierApi.basePath}${getTableFilterQueryString()}`,
    SupplierApi.getAllFetcher
  );

  // State
  const deleteModal = useModal();
  const [selectedSupplier, setSelectedSupplier] = useState<
    Supplier | undefined
  >(undefined);
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  // Columns Definition
  const suppliersColumns: ColumnDef<Supplier>[] = [
    {
      header: '#',
      cell: (props) =>
        tableFilterState.pageSize * (tableFilterState.page - 1) +
        props.row.index +
        1,
    },
    {
      accessorKey: 'name',
      header: 'Nama',
    },
    {
      accessorKey: 'alias',
      header: 'Alias',
    },
    {
      accessorKey: 'pic',
      header: 'Nama PIC',
    },
    {
      accessorKey: 'category',
      header: 'Kategori',
    },
    {
      accessorKey: 'type',
      header: 'Tipe',
    },
    {
      accessorKey: 'phone',
      header: 'No. Telp',
    },
    {
      accessorKey: 'email',
      header: 'Email',
    },
    {
      accessorKey: 'address',
      header: 'Alamat',
    },
    {
      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 = () => {
          setSelectedSupplier(props.row.original);
          deleteModal.openModal();
        };

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

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

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

    const deleteResponse = await SupplierApi.delete(
      selectedSupplier?.id as number
    );

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

    refreshSuppliers();

    deleteModal.closeModal();
    toast.success('Successfully delete Supplier!');
    setIsDeleteLoading(false);
  };
  const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
    updateFilter('search', e.target.value);
  };
  const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
    const newVal = val as OptionType;
    setPageSize(newVal.value as number);
  };

  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.suppliers.create'>
                <Button
                  href='/master-data/supplier/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 Supplier'
              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<Supplier>
          data={isResponseSuccess(suppliers) ? suppliers?.data : []}
          columns={suppliersColumns}
          pageSize={tableFilterState.pageSize}
          page={isResponseSuccess(suppliers) ? suppliers?.meta?.page : 0}
          totalItems={
            isResponseSuccess(suppliers) ? suppliers?.meta?.total_results : 0
          }
          onPageChange={setPage}
          isLoading={isLoading}
          className={{
            containerClassName: cn({
              'mb-20':
                isResponseSuccess(suppliers) && suppliers?.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 Supplier ini (${selectedSupplier?.name})?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          isLoading: isDeleteLoading,
          onClick: confirmationModalDeleteClickHandler,
        }}
      />
    </>
  );
};

export default SuppliersTable;
