import { useState, useEffect } from 'react'
import { api } from '../api/client'
import type { Route, Pokemon } from '../types'

interface EggEncounterModalProps {
  routes: Route[]
  onSubmit: (data: {
    routeId: number
    pokemonId: number
    nickname?: string
    status: 'caught'
    catchLevel?: number
    origin: 'egg'
  }) => void
  onClose: () => void
  isPending: boolean
}

export function EggEncounterModal({
  routes,
  onSubmit,
  onClose,
  isPending,
}: EggEncounterModalProps) {
  const [selectedRouteId, setSelectedRouteId] = useState<number | null>(null)
  const [selectedPokemon, setSelectedPokemon] = useState<Pokemon | null>(null)
  const [nickname, setNickname] = useState('')
  const [catchLevel, setCatchLevel] = useState<string>('')
  const [search, setSearch] = useState('')
  const [searchResults, setSearchResults] = useState<Pokemon[]>([])
  const [isSearching, setIsSearching] = useState(false)

  // Only show leaf routes (no children)
  const parentIds = new Set(routes.filter(r => r.parentRouteId !== null).map(r => r.parentRouteId))
  const leafRoutes = routes.filter(r => !parentIds.has(r.id))

  // Debounced pokemon search
  useEffect(() => {
    if (search.length < 2) {
      setSearchResults([])
      return
    }

    const timer = setTimeout(async () => {
      setIsSearching(true)
      try {
        const data = await api.get<{ items: Pokemon[] }>(`/pokemon?search=${encodeURIComponent(search)}&limit=20`)
        setSearchResults(data.items)
      } catch {
        setSearchResults([])
      } finally {
        setIsSearching(false)
      }
    }, 300)

    return () => clearTimeout(timer)
  }, [search])

  const handleSubmit = () => {
    if (selectedPokemon && selectedRouteId) {
      onSubmit({
        routeId: selectedRouteId,
        pokemonId: selectedPokemon.id,
        nickname: nickname || undefined,
        status: 'caught',
        catchLevel: catchLevel ? Number(catchLevel) : undefined,
        origin: 'egg',
      })
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="fixed inset-0 bg-black/50" onClick={onClose} />
      <div className="relative bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-lg w-full max-h-[90vh] overflow-y-auto">
        <div className="sticky top-0 bg-white dark:bg-gray-800 border-b border-green-300 dark:border-green-600 px-6 py-4 rounded-t-xl">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2">
              <span className="text-green-500">&#x1F95A;</span>
              Log Egg Hatch
            </h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
            >
              <svg
                className="w-5 h-5"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
          </div>
          <p className="text-sm text-green-600 dark:text-green-400 mt-1">
            Egg hatches bypass the one-per-route rule
          </p>
        </div>

        <div className="px-6 py-4 space-y-4">
          {/* Route selector */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Hatch Location
            </label>
            <select
              value={selectedRouteId ?? ''}
              onChange={(e) => setSelectedRouteId(Number(e.target.value))}
              className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-green-500"
            >
              <option value="">Select a location...</option>
              {leafRoutes.map((r) => (
                <option key={r.id} value={r.id}>
                  {r.name}
                </option>
              ))}
            </select>
          </div>

          {/* Pokemon search */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Pokemon
            </label>
            {selectedPokemon ? (
              <div className="flex items-center gap-3 p-3 rounded-lg border border-green-300 dark:border-green-600 bg-green-50 dark:bg-green-900/20">
                {selectedPokemon.spriteUrl ? (
                  <img
                    src={selectedPokemon.spriteUrl}
                    alt={selectedPokemon.name}
                    className="w-10 h-10"
                  />
                ) : (
                  <div className="w-10 h-10 rounded-full bg-gray-200 dark:bg-gray-600 flex items-center justify-center text-xs font-bold">
                    {selectedPokemon.name[0].toUpperCase()}
                  </div>
                )}
                <span className="font-medium text-gray-900 dark:text-gray-100 capitalize">
                  {selectedPokemon.name}
                </span>
                <button
                  onClick={() => {
                    setSelectedPokemon(null)
                    setSearch('')
                    setSearchResults([])
                  }}
                  className="ml-auto text-sm text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
                >
                  Change
                </button>
              </div>
            ) : (
              <>
                <input
                  type="text"
                  placeholder="Search pokemon by name..."
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-green-500"
                />
                {isSearching && (
                  <div className="flex items-center justify-center py-4">
                    <div className="w-6 h-6 border-2 border-green-500 border-t-transparent rounded-full animate-spin" />
                  </div>
                )}
                {searchResults.length > 0 && (
                  <div className="mt-2 max-h-64 overflow-y-auto grid grid-cols-3 gap-2">
                    {searchResults.map((p) => (
                      <button
                        key={p.id}
                        type="button"
                        onClick={() => setSelectedPokemon(p)}
                        className="flex flex-col items-center p-2 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-green-400 dark:hover:border-green-600 text-center transition-colors"
                      >
                        {p.spriteUrl ? (
                          <img
                            src={p.spriteUrl}
                            alt={p.name}
                            className="w-10 h-10"
                          />
                        ) : (
                          <div className="w-10 h-10 rounded-full bg-gray-200 dark:bg-gray-600 flex items-center justify-center text-xs font-bold">
                            {p.name[0].toUpperCase()}
                          </div>
                        )}
                        <span className="text-xs text-gray-700 dark:text-gray-300 mt-1 capitalize">
                          {p.name}
                        </span>
                      </button>
                    ))}
                  </div>
                )}
                {search.length >= 2 && !isSearching && searchResults.length === 0 && (
                  <p className="text-sm text-gray-500 dark:text-gray-400 py-2">
                    No pokemon found
                  </p>
                )}
              </>
            )}
          </div>

          {/* Nickname */}
          {selectedPokemon && (
            <div>
              <label
                htmlFor="egg-nickname"
                className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >
                Nickname
              </label>
              <input
                id="egg-nickname"
                type="text"
                value={nickname}
                onChange={(e) => setNickname(e.target.value)}
                placeholder="Give it a name..."
                className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-green-500"
              />
            </div>
          )}

          {/* Hatch Level */}
          {selectedPokemon && (
            <div>
              <label
                htmlFor="egg-catch-level"
                className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >
                Hatch Level
              </label>
              <input
                id="egg-catch-level"
                type="number"
                min={1}
                max={100}
                value={catchLevel}
                onChange={(e) => setCatchLevel(e.target.value)}
                placeholder="1"
                className="w-24 px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-green-500"
              />
            </div>
          )}
        </div>

        <div className="sticky bottom-0 bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 px-6 py-4 rounded-b-xl flex justify-end gap-3">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg font-medium hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
          >
            Cancel
          </button>
          <button
            type="button"
            disabled={!selectedPokemon || !selectedRouteId || isPending}
            onClick={handleSubmit}
            className="px-4 py-2 bg-green-500 text-white rounded-lg font-medium hover:bg-green-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {isPending ? 'Saving...' : 'Log Egg Hatch'}
          </button>
        </div>
      </div>
    </div>
  )
}
