import { useResultStore } from '@/common/stores/useResultStore'
import { Input, Modal, ModalBody, ModalContent, ModalHeader, Pagination, Select, SelectItem, Skeleton, Table, TableBody, TableCell, TableColumn, TableHeader, TableRow } from '@nextui-org/react'
import { Product } from 'prisma/generated/client'
import { useQuery } from '@tanstack/react-query'
import React, { useEffect, useMemo, useState } from 'react'
import { useDebounce } from 'usehooks-ts'
import { SHOWING_SELECTIONS } from '@/common/constants/product'

type Props = {
  modal: {
    isOpen: boolean,
    onOpenChange: () => void
  }
}

const ProductModal = ({ modal }: Props) => {
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState("")
  const [show, setShow] = useState("1")
  const debouncedSearch = useDebounce(search, 500)
  const { filter } = useResultStore()

  useEffect(() => {
    setPage(1)
  }, [debouncedSearch, show, filter.company])

  const { data } = useQuery({
    queryKey: ['product', page, debouncedSearch, filter.company, show],
    queryFn: async () => {
      const showValue = SHOWING_SELECTIONS.find((item) => item.key === show)?.value || ''
      const searchParams = new URLSearchParams({
        page: page.toString(),
        search: debouncedSearch,
        companyId: filter.company,
        show: showValue
      })
      const response = await fetch(`/api/product?${searchParams}`)
      const data: {
        products: (Product & { company: { id: number, name: string }, location?: { id: number, name: string } | null })[],
        page: number,
        totalPage: number
      } = await response.json()

      return data
    }
  })

  const [totalPage, setTotalPage] = useState(1)

  useEffect(() => {
    if (data?.totalPage) setTotalPage(data?.totalPage)
  }, [data?.totalPage])

  const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setShow(e.target.value)
  }

  return (
    <Modal isOpen={modal.isOpen} onOpenChange={modal.onOpenChange} size='5xl'>
      <ModalContent>
        <ModalHeader>Product List</ModalHeader>
        <ModalBody className='pb-6'>
          <div className="flex flex-wrap gap-3">
            <div className="w-10/12">
              <Input type='text' label="Search" value={search} onChange={(e) => setSearch(e.target.value)} />
            </div>
            <div className="flex-1 md:w-2/12">
              <Select
                label="Tampilkan"
                selectedKeys={show}
                name="show"
                onChange={handleSelectChange}
              >
                {SHOWING_SELECTIONS.map((selection) => (
                  <SelectItem key={selection.key}>{selection.label}</SelectItem>
                ))}
              </Select>
            </div>
          </div>
          {!data && (
            <Skeleton isLoaded={!!data} className='rounded-lg h-[600px]' />
          )}

          {!!data && (
            <Table className='max-h-[50vh]' isHeaderSticky>
              <TableHeader>
                <TableColumn>NAME</TableColumn>
                <TableColumn>ITEM CODE</TableColumn>
                <TableColumn>BARCODE</TableColumn>
                <TableColumn>ON-HAND QTY</TableColumn>
                <TableColumn>DIFFERENCE QTY</TableColumn>
                <TableColumn>LOCATION</TableColumn>
                <TableColumn>COMPANY</TableColumn>
              </TableHeader>
              <TableBody items={data?.products || []}>
                {(product) => (
                  <TableRow key={product.id}>
                    <TableCell>{product.name}</TableCell>
                    <TableCell>{product.itemCode}</TableCell>
                    <TableCell>{product.barcode}</TableCell>
                    <TableCell>{product.onhandQty}</TableCell>
                    <TableCell>{product.differenceQty}</TableCell>
                    <TableCell>{(product as any).location?.name || '-'}</TableCell>
                    <TableCell>{product.company.name}</TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          )}

          <Pagination
            initialPage={1}
            page={page}
            total={totalPage}
            onChange={(page) => setPage(page)}
            className='mt-2'
          />


        </ModalBody>
      </ModalContent>
    </Modal>
  )
}

export default ProductModal