import { useEffect, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Search, X } from 'lucide-react'
import { api } from '@/lib/api'
import type { PagedResult, Product } from '@/lib/types'

interface Props {
  open: boolean
  onClose: () => void
  onPick: (product: Product) => void
  title?: string
}

export function ProductPicker({ open, onClose, onPick, title = 'Выбор товара' }: Props) {
  const [search, setSearch] = useState('')

  useEffect(() => { if (!open) setSearch('') }, [open])

  const results = useQuery({
    queryKey: ['product-picker', search],
    queryFn: async () => {
      const params = new URLSearchParams({ pageSize: '30' })
      if (search) params.set('search', search)
      return (await api.get<PagedResult<Product>>(`/api/catalog/products?${params}`)).data.items
    },
    enabled: open,
  })

  if (!open) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" onClick={onClose}>
      <div className="bg-white dark:bg-slate-900 rounded-xl shadow-2xl w-full max-w-2xl max-h-[80vh] flex flex-col overflow-hidden" onClick={(e) => e.stopPropagation()}>
        <div className="px-5 py-3 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
          <h3 className="font-semibold text-slate-900 dark:text-slate-100">{title}</h3>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-700 dark:hover:text-slate-200">
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="px-5 py-3 border-b border-slate-200 dark:border-slate-800">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
            <input
              autoFocus
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="По названию, артикулу или штрихкоду…"
              className="w-full pl-9 pr-3 py-2 rounded-md border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-brand)]"
            />
          </div>
        </div>

        <div className="flex-1 overflow-auto">
          {results.isLoading && <div className="p-6 text-center text-slate-400 text-sm">Загрузка…</div>}
          {results.data && results.data.length === 0 && (
            <div className="p-6 text-center text-slate-400 text-sm">
              {search ? 'Ничего не найдено' : 'Начни вводить название или штрихкод'}
            </div>
          )}
          {results.data && results.data.map((p) => (
            <button
              key={p.id}
              type="button"
              onClick={() => { onPick(p); onClose() }}
              className="w-full text-left px-5 py-2.5 border-b border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800 flex items-center justify-between gap-3"
            >
              <div className="min-w-0">
                <div className="font-medium text-slate-900 dark:text-slate-100 truncate">{p.name}</div>
                <div className="text-xs text-slate-400 flex gap-2 font-mono">
                  {p.article && <span>{p.article}</span>}
                  {p.barcodes[0] && <span>· {p.barcodes[0].code}</span>}
                  <span>· {p.unitName}</span>
                </div>
              </div>
              {p.referencePrice !== null && (
                <div className="text-xs text-slate-500 font-mono flex-shrink-0">
                  закуп: {p.referencePrice.toLocaleString('ru')} {p.purchaseCurrencyCode ?? ''}
                </div>
              )}
            </button>
          ))}
        </div>
      </div>
    </div>
  )
}
