'use client';

import { useState, useMemo } from 'react';
import { SortingState } from '@tanstack/react-table';
import { Icon } from '@iconify/react';
import Table from '@/components/Table';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import { ROWS_OPTIONS } from '@/config/constant';
import { Movement } from '@/types/api/inventory/movement';
import { TableToolbar } from '@/components/table/TableToolbar';
import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
import { TableRowOptions } from '@/components/table/TableRowOptions';
import { OptionType } from '@/components/input/SelectInput';
import Button from '@/components/Button';
import { cn } from '@/lib/helper';

// Dummy data
const baseMetadata = {
  created_user: {
    id: 1,
    id_user: 1,
    email: 'user@example.com',
    name: 'User',
  },
  created_at: '2024-06-01T00:00:00Z',
  updated_at: '2024-06-01T00:00:00Z',
};

const dummyMovements: Movement[] = [
  {
    ...baseMetadata,
    id: 1,
    alasan_transfer: 'Restock',
    tanggal_transfer: '2024-06-01',
    warehouse_asal: {
      ...baseMetadata,
      id: 1,
      name: 'Warehouse A',
      type: 'AREA',
      area: { id: 1, name: 'Area 1' },
    },
    warehouse_tujuan: {
      ...baseMetadata,
      id: 2,
      name: 'Warehouse B',
      type: 'AREA',
      area: { id: 2, name: 'Area 2' },
    },
    product: [
      {
        product: {
          ...baseMetadata,
          id: 1,
          name: 'Product X',
          brand: 'Brand X',
          sku: 'SKU-X',
          product_price: 10000,
          selling_price: 12000,
          tax: 10,
          expiry_period: 365,
          uom: {
            ...baseMetadata,
            id: 1,
            name: 'PCS',
          },
          product_category: {
            ...baseMetadata,
            id: 1,
            code: 'CAT-1',
            name: 'Category 1',
          },
          suppliers: [],
          flags: [],
        },
        qty_product: 10,
      },
    ],
    ekspedisi: [
      {
        product_id: 1,
        qty: 10,
        supplier: {
          ...baseMetadata,
          id: 1,
          name: 'Supplier 1',
          alias: 'S1',
          category: 'General',
          pic: 'PIC 1',
          type: 'Type 1',
          hatchery: 'Hatchery 1',
          phone: '08123456789',
          email: 'supplier1@example.com',
          address: 'Address 1',
          npwp: '1234567890123456',
          account_number: '1234567890',
          balance: 0,
          due_date: 30,
        },
        plat_nomor: 'B 1234 CD',
        no_surat_jalan: 'SJ-001',
        dokumen: 'doc1.pdf',
        biaya_ekspedisi: 50000,
        nama_sopir: 'Andi',
      },
    ],
  },
  {
    ...baseMetadata,
    id: 2,
    alasan_transfer: 'Mutasi Stok',
    tanggal_transfer: '2024-06-02',
    warehouse_asal: {
      ...baseMetadata,
      id: 2,
      name: 'Warehouse B',
      type: 'AREA',
      area: { id: 2, name: 'Area 2' },
    },
    warehouse_tujuan: {
      ...baseMetadata,
      id: 3,
      name: 'Warehouse C',
      type: 'AREA',
      area: { id: 3, name: 'Area 3' },
    },
    product: [
      {
        product: {
          ...baseMetadata,
          id: 2,
          name: 'Product Y',
          brand: 'Brand Y',
          sku: 'SKU-Y',
          product_price: 20000,
          selling_price: 25000,
          tax: 5,
          expiry_period: 180,
          uom: {
            ...baseMetadata,
            id: 2,
            name: 'BOX',
          },
          product_category: {
            ...baseMetadata,
            id: 2,
            code: 'CAT-2',
            name: 'Category 2',
          },
          suppliers: [],
          flags: [],
        },
        qty_product: 5,
      },
    ],
    ekspedisi: [
      {
        product_id: 2,
        qty: 5,
        supplier: {
          ...baseMetadata,
          id: 2,
          name: 'Supplier 2',
          alias: 'S2',
          category: 'Special',
          pic: 'PIC 2',
          type: 'Type 2',
          hatchery: 'Hatchery 2',
          phone: '08123456780',
          email: 'supplier2@example.com',
          address: 'Address 2',
          npwp: '1234567890123457',
          account_number: '1234567891',
          balance: 1000,
          due_date: 15,
        },
        plat_nomor: 'D 5678 EF',
        no_surat_jalan: 'SJ-002',
        dokumen: 'doc2.pdf',
        biaya_ekspedisi: 60000,
        nama_sopir: 'Budi',
      },
    ],
  },
  {
    ...baseMetadata,
    id: 3,
    alasan_transfer: 'Pengembalian',
    tanggal_transfer: '2024-06-03',
    warehouse_asal: {
      ...baseMetadata,
      id: 3,
      name: 'Warehouse C',
      type: 'AREA',
      area: { id: 3, name: 'Area 3' },
    },
    warehouse_tujuan: {
      ...baseMetadata,
      id: 1,
      name: 'Warehouse A',
      type: 'AREA',
      area: { id: 1, name: 'Area 1' },
    },
    product: [
      {
        product: {
          ...baseMetadata,
          id: 3,
          name: 'Product Z',
          brand: 'Brand Z',
          sku: 'SKU-Z',
          product_price: 15000,
          selling_price: 18000,
          tax: 8,
          expiry_period: 90,
          uom: {
            ...baseMetadata,
            id: 3,
            name: 'KG',
          },
          product_category: {
            ...baseMetadata,
            id: 3,
            code: 'CAT-3',
            name: 'Category 3',
          },
          suppliers: [],
          flags: [],
        },
        qty_product: 8,
      },
    ],
    ekspedisi: [
      {
        product_id: 3,
        qty: 8,
        supplier: {
          ...baseMetadata,
          id: 3,
          name: 'Supplier 3',
          alias: 'S3',
          category: 'Return',
          pic: 'PIC 3',
          type: 'Type 3',
          hatchery: 'Hatchery 3',
          phone: '08123456781',
          email: 'supplier3@example.com',
          address: 'Address 3',
          npwp: '1234567890123458',
          account_number: '1234567892',
          balance: 500,
          due_date: 10,
        },
        plat_nomor: 'F 9101 GH',
        no_surat_jalan: 'SJ-003',
        dokumen: 'doc3.pdf',
        biaya_ekspedisi: 40000,
        nama_sopir: 'Cici',
      },
    ],
  },
  {
    ...baseMetadata,
    id: 4,
    alasan_transfer: 'Transfer Internal',
    tanggal_transfer: '2024-06-04',
    warehouse_asal: {
      ...baseMetadata,
      id: 4,
      name: 'Warehouse D',
      type: 'AREA',
      area: { id: 4, name: 'Area 4' },
    },
    warehouse_tujuan: {
      ...baseMetadata,
      id: 5,
      name: 'Warehouse E',
      type: 'AREA',
      area: { id: 5, name: 'Area 5' },
    },
    product: [
      {
        product: {
          ...baseMetadata,
          id: 4,
          name: 'Product A',
          brand: 'Brand A',
          sku: 'SKU-A',
          product_price: 5000,
          selling_price: 7000,
          tax: 0,
          expiry_period: 60,
          uom: {
            ...baseMetadata,
            id: 4,
            name: 'LITER',
          },
          product_category: {
            ...baseMetadata,
            id: 4,
            code: 'CAT-4',
            name: 'Category 4',
          },
          suppliers: [],
          flags: [],
        },
        qty_product: 20,
      },
    ],
    ekspedisi: [
      {
        product_id: 4,
        qty: 20,
        supplier: {
          ...baseMetadata,
          id: 4,
          name: 'Supplier 4',
          alias: 'S4',
          category: 'Internal',
          pic: 'PIC 4',
          type: 'Type 4',
          hatchery: 'Hatchery 4',
          phone: '08123456782',
          email: 'supplier4@example.com',
          address: 'Address 4',
          npwp: '1234567890123459',
          account_number: '1234567893',
          balance: 200,
          due_date: 20,
        },
        plat_nomor: 'H 2345 IJ',
        no_surat_jalan: 'SJ-004',
        dokumen: 'doc4.pdf',
        biaya_ekspedisi: 30000,
        nama_sopir: 'Dedi',
      },
    ],
  },
];

