import { type FormEvent, useState } from 'react'
import { PokemonSelector } from './PokemonSelector'
import type { BossBattle } from '../../types/game'
import type { BossPokemonInput } from '../../types/admin'

interface BossTeamEditorProps {
  boss: BossBattle
  onSave: (team: BossPokemonInput[]) => void
  onClose: () => void
  isSaving?: boolean
}

interface PokemonSlot {
  pokemonId: number | null
  pokemonName: string
  level: string
  order: number
}

interface Variant {
  label: string | null
  pokemon: PokemonSlot[]
}

function groupByVariant(boss: BossBattle): Variant[] {
  const sorted = [...boss.pokemon].sort((a, b) => a.order - b.order)
  const map = new Map<string | null, PokemonSlot[]>()

  for (const bp of sorted) {
    const key = bp.conditionLabel
    if (!map.has(key)) map.set(key, [])
    map.get(key)!.push({
      pokemonId: bp.pokemonId,
      pokemonName: bp.pokemon.name,
      level: String(bp.level),
      order: bp.order,
    })
  }

  if (map.size === 0) {
    return [{ label: null, pokemon: [{ pokemonId: null, pokemonName: '', level: '', order: 1 }] }]
  }

  const variants: Variant[] = []
  // null (default) first
  if (map.has(null)) {
    variants.push({ label: null, pokemon: map.get(null)! })
    map.delete(null)
  }
  // Then alphabetical
  const remaining = [...map.entries()].sort((a, b) => (a[0] ?? '').localeCompare(b[0] ?? ''))
  for (const [label, pokemon] of remaining) {
    variants.push({ label, pokemon })
  }
  return variants
}

