import Button from '@/components/Button';
import Card from '@/components/Card';
import Table from '@/components/Table';
import { isResponseSuccess } from '@/lib/api-helper';
import { formatDate, formatNumber, formatTitleCase } from '@/lib/helper';
import { StockLogApi } from '@/services/api/inventory';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ProductWarehouseStock, StockLog } from '@/types/api/inventory/product';
import { ColumnDef } from '@tanstack/react-table';
import { FileDown } from 'lucide-react';
import toast from 'react-hot-toast';
import { useEffect, useRef, useState } from 'react';
import useSWR from 'swr';

const stockLogTableColumns: (warehouseName: string) => ColumnDef<StockLog>[] = (
  warehouseName
) => [
  {
    header: 'ID',
    accessorKey: 'id',
  },
  {
    header: 'Tanggal',
    accessorKey: 'created_at',
    cell: (props) => {
      return formatDate(props.row.original.created_at, 'DD-MMM-yyyy');
    },
  },
  {
    header: 'Gudang',
    accessorKey: 'warehouse_name',
    cell: warehouseName,
  },
  {
    header: 'Stock Akhir',
    accessorKey: 'stock',
    cell: (props) => {
      return formatNumber(props.row.original.stock);
    },
  },
  {
    header: 'Peningkatan',
    accessorKey: 'increase',
    cell: (props) => {
      return formatNumber(props.row.original.increase);
    },
  },
  {
    header: 'Penurunan',
    accessorKey: 'decrease',
    cell: (props) => {
      return formatNumber(props.row.original.decrease);
    },
  },
  {
    header: 'Jenis Transaksi',
    accessorKey: 'loggable_type',
    cell: (props) => {
      return props.row.original.loggable_type
        ? formatTitleCase(props.row.original.loggable_type)
        : '-';
    },
  },
  {
    header: 'Catatan',
    accessorKey: 'notes',
    cell: (props) => {
      return props.row.original.notes ? props.row.original.notes : '-';
    },
  },
  {
    header: 'Oleh',
    accessorKey: 'created_user.name',
  },
];

const StockLogTable = ({
  productWarehouse,
}: {
  productWarehouse: ProductWarehouseStock;
}) => {
  const [isExportLoading, setIsExportLoading] = useState(false);
  const [hasBeenVisible, setHasBeenVisible] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setHasBeenVisible(true);
          observer.disconnect();
        }
      },
      { threshold: 0.1 }
    );

    if (containerRef.current) observer.observe(containerRef.current);
    return () => observer.disconnect();
  }, []);

  const {
    state: tableFilterState,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      product_warehouse_id: productWarehouse.id,
    },
  });

  const handleExportExcel = async () => {
    setIsExportLoading(true);
    try {
      await StockLogApi.exportToExcel(
        productWarehouse.warehouse_name,
        getTableFilterQueryString()
      );
      toast.success('Excel berhasil dibuat dan diunduh.');
    } catch {
      toast.error('Gagal membuat Excel. Silakan coba lagi.');
    } finally {
      setIsExportLoading(false);
    }
  };

  const { data: stockLogsResponse, isLoading: isLoadingStockLogs } = useSWR(
    hasBeenVisible
      ? `${StockLogApi.basePath}${getTableFilterQueryString()}`
      : null,
    StockLogApi.getAllFetcher
  );

  const stockLogs = isResponseSuccess(stockLogsResponse)
    ? stockLogsResponse.data
    : [];

  return (
    <div ref={containerRef}>
      <Card
        title={`Informasi Stock Produk - ${productWarehouse.warehouse_name}`}
        collapsible
        variant='bordered'
        className={{
          wrapper: 'w-full',
        }}
      >
        <div className='flex justify-end px-6 pt-4'>
          <Button onClick={handleExportExcel} isLoading={isExportLoading}>
            <FileDown size={16} />
            Export Excel
          </Button>
        </div>
        <Table<StockLog>
          data={stockLogs}
          columns={stockLogTableColumns(productWarehouse.warehouse_name)}
          page={tableFilterState.page ?? 0}
          pageSize={tableFilterState.pageSize}
          onPageChange={setPage}
          onPageSizeChange={setPageSize}
          isLoading={isLoadingStockLogs}
          totalItems={
            isResponseSuccess(stockLogsResponse)
              ? stockLogsResponse.meta?.total_results
              : 0
          }
          className={{
            containerClassName: 'mt-4 mb-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',
          }}
        />
      </Card>
    </div>
  );
};

export default StockLogTable;
