'use client';

import Button from '@/components/Button';
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Table from '@/components/Table';
import RequirePermission from '@/components/helper/RequirePermission';
import ButtonFilter from '@/components/helper/ButtonFilter';
import Modal, { useModal } from '@/components/Modal';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import { OptionType } from '@/components/input/SelectInput';
import { isResponseSuccess } from '@/lib/api-helper';
import { cn, formatCurrency, formatNumber } from '@/lib/helper';
import { InventoryProductApi } from '@/services/api/inventory';
import { ProductCategoryApi } from '@/services/api/master-data';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { InventoryProduct } from '@/types/api/inventory/product';
import { ProductCategory } from '@/types/api/master-data/product-category';
import { Icon } from '@iconify/react';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import { ChangeEventHandler, useMemo, useState } from 'react';
import useSWR from 'swr';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import InventoryProductTableSkeleton from '@/components/pages/inventory/product/skeleton/InventoryProductTableSkeleton';

const RowOptionsMenu = ({
  popoverPosition = 'bottom',
  props,
}: {
  popoverPosition: 'bottom' | 'top';
  props: CellContext<InventoryProduct, unknown>;
}) => {
  const popoverId = `product#${props.row.original.id}`;
  const popoverAnchorName = `--anchor-product#${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.inventory.product_stock.detail'>
            <Button
              href={`/inventory/product/detail?inventoryProductId=${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>
        </div>
      </PopoverContent>
    </div>
  );
};

const InventoryProductTable = () => {
  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter<{
    search: string;
    categoryFilter?: OptionType<string>;
  }>({
    initial: {
      search: '',
      categoryFilter: undefined,
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      categoryFilter: 'product_category_id',
    },
    persist: true,
    storeName: 'inventory-product-table',
  });

  // ===== FILTER MODAL STATE =====
  const filterModal = useModal();

  // ===== FORMIK SETUP =====
  const formik = useFormik<{ category?: OptionType<string> }>({
    initialValues: { category: tableFilterState.categoryFilter },
    validationSchema: Yup.object().shape({
      category: Yup.object({
        value: Yup.string().nullable(),
        label: Yup.string().nullable(),
      }).nullable(),
    }),
    onSubmit: (values, { setSubmitting }) => {
      updateFilter('categoryFilter', values.category || undefined, true);
      filterModal.closeModal();
      setSubmitting(false);
    },
    onReset: () => {
      updateFilter('categoryFilter', undefined, true);
      filterModal.closeModal();
    },
  });

  // ===== CATEGORY OPTIONS =====
  const {
    setInputValue: setCategoryInputValue,
    options: categoryOptions,
    isLoadingOptions: isLoadingCategoryOptions,
    loadMore: loadMoreCategories,
  } = useSelect<ProductCategory>(
    filterModal.open ? ProductCategoryApi.basePath : null,
    'id',
    'name',
    'search'
  );

  // ===== HANDLE FILTER MODAL OPEN =====
  const handleFilterModalOpen = () => {
    formik.setValues({
      category: tableFilterState.categoryFilter ?? undefined,
    });
    filterModal.openModal();
  };

  const handleFilterCategoryChange = (
    val: OptionType | OptionType[] | null
  ) => {
    formik.setFieldValue('category', val);
  };

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

  const columns: ColumnDef<InventoryProduct>[] = useMemo(
    () => [
      {
        header: 'No',
        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: CellContext<InventoryProduct, 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;

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

  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.inventory.product_stock.create'>
              <Button
                href='/inventory/product/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 Product
              </Button>
            </RequirePermission>
          </div>

          {/* Search and Filter */}
          <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',
              }}
            />
            <ButtonFilter
              values={tableFilterState}
              excludeFields={['page', 'pageSize', 'search']}
              onClick={handleFilterModalOpen}
              className='px-3 py-2.5'
            />
          </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(inventoryProducts) ||
            inventoryProducts.data?.length === 0 ? (
            <div className='p-3'>
              <InventoryProductTableSkeleton
                columns={columns}
                icon={
                  <Icon
                    icon='heroicons:document-text'
                    className='text-white'
                    width={20}
                    height={20}
                  />
                }
              />
            </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}
              onPageSizeChange={setPageSize}
              isLoading={isLoading}
              sorting={sorting}
              setSorting={setSorting}
              className={{
                containerClassName: cn('p-3 mb-0'),
                headerColumnClassName: 'text-nowrap',
              }}
            />
          )}
        </div>
      </div>

      {/* Filter Modal */}
      <Modal
        ref={filterModal.ref}
        className={{
          modal: 'p-0',
          modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
        }}
      >
        <div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
          <div className='flex items-center gap-2 text-primary'>
            <Icon icon='heroicons:funnel' width={20} height={20} />
            <h3 className='font-medium text-sm'>Filter Data</h3>
          </div>
          <Button
            variant='link'
            onClick={filterModal.closeModal}
            className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
          >
            <Icon icon='heroicons:x-mark' width={20} height={20} />
          </Button>
        </div>
        <form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
          <div className='p-4 flex flex-col gap-1.5'>
            <SelectInput
              label='Kategori Produk'
              placeholder='Pilih Kategori'
              options={categoryOptions}
              value={formik.values.category}
              onChange={handleFilterCategoryChange}
              onInputChange={setCategoryInputValue}
              isLoading={isLoadingCategoryOptions}
              isClearable
              onMenuScrollToBottom={loadMoreCategories}
              className={{ wrapper: 'w-full' }}
            />
          </div>
          <div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
            <Button
              type='reset'
              variant='soft'
              className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
            >
              Reset Filter
            </Button>
            <Button
              type='submit'
              className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
              disabled={!formik.isValid || formik.isSubmitting}
            >
              Apply Filter
            </Button>
          </div>
        </form>
      </Modal>
    </>
  );
};

export default InventoryProductTable;
