"use client";
import { useResultStore } from '@/common/stores/useResultStore';
import { StockOpnameLocationRes } from '@/common/types/stockOpname';
import { Skeleton } from '@nextui-org/react';
import { useQuery } from '@tanstack/react-query'
import styles from './table.module.css'
import { CornerDownRightIcon } from 'lucide-react';
import { User } from 'prisma/generated/client';
import clsxm from '@/common/libs/clsxm';
import getClientCredential from '@/common/libs/getClientCredential';

const DetailRow = ({ productId }: { productId: number }) => {
  const { filter } = useResultStore()

  const detailLocation = useQuery({
    queryKey: ['detailLocation', productId, filter.company],
    queryFn: async () => {
      const searchParams = new URLSearchParams()
      if (!filter?.company) return null
      searchParams.set('companyId', filter.company)
      searchParams.set('productId', productId.toString())
      return await fetch(`/api/stock-opname/location?${searchParams}`)
        .then(res => res.json())
    }
  })

  if (detailLocation.isLoading) {
    return (
      <tr>
        <td colSpan={8}>
          <div className='grid grid-cols-1 gap-y-2 w-full'>
            <Skeleton className='w-full h-8' />
          </div>
        </td>
      </tr>
    )
  }

  return (
    <>
      {detailLocation.data?.map((location: StockOpnameLocationRes) => (
        <tr key={location.id}>
          <td />
          <td className={clsxm(styles.td, 'min-w-[250px]')}>
            <div className="flex gap-x-2">
              <CornerDownRightIcon size={16} />
              {location.name}
            </div>
          </td>
          <td className={styles.td}>
            <QuantityColumn data={location.COUNT1} />
          </td>
          <td className={styles.td}>
            <QuantityColumn data={location.COUNT2} />
          </td>
          <td className={styles.td}>
            <QuantityColumn data={location.COUNT3} />
          </td>
          <td className={styles.td}>
            <QuantityColumn data={location.VERIFICATION} />
          </td>
          <td className={styles.td} />
          <td className={styles.td} />
        </tr>
      ))}
    </>
  )
}

const QuantityColumn = ({ data }: { data: { quantity?: number | undefined, user?: User } }) => {
  const credential = getClientCredential()

  if (!(credential?.team == "VERIFICATION")) return '-'

  return (
    <div className='grid grid-cols-1'>
      {typeof data?.quantity !== 'number' && '-'}
      {data.quantity !== null && (
        <>
          <span>{data.quantity}</span>
          <div className='text-xs text-neutral-500'>
            {data.user?.name}
          </div>
        </>
      )}
    </div>
  )
}

export default DetailRow