'use client';

import Card from '@/components/Card';
import { OptionType } from '@/components/input/SelectInput';
import { FormHeader } from '@/components/helper/form/FormHeader';
import ButtonFilter from '@/components/helper/ButtonFilter';
import RequirePermission from '@/components/helper/RequirePermission';
import { useModal } from '@/components/Modal';
import StockLogFilterModal from '@/components/pages/inventory/product/detail/StockLogFilterModal';
import StockLogTable from '@/components/pages/inventory/product/detail/StockLogTable';
import StockProductWarehouseTable from '@/components/pages/inventory/product/detail/StockProductWarehouseTable';
import { formatCurrency, formatNumber } from '@/lib/helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { InventoryProduct } from '@/types/api/inventory/product';
import { useMemo } from 'react';

const InventoryProductDetail = ({
  inventoryProduct,
}: {
  inventoryProduct?: InventoryProduct;
}) => {
  const filterModal = useModal();

  const { state: filterState, updateFilter } = useTableFilter<{
    warehouse_ids: OptionType<number>[];
  }>({
    initial: {
      warehouse_ids: [],
    },
    persist: true,
    storeName: 'inventory-product-stock-log-filter',
  });

  const filteredProductWarehouses = useMemo(() => {
    const warehouses = inventoryProduct?.product_warehouses ?? [];
    if (!filterState.warehouse_ids?.length) return warehouses;
    const selectedIds = new Set(filterState.warehouse_ids.map((w) => w.value));
    return warehouses.filter((pw) => selectedIds.has(pw.warehouse_id));
  }, [inventoryProduct?.product_warehouses, filterState.warehouse_ids]);

  const filterSubmitHandler = (values: {
    warehouse_ids: OptionType<number>[];
  }) => {
    updateFilter('warehouse_ids', values.warehouse_ids, true);
  };

  const filterResetHandler = () => {
    updateFilter('warehouse_ids', [], true);
  };

  return (
    <div className='flex flex-col gap-4 p-4'>
      <FormHeader
        title='Detail Persediaan Produk'
        backUrl='/inventory/product'
      />

      <Card
        title='Informasi Produk'
        variant='bordered'
        className={{
          wrapper: 'w-full mt-4',
        }}
      >
        <div className='grid grid-cols-2 gap-4'>
          <div className='overflow-x-auto rounded-box border border-base-content/5 bg-base-100 mt-3'>
            <table className='table'>
              <tbody>
                <tr>
                  <td className='font-semibold'>SKU</td>
                  <td>:</td>
                  <td>{inventoryProduct?.sku}</td>
                </tr>
                <tr>
                  <td className='font-semibold'>Nama Produk</td>
                  <td>:</td>
                  <td>{inventoryProduct?.name}</td>
                </tr>
                <tr>
                  <td className='font-semibold'>Kategory</td>
                  <td>:</td>
                  <td>{inventoryProduct?.product_category.name}</td>
                </tr>
                <tr>
                  <td className='font-semibold'>Satuan</td>
                  <td>:</td>
                  <td>{inventoryProduct?.uom.name}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div className='overflow-x-auto rounded-box border border-base-content/5 bg-base-100 mt-3'>
            <table className='table'>
              <tbody>
                <tr>
                  <td className='font-semibold'>Harga Jual</td>
                  <td>:</td>
                  <td>
                    {inventoryProduct?.selling_price
                      ? formatCurrency(inventoryProduct.selling_price)
                      : '-'}
                  </td>
                </tr>
                <tr>
                  <td className='font-semibold'>Harga Beli</td>
                  <td>:</td>
                  <td>
                    {inventoryProduct?.product_price
                      ? formatCurrency(inventoryProduct?.product_price)
                      : '-'}
                  </td>
                </tr>
                <tr>
                  <td className='font-semibold'>Pajak</td>
                  <td>:</td>
                  <td>
                    {inventoryProduct?.tax
                      ? formatNumber(inventoryProduct?.tax) + '%'
                      : '-'}
                  </td>
                </tr>
                <tr>
                  <td className='font-semibold'>Total Stok</td>
                  <td>:</td>
                  <td>
                    {inventoryProduct?.total_stock
                      ? formatNumber(inventoryProduct?.total_stock)
                      : '0'}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </Card>

      <StockProductWarehouseTable
        productWarehouseStock={inventoryProduct?.product_warehouses ?? []}
      />

      <RequirePermission permissions={'lti.inventory.stock_log.list'}>
        <div className='flex justify-end'>
          <ButtonFilter
            values={{ warehouse_ids: filterState.warehouse_ids }}
            onClick={filterModal.openModal}
            className='px-3 py-2.5'
          />
        </div>
        {filteredProductWarehouses.map((productWarehouse) => (
          <StockLogTable
            key={productWarehouse.id}
            productWarehouse={productWarehouse}
          />
        ))}
      </RequirePermission>

      <StockLogFilterModal
        ref={filterModal.ref}
        productWarehouses={inventoryProduct?.product_warehouses ?? []}
        initialValues={{ warehouse_ids: filterState.warehouse_ids }}
        onSubmit={filterSubmitHandler}
        onReset={filterResetHandler}
      />
    </div>
  );
};

export default InventoryProductDetail;
