'use client';

import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
import useSWR from 'swr';
import { CellContext, ColumnDef, 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 RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import NonstockTableSkeleton from '@/components/pages/master-data/nonstock/skeleton/NonstockTableSkeleton';

import { Nonstock } from '@/types/api/master-data/nonstock';
import { NonstockApi } from '@/services/api/master-data';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';

const RowOptionsMenu = ({
  popoverPosition = 'bottom',
  props,
  deleteClickHandler,
}: {
  popoverPosition: 'bottom' | 'top';
  props: CellContext<Nonstock, unknown>;
  deleteClickHandler: () => void;
}) => {
  const popoverId = `nonstock#${props.row.original.id}`;
  const popoverAnchorName = `--anchor-nonstock#${props.row.original.id}`;

  const closePopover = () => {
    document.getElementById(popoverId)?.hidePopover();
  };

  return (
    <div className='relative'>
      <PopoverButton
        tabIndex={0}
        variant='ghost'
        color='none'
        popoverTarget={popoverId}
        anchorName={popoverAnchorName}
      >
        <Icon icon='material-symbols:more-vert' width={16} height={16} />
      </PopoverButton>

      <PopoverContent
        id={popoverId}
        anchorName={popoverAnchorName}
        position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
        className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
      >
        <div className='flex flex-col bg-base-100 rounded-xl'>
          <RequirePermission permissions='lti.master.nonstocks.detail'>
            <Button
              href={`/master-data/nonstock/detail/?nonstockId=${props.row.original.id}`}
              variant='ghost'
              color='none'
              className='p-3 justify-start text-sm font-semibold w-full'
              onClick={closePopover}
            >
              <Icon icon='heroicons:eye' width={20} height={20} />
              Detail
            </Button>
          </RequirePermission>
          <RequirePermission permissions='lti.master.nonstocks.update'>
            <Button
              href={`/master-data/nonstock/detail/edit/?nonstockId=${props.row.original.id}`}
              variant='ghost'
              color='none'
              className='p-3 justify-start text-sm font-semibold w-full'
              onClick={closePopover}
            >
              <Icon icon='heroicons:pencil-square' width={20} height={20} />
              Edit
            </Button>
          </RequirePermission>
          <RequirePermission permissions='lti.master.nonstocks.delete'>
            <Button
              onClick={() => {
                deleteClickHandler();
                closePopover();
              }}
              variant='ghost'
              color='none'
              className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
            >
              <Icon icon='heroicons:trash' width={20} height={20} />
              Delete
            </Button>
          </RequirePermission>
        </div>
      </PopoverContent>
    </div>
  );
};

const NonstocksTable = () => {
  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      search: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
    },
    persist: true,
    storeName: 'nonstock-table',
  });

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

  const {
    data: nonstocks,
    isLoading,
    mutate: refreshNonstocks,
  } = useSWR(
    `${NonstockApi.basePath}${getTableFilterQueryString()}`,
    NonstockApi.getAllFetcher
  );

  const deleteModal = useModal();
  const [selectedNonstock, setSelectedNonstock] = useState<
    Nonstock | undefined
  >(undefined);
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

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

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

    const deleteResponse = await NonstockApi.delete(
      selectedNonstock?.id as number
    );

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

    refreshNonstocks();

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

  const nonstocksColumns: ColumnDef<Nonstock>[] = useMemo(
    () => [
      {
        header: 'No',
        cell: (props) =>
          tableFilterState.pageSize * (tableFilterState.page - 1) +
          props.row.index +
          1,
      },
      {
        accessorKey: 'name',
        header: 'Nama',
      },
      {
        accessorFn: (row) => row.uom?.name ?? '-',
        header: 'UOM',
      },
      {
        accessorFn: (row) =>
          row.suppliers?.map((supplier) => supplier.name).join(', ') || '-',
        header: 'Supplier',
      },
      {
        accessorFn: (row) => row.flags?.join(', ') || '-',
        header: 'Flag',
      },
      {
        header: 'Aksi',
        cell: (props: CellContext<Nonstock, unknown>) => {
          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 = () => {
            setSelectedNonstock(props.row.original);
            deleteModal.openModal();
          };

          return (
            <RowOptionsMenu
              props={props}
              popoverPosition={isLast2Rows ? 'top' : 'bottom'}
              deleteClickHandler={deleteClickHandler}
            />
          );
        },
      },
    ],
    [tableFilterState.pageSize, tableFilterState.page, deleteModal]
  );

  return (
    <>
      <div className='w-full'>
        {/* Header Section */}
        <div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
          {/* Action Buttons */}
          <div className='w-fit flex flex-row gap-3 flex-wrap'>
            <RequirePermission permissions='lti.master.nonstocks.create'>
              <Button
                href='/master-data/nonstock/add'
                color='primary'
                className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
              >
                <Icon icon='heroicons:plus' width={20} height={20} />
                Add Nonstock
              </Button>
            </RequirePermission>
          </div>

          {/* Search */}
          <div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
            <DebouncedTextInput
              name='search'
              placeholder='Search'
              value={tableFilterState.search ?? ''}
              onChange={searchChangeHandler}
              startAdornment={
                <Icon
                  icon='heroicons:magnifying-glass'
                  width={20}
                  height={20}
                />
              }
              className={{
                wrapper: 'w-full min-w-24 max-w-3xs',
                inputWrapper: 'rounded-xl! shadow-button-soft',
                input:
                  'placeholder:font-semibold placeholder:text-base-content/50',
              }}
            />
          </div>
        </div>

        {/* Table Section */}
        <div className='flex flex-col mb-4'>
          {isLoading ? (
            <div className='w-full flex flex-row justify-center items-center p-4'>
              <span className='loading loading-spinner loading-xl' />
            </div>
          ) : !isResponseSuccess(nonstocks) || nonstocks.data?.length === 0 ? (
            <div className='p-3'>
              <NonstockTableSkeleton
                columns={nonstocksColumns}
                icon={
                  <Icon
                    icon='heroicons:document-text'
                    className='text-white'
                    width={20}
                    height={20}
                  />
                }
              />
            </div>
          ) : (
            <Table<Nonstock>
              data={nonstocks?.data}
              columns={nonstocksColumns}
              pageSize={tableFilterState.pageSize}
              page={nonstocks?.meta?.page ?? 0}
              totalItems={nonstocks?.meta?.total_results ?? 0}
              onPageChange={setPage}
              onPageSizeChange={setPageSize}
              isLoading={false}
              sorting={sorting}
              setSorting={setSorting}
              className={{
                containerClassName: 'p-3 mb-0',
                headerColumnClassName: 'text-nowrap',
              }}
            />
          )}
        </div>
      </div>

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

export default NonstocksTable;
