import { useMemo, useState } from 'react'
import { FixedSizeList as List, ListChildComponentProps } from 'react-window'
import { Product } from '../types/product'
import { useCartStore } from '../stores/cartStore'
import { Shell } from '../layouts/Shell'

// Mock data updated to match new Product interface
const mockProducts: Product[] = Array.from({ length: 500 }).map((_, idx) => {
  return {
    id: `prod-${idx + 1}`,
    seller_id: `seller-${idx % 4}`,
    name: `Produto ${idx + 1}`,
    description: `Descrição do produto ${idx + 1}`,
    batch: `L${1000 + idx}`,
    expires_at: `202${(idx % 4) + 5}-0${(idx % 9) + 1}-01`,
    price_cents: 1000 + (idx % 2000),
    stock: 100 + idx,
    created_at: new Date().toISOString(),
    updated_at: new Date().toISOString()
  }
})

function DenseRow({ index, style, data }: ListChildComponentProps<Product[]>) {
  const product = data[index]
  const addItem = useCartStore((state) => state.addItem)

  return (
    <div
      style={style}
      className="grid grid-cols-7 items-center gap-2 border-b border-gray-200 bg-gray-50 px-3 text-sm hover:bg-gray-100"
    >
      <div className="truncate font-semibold text-gray-800">{product.name}</div>
      <div className="truncate text-gray-700">{product.description}</div>
      <div className="truncate text-gray-700">{product.batch}</div>
      <div className="truncate text-gray-700">{product.expires_at}</div>
      <div className="text-right font-semibold text-medicalBlue">R$ {(product.price_cents / 100).toFixed(2)}</div>
      <div className="col-span-2 flex items-center justify-end gap-2">
        <button
          className="rounded bg-healthGreen px-3 py-1 text-xs font-semibold text-white shadow-sm hover:opacity-90"
          onClick={() => addItem({
            ...product,
            price: product.price_cents / 100 // Adapter for cart store if needed
          } as any)}
        >
          Adicionar
        </button>
      </div>
    </div>
  )
}

export function DashboardPage() {
  const [search, setSearch] = useState('')

  const filtered = useMemo(() => {
    return mockProducts.filter((p) => {
      const matchesSearch = p.name.toLowerCase().includes(search.toLowerCase())
      return matchesSearch
    })
  }, [search])

  return (
    <Shell>
      <div className="mb-4 flex flex-col gap-4">
        <div className="grid grid-cols-1 gap-3 rounded-lg bg-white p-4 shadow-sm">
          <div>
            <p className="text-sm font-semibold text-gray-700">Busca rápida</p>
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Procure por nome"
              className="mt-2 w-full rounded border border-gray-200 px-3 py-2"
            />
          </div>
        </div>
        <div className="rounded-lg border border-gray-200 bg-gray-200 shadow-inner">
          <div className="table-header grid grid-cols-7 gap-2 px-3 py-2 text-xs font-semibold uppercase tracking-wide">
            <span>Nome</span>
            <span>Descrição</span>
            <span>Lote</span>
            <span>Validade</span>
            <span className="text-right">Preço</span>
            <span className="col-span-2 text-right">Ações</span>
          </div>
          <List
            height={520}
            itemCount={filtered.length}
            itemSize={52}
            width="100%"
            itemData={filtered}
          >
            {DenseRow}
          </List>
        </div>
      </div>
    </Shell>
  )
}
