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

const mockProducts: Product[] = Array.from({ length: 500 }).map((_, idx) => {
  const lab = ['EMS', 'Eurofarma', 'Aché'][idx % 3]
  const actives = ['Amoxicilina', 'Dipirona', 'Losartana']
  const categories = ['Antibiótico', 'Analgésico', 'Cardiovascular']
  return {
    id: `prod-${idx + 1}`,
    name: `Produto ${idx + 1}`,
    activeIngredient: actives[idx % actives.length],
    lab,
    category: categories[idx % categories.length],
    batch: `L${1000 + idx}`,
    expiry: `202${(idx % 4) + 5}-0${(idx % 9) + 1}`,
    vendorId: `vendor-${idx % 4}`,
    vendorName: ['Distribuidora Norte', 'Distribuidora Sul', 'FastMed', 'HealthPro'][idx % 4],
    price: 10 + (idx % 20)
  }
})

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-9 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.activeIngredient}</div>
      <div className="truncate text-gray-700">{product.lab}</div>
      <div className="truncate text-gray-700">{product.batch}</div>
      <div className="truncate text-gray-700">{product.expiry}</div>
      <div className="truncate text-gray-700">{product.vendorName}</div>
      <div className="text-right font-semibold text-medicalBlue">R$ {product.price.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({
            id: product.id,
            name: product.name,
            activeIngredient: product.activeIngredient,
            lab: product.lab,
            batch: product.batch,
            expiry: product.expiry,
            vendorId: product.vendorId,
            vendorName: product.vendorName,
            unitPrice: product.price
          })}
        >
          Adicionar
        </button>
      </div>
    </div>
  )
}

export function DashboardPage() {
  const { filters, setFilters } = usePersistentFilters()
  const [search, setSearch] = useState('')

  const filtered = useMemo(() => {
    return mockProducts.filter((p) => {
      const matchesSearch = p.name.toLowerCase().includes(search.toLowerCase())
      const matchesActive = filters.activeIngredient
        ? p.activeIngredient === filters.activeIngredient
        : true
      const matchesCategory = filters.category ? p.category === filters.category : true
      const matchesLab = filters.lab ? p.lab === filters.lab : true
      return matchesSearch && matchesActive && matchesCategory && matchesLab
    })
  }, [filters.activeIngredient, filters.category, filters.lab, search])

  const labs = Array.from(new Set(mockProducts.map((p) => p.lab)))
  const actives = Array.from(new Set(mockProducts.map((p) => p.activeIngredient)))
  const categories = Array.from(new Set(mockProducts.map((p) => p.category)))

  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 lg:grid-cols-4">
          <div className="lg:col-span-2">
            <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 ou SKU"
              className="mt-2 w-full rounded border border-gray-200 px-3 py-2"
            />
            <p className="mt-1 text-xs text-gray-500">Otimizada para milhares de SKUs com renderização virtualizada.</p>
          </div>
          <div>
            <label className="text-sm font-semibold text-gray-700">Princípio Ativo</label>
            <select
              className="mt-2 w-full rounded border border-gray-200 px-2 py-2"
              value={filters.activeIngredient}
              onChange={(e) => setFilters((prev) => ({ ...prev, activeIngredient: e.target.value }))}
            >
              <option value="">Todos</option>
              {actives.map((active) => (
                <option key={active} value={active}>
                  {active}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="text-sm font-semibold text-gray-700">Categoria</label>
            <select
              className="mt-2 w-full rounded border border-gray-200 px-2 py-2"
              value={filters.category}
              onChange={(e) => setFilters((prev) => ({ ...prev, category: e.target.value }))}
            >
              <option value="">Todas</option>
              {categories.map((category) => (
                <option key={category} value={category}>
                  {category}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="text-sm font-semibold text-gray-700">Laboratório</label>
            <select
              className="mt-2 w-full rounded border border-gray-200 px-2 py-2"
              value={filters.lab}
              onChange={(e) => setFilters((prev) => ({ ...prev, lab: e.target.value }))}
            >
              <option value="">Todos</option>
              {labs.map((lab) => (
                <option key={lab} value={lab}>
                  {lab}
                </option>
              ))}
            </select>
          </div>
          <div className="lg:col-span-4 flex justify-end">
            <button
              className="rounded bg-gray-200 px-3 py-2 text-xs font-semibold text-gray-700"
              onClick={() => setFilters(defaultFilters)}
            >
              Limpar filtros
            </button>
          </div>
        </div>
        <div className="rounded-lg border border-gray-200 bg-gray-200 shadow-inner">
          <div className="table-header grid grid-cols-9 gap-2 px-3 py-2 text-xs font-semibold uppercase tracking-wide">
            <span>Nome</span>
            <span>Princípio Ativo</span>
            <span>Laboratório</span>
            <span>Lote</span>
            <span>Validade</span>
            <span>Distribuidora</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>
  )
}