const MovementTable = () => {
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [sorting, setSorting] = useState<SortingState>([]);
  const [, setSelectedMovement] = useState<Movement | undefined>(undefined);
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  const deleteModal = useModal();

  const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
    setPage(1);
  };

  const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
    const newVal = val as OptionType;
    setPageSize(newVal.value as number);
    setPage(1);
  };

  const confirmationModalDeleteClickHandler = async () => {
    setIsDeleteLoading(true);
    setTimeout(() => {
      setIsDeleteLoading(false);
      deleteModal.closeModal();
    }, 1000);
  };

  const paginatedData = useMemo(() => {
    const start = (page - 1) * pageSize;
    return dummyMovements.slice(start, start + pageSize);
  }, [page, pageSize]);

  return (
    <div className='flex flex-col gap-4'>
      <div className='flex flex-col gap-2 mb-4'>
        <TableToolbar
          addButton={{
            href: '/inventory/movement/add',
            label: 'Tambah Movement',
          }}
          search={{
            value: search,
            onChange: searchChangeHandler,
            placeholder: 'Cari Movement',
          }}
        />
        <TableRowSizeSelector
          value={pageSize}
          onChange={pageSizeChangeHandler}
          options={ROWS_OPTIONS}
        />
      </div>

      <Table
        data={paginatedData}
        columns={[
          {
            header: '#',
            cell: (props) => pageSize * (page - 1) + props.row.index + 1,
          },
          {
            accessorKey: 'warehouse_asal',
            header: 'Gudang Asal',
            cell: (props) => props.row.original.warehouse_asal.name,
          },
          {
            accessorKey: 'warehouse_tujuan',
            header: 'Gudang Tujuan',
            cell: (props) => props.row.original.warehouse_tujuan.name,
          },
          {
            accessorKey: 'product',
            header: 'Nama Produk',
            cell: (props) =>
              props.row.original.product.map((p) => p.product.name),
          },
          {
            accessorKey: 'alasan_transfer',
            header: 'Catatan',
          },
          {
            accessorKey: 'biaya_ekspedisi',
            header: 'Biaya Ekspedisi',
            cell: (props) =>
              props.row.original.ekspedisi.map((e) => e.biaya_ekspedisi),
          },
          {
            id: 'actions',
            cell: (props) => (
              <div className='dropdown dropdown-end'>
                <Button tabIndex={0} variant='ghost' className='px-2'>
                  <Icon icon='carbon:overflow-menu-vertical' />
                </Button>
                <TableRowOptions
                  type='dropdown'
                  recordId={props.row.original.id}
                  basePath='/inventory/movement'
                  onDelete={() => {
                    setSelectedMovement(props.row.original);
                    deleteModal.openModal();
                  }}
                />
              </div>
            ),
          },
        ]}
        pageSize={pageSize}
        page={page}
        totalItems={dummyMovements.length}
        onPageChange={setPage}
        isLoading={false}
        sorting={sorting}
        setSorting={setSorting}
        className={{
          containerClassName: cn({
            'mb-20': paginatedData.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',
        }}
      />

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

export default MovementTable;