export function BossTeamEditor({ boss, onSave, onClose, isSaving }: BossTeamEditorProps) {
  const [variants, setVariants] = useState<Variant[]>(() => groupByVariant(boss))
  const [activeTab, setActiveTab] = useState(0)
  const [newVariantName, setNewVariantName] = useState('')
  const [showAddVariant, setShowAddVariant] = useState(false)

  const activeVariant = variants[activeTab] ?? variants[0]

  const updateVariant = (tabIndex: number, updater: (v: Variant) => Variant) => {
    setVariants((prev) => prev.map((v, i) => (i === tabIndex ? updater(v) : v)))
  }

  const addSlot = () => {
    updateVariant(activeTab, (v) => ({
      ...v,
      pokemon: [...v.pokemon, { pokemonId: null, pokemonName: '', level: '', order: v.pokemon.length + 1 }],
    }))
  }

  const removeSlot = (index: number) => {
    updateVariant(activeTab, (v) => ({
      ...v,
      pokemon: v.pokemon.filter((_, i) => i !== index).map((item, i) => ({ ...item, order: i + 1 })),
    }))
  }

  const updateSlot = (index: number, field: string, value: number | string | null) => {
    updateVariant(activeTab, (v) => ({
      ...v,
      pokemon: v.pokemon.map((item, i) => (i === index ? { ...item, [field]: value } : item)),
    }))
  }

  const addVariant = () => {
    const name = newVariantName.trim()
    if (!name) return
    if (variants.some((v) => v.label === name)) return
    setVariants((prev) => [...prev, { label: name, pokemon: [{ pokemonId: null, pokemonName: '', level: '', order: 1 }] }])
    setActiveTab(variants.length)
    setNewVariantName('')
    setShowAddVariant(false)
  }

  const removeVariant = (tabIndex: number) => {
    if (variants[tabIndex].label === null) return
    if (!window.confirm(`Remove variant "${variants[tabIndex].label}"?`)) return
    setVariants((prev) => prev.filter((_, i) => i !== tabIndex))
    setActiveTab((prev) => Math.min(prev, variants.length - 2))
  }

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault()
    const allPokemon: BossPokemonInput[] = []
    for (const variant of variants) {
      const conditionLabel = variants.length === 1 && variant.label === null ? null : variant.label
      const validPokemon = variant.pokemon.filter((t) => t.pokemonId != null && t.level)
      for (let i = 0; i < validPokemon.length; i++) {
        allPokemon.push({
          pokemonId: validPokemon[i].pokemonId!,
          level: Number(validPokemon[i].level),
          order: i + 1,
          conditionLabel,
        })
      }
    }
    onSave(allPokemon)
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="fixed inset-0 bg-black/50" onClick={onClose} />
      <div className="relative bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-lg w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-lg font-semibold">{boss.name}'s Team</h2>
        </div>

        {/* Variant tabs */}
        <div className="px-6 pt-3 flex items-center gap-1 flex-wrap border-b border-gray-200 dark:border-gray-700">
          {variants.map((v, i) => (
            <button
              key={v.label ?? '__default'}
              type="button"
              onClick={() => setActiveTab(i)}
              className={`px-3 py-1.5 text-sm font-medium rounded-t-md border border-b-0 transition-colors ${
                activeTab === i
                  ? 'bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 text-gray-900 dark:text-gray-100'
                  : 'bg-gray-50 dark:bg-gray-700 border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
              }`}
            >
              {v.label ?? 'Default'}
              {v.label !== null && (
                <span
                  onClick={(e) => { e.stopPropagation(); removeVariant(i) }}
                  className="ml-1.5 text-gray-400 hover:text-red-500 cursor-pointer"
                  title="Remove variant"
                >
                  &#10005;
                </span>
              )}
            </button>
          ))}
          {!showAddVariant ? (
            <button
              type="button"
              onClick={() => setShowAddVariant(true)}
              className="px-2 py-1.5 text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
              title="Add variant"
            >
              +
            </button>
          ) : (
            <div className="flex items-center gap-1 pb-1">
              <input
                type="text"
                value={newVariantName}
                onChange={(e) => setNewVariantName(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addVariant() } if (e.key === 'Escape') setShowAddVariant(false) }}
                placeholder="Variant name..."
                className="px-2 py-1 text-sm border rounded dark:bg-gray-700 dark:border-gray-600 w-40"
                autoFocus
              />
              <button type="button" onClick={addVariant} className="px-2 py-1 text-sm text-blue-600 dark:text-blue-400">Add</button>
              <button type="button" onClick={() => setShowAddVariant(false)} className="px-1 py-1 text-sm text-gray-400">&#10005;</button>
            </div>
          )}
        </div>

        <form onSubmit={handleSubmit}>
          <div className="px-6 py-4 space-y-3">
            {activeVariant.pokemon.map((slot, index) => (
              <div key={`${activeTab}-${index}`} className="flex items-end gap-2">
                <div className="flex-1">
                  <PokemonSelector
                    label={`Pokemon ${index + 1}`}
                    selectedId={slot.pokemonId}
                    initialName={slot.pokemonName}
                    onChange={(id) => updateSlot(index, 'pokemonId', id)}
                  />
                </div>
                <div className="w-20">
                  <label className="block text-sm font-medium mb-1">Level</label>
                  <input
                    type="number"
                    min={1}
                    max={100}
                    value={slot.level}
                    onChange={(e) => updateSlot(index, 'level', e.target.value)}
                    className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
                  />
                </div>
                <button
                  type="button"
                  onClick={() => removeSlot(index)}
                  className="px-2 py-2 text-red-500 hover:text-red-700 text-sm"
                  title="Remove"
                >
                  &#10005;
                </button>
              </div>
            ))}

            {activeVariant.pokemon.length < 6 && (
              <button
                type="button"
                onClick={addSlot}
                className="w-full py-2 text-sm text-blue-600 dark:text-blue-400 border border-dashed border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-50 dark:hover:bg-gray-700"
              >
                + Add Pokemon
              </button>
            )}
          </div>

          <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium rounded-md border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isSaving}
              className="px-4 py-2 text-sm font-medium rounded-md bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
            >
              {isSaving ? 'Saving...' : 'Save Team'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
