/**
 * Person Selector Component
 *
 * Dropdown to select a person with relationship info
 */

import { useState, useEffect } from 'react'
import { useQuery } from '@tanstack/react-query'
import { ChevronDown, Plus, Search } from 'lucide-react'
import { api } from '../../lib/api'

interface Person {
  id: number
  name: string
  sort_name?: string | null
  relationship_id: number
  relationship: {
    id: number
    name: string
    color: string
  }
  default_tag_ids: number[]
}

interface PersonSelectorProps {
  value?: number
  onChange: (personId: number | undefined, person?: Person) => void
  placeholder?: string
  required?: boolean
  className?: string
  onCreateNew?: () => void
}

export function PersonSelector({
  value,
  onChange,
  placeholder = 'Select a person',
  required = false,
  className = '',
  onCreateNew,
}: PersonSelectorProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [search, setSearch] = useState('')

  const { data: persons = [], isLoading } = useQuery({
    queryKey: ['private-gallery-persons'],
    queryFn: () => api.privateGallery.getPersons(),
  })

  // Find selected person
  const selectedPerson = persons.find(p => p.id === value)

  // Filter persons by search
  const filteredPersons = persons.filter(p =>
    p.name.toLowerCase().includes(search.toLowerCase()) ||
    (p.sort_name && p.sort_name.toLowerCase().includes(search.toLowerCase()))
  )

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      const target = e.target as HTMLElement
      if (!target.closest('.person-selector')) {
        setIsOpen(false)
      }
    }

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside)
      return () => document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [isOpen])

  return (
    <div className={`relative person-selector ${className}`}>
      {/* Trigger Button */}
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className={`w-full px-4 py-2.5 rounded-lg border bg-background text-left flex items-center justify-between gap-2 transition-colors ${
          isOpen
            ? 'border-primary ring-2 ring-primary/20'
            : 'border-border hover:border-primary/50'
        }`}
      >
        {selectedPerson ? (
          <div className="flex items-center gap-2 overflow-hidden">
            <div
              className="w-3 h-3 rounded-full flex-shrink-0"
              style={{ backgroundColor: selectedPerson.relationship.color }}
            />
            <span className="truncate">{selectedPerson.name}</span>
            <span className="text-xs text-muted-foreground">
              ({selectedPerson.relationship.name})
            </span>
          </div>
        ) : (
          <span className="text-muted-foreground">{placeholder}</span>
        )}
        <ChevronDown className={`w-4 h-4 text-muted-foreground transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {/* Dropdown */}
      {isOpen && (
        <div className="absolute z-50 mt-1 w-full bg-popover rounded-lg shadow-lg border border-border overflow-hidden">
          {/* Search */}
          <div className="p-2 border-b border-border">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search persons..."
                className="w-full pl-9 pr-4 py-2 text-sm rounded-md border border-border bg-background focus:outline-none focus:ring-2 focus:ring-primary"
                autoFocus
              />
            </div>
          </div>

          {/* Options */}
          <div className="max-h-64 overflow-y-auto">
            {isLoading ? (
              <div className="p-4 text-center text-muted-foreground">Loading...</div>
            ) : filteredPersons.length === 0 ? (
              <div className="p-4 text-center text-muted-foreground">
                {search ? 'No persons found' : 'No persons yet'}
              </div>
            ) : (
              filteredPersons.map((person) => (
                <button
                  key={person.id}
                  type="button"
                  onClick={() => {
                    onChange(person.id, person)
                    setIsOpen(false)
                    setSearch('')
                  }}
                  className={`w-full px-4 py-2.5 text-left flex items-center gap-3 hover:bg-secondary transition-colors ${
                    person.id === value ? 'bg-primary/10' : ''
                  }`}
                >
                  <div
                    className="w-3 h-3 rounded-full flex-shrink-0"
                    style={{ backgroundColor: person.relationship.color }}
                  />
                  <div className="flex-1 overflow-hidden">
                    <div className="truncate font-medium">{person.name}</div>
                    <div className="text-xs text-muted-foreground truncate">
                      {person.relationship.name}
                      {person.sort_name && ` • ${person.sort_name}`}
                    </div>
                  </div>
                </button>
              ))
            )}
          </div>

          {/* Create New Option */}
          {onCreateNew && (
            <div className="p-2 border-t border-border">
              <button
                type="button"
                onClick={() => {
                  setIsOpen(false)
                  onCreateNew()
                }}
                className="w-full px-4 py-2 rounded-md text-sm text-primary hover:bg-primary/10 flex items-center gap-2 transition-colors"
              >
                <Plus className="w-4 h-4" />
                Add New Person
              </button>
            </div>
          )}

          {/* Clear Option */}
          {!required && value && (
            <div className="p-2 border-t border-border">
              <button
                type="button"
                onClick={() => {
                  onChange(undefined)
                  setIsOpen(false)
                }}
                className="w-full px-4 py-2 rounded-md text-sm text-muted-foreground hover:bg-secondary flex items-center gap-2 transition-colors"
              >
                Clear Selection
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  )
}

export default PersonSelector
