import { useState, useRef, useEffect, useCallback } from 'react'
import { BookUser, Search, Star, User } from 'lucide-react'
import { contactsApi, type PecContactResponse } from '@/api/contacts.api'

interface ContactPickerPopoverProps {
  onSelect: (email: string) => void
  size?: 'sm' | 'md'
}

function useDebounce<T>(value: T, delay: number): T {
  const [debounced, setDebounced] = useState<T>(value)
  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delay)
    return () => clearTimeout(timer)
  }, [value, delay])
  return debounced
}

export function ContactPickerPopover({ onSelect, size = 'md' }: ContactPickerPopoverProps) {
  const [open, setOpen] = useState(false)
  const [query, setQuery] = useState('')
  const [results, setResults] = useState<PecContactResponse[]>([])
  const [loading, setLoading] = useState(false)
  const containerRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement>(null)
  const debouncedQuery = useDebounce(query, 250)

  // Chiudi il popover cliccando fuori
  useEffect(() => {
    if (!open) return
    const handler = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [open])

  // Focus sull'input quando si apre
  useEffect(() => {
    if (open) {
      setTimeout(() => inputRef.current?.focus(), 50)
    } else {
      setQuery('')
      setResults([])
    }
  }, [open])

  // Ricerca contatti
  const fetchContacts = useCallback(async (q: string) => {
    setLoading(true)
    try {
      if (q.trim().length >= 1) {
        const data = await contactsApi.autocomplete(q.trim())
        setResults(data)
      } else {
        // Senza query: mostra tutti (primi 20 ordinati per preferiti)
        const data = await contactsApi.list({ page_size: 20 })
        setResults(data.items)
      }
    } catch {
      setResults([])
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    if (open) {
      fetchContacts(debouncedQuery)
    }
  }, [debouncedQuery, open, fetchContacts])

  const handleSelect = (contact: PecContactResponse) => {
    onSelect(contact.email)
    setOpen(false)
  }

  const isSm = size === 'sm'

  return (
    <div ref={containerRef} className="relative flex-shrink-0">
      {/* Bottone apertura */}
      <button
        type="button"
        title="Seleziona dalla rubrica"
        onClick={() => setOpen((v) => !v)}
        className={`
          flex items-center justify-center rounded border border-input bg-background
          text-muted-foreground hover:text-primary hover:border-primary/60
          transition-colors
          ${isSm ? 'h-8 w-8' : 'h-10 w-10'}
          ${open ? 'border-primary/60 text-primary bg-primary/5' : ''}
        `}
      >
        <BookUser className={isSm ? 'h-3.5 w-3.5' : 'h-4 w-4'} />
      </button>

      {/* Popover */}
      {open && (
        <div
          className="absolute z-50 right-0 top-full mt-1 w-72 rounded-lg border bg-background shadow-lg overflow-hidden"
          style={{ minWidth: '260px' }}
        >
          {/* Campo ricerca */}
          <div className="flex items-center gap-2 px-3 py-2 border-b bg-muted/30">
            <Search className="h-3.5 w-3.5 text-muted-foreground flex-shrink-0" />
            <input
              ref={inputRef}
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Cerca nella rubrica..."
              className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
            />
          </div>

          {/* Lista risultati */}
          <div className="max-h-52 overflow-y-auto">
            {loading ? (
              <div className="px-3 py-4 text-center text-xs text-muted-foreground">
                Ricerca in corso...
              </div>
            ) : results.length === 0 ? (
              <div className="px-3 py-4 text-center text-xs text-muted-foreground">
                {query.trim() ? 'Nessun contatto trovato' : 'Rubrica vuota'}
              </div>
            ) : (
              results.map((contact) => (
                <button
                  key={contact.id}
                  type="button"
                  onClick={() => handleSelect(contact)}
                  className="w-full text-left px-3 py-2 hover:bg-muted/60 transition-colors flex items-start gap-2 group"
                >
                  <div className="mt-0.5 flex-shrink-0 h-6 w-6 rounded-full bg-primary/10 flex items-center justify-center">
                    {contact.is_favorite ? (
                      <Star className="h-3 w-3 text-amber-500 fill-amber-500" />
                    ) : (
                      <User className="h-3 w-3 text-primary/60" />
                    )}
                  </div>
                  <div className="min-w-0 flex-1">
                    {(contact.name || contact.organization) && (
                      <p className="text-xs font-medium text-foreground truncate">
                        {contact.name || contact.organization}
                      </p>
                    )}
                    <p className="text-xs text-muted-foreground truncate">
                      {contact.email}
                    </p>
                    {contact.name && contact.organization && (
                      <p className="text-xs text-muted-foreground/70 truncate">
                        {contact.organization}
                      </p>
                    )}
                  </div>
                </button>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  )
}
