import { type FormEvent, useState } from 'react'
import { FormModal } from './FormModal'
import type { BossBattle, Route } from '../../types/game'
import type { CreateBossBattleInput, UpdateBossBattleInput } from '../../types/admin'

interface BossBattleFormModalProps {
  boss?: BossBattle
  routes: Route[]
  nextOrder: number
  onSubmit: (data: CreateBossBattleInput | UpdateBossBattleInput) => void
  onClose: () => void
  isSubmitting?: boolean
  onDelete?: () => void
  isDeleting?: boolean
  onEditTeam?: () => void
}

const POKEMON_TYPES = [
  'normal', 'fire', 'water', 'electric', 'grass', 'ice',
  'fighting', 'poison', 'ground', 'flying', 'psychic', 'bug',
  'rock', 'ghost', 'dragon', 'dark', 'steel', 'fairy',
]

const BOSS_TYPES = [
  { value: 'gym_leader', label: 'Gym Leader' },
  { value: 'elite_four', label: 'Elite Four' },
  { value: 'champion', label: 'Champion' },
  { value: 'rival', label: 'Rival' },
  { value: 'evil_team', label: 'Evil Team' },
  { value: 'other', label: 'Other' },
]

export function BossBattleFormModal({
  boss,
  routes,
  nextOrder,
  onSubmit,
  onClose,
  isSubmitting,
  onDelete,
  isDeleting,
  onEditTeam,
}: BossBattleFormModalProps) {
  const [name, setName] = useState(boss?.name ?? '')
  const [bossType, setBossType] = useState(boss?.bossType ?? 'gym_leader')
  const [specialtyType, setSpecialtyType] = useState(boss?.specialtyType ?? '')
  const [badgeName, setBadgeName] = useState(boss?.badgeName ?? '')
  const [badgeImageUrl, setBadgeImageUrl] = useState(boss?.badgeImageUrl ?? '')
  const [levelCap, setLevelCap] = useState(String(boss?.levelCap ?? ''))
  const [order, setOrder] = useState(String(boss?.order ?? nextOrder))
  const [afterRouteId, setAfterRouteId] = useState(String(boss?.afterRouteId ?? ''))
  const [location, setLocation] = useState(boss?.location ?? '')
  const [section, setSection] = useState(boss?.section ?? '')
  const [spriteUrl, setSpriteUrl] = useState(boss?.spriteUrl ?? '')

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault()
    onSubmit({
      name,
      bossType,
      specialtyType: specialtyType || null,
      badgeName: badgeName || null,
      badgeImageUrl: badgeImageUrl || null,
      levelCap: Number(levelCap),
      order: Number(order),
      afterRouteId: afterRouteId ? Number(afterRouteId) : null,
      location,
      section: section || null,
      spriteUrl: spriteUrl || null,
    })
  }

  // Sort routes by order for the dropdown
  const sortedRoutes = [...routes].sort((a, b) => a.order - b.order)

  return (
    <FormModal
      title={boss ? 'Edit Boss Battle' : 'Add Boss Battle'}
      onClose={onClose}
      onSubmit={handleSubmit}
      isSubmitting={isSubmitting}
      onDelete={onDelete}
      isDeleting={isDeleting}
      headerExtra={onEditTeam ? (
        <button
          type="button"
          onClick={onEditTeam}
          className="text-sm text-blue-600 dark:text-blue-400 hover:underline"
        >
          Edit Team ({boss?.pokemon.length ?? 0})
        </button>
      ) : undefined}
    >
      <div className="grid grid-cols-3 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">Name</label>
          <input
            type="text"
            required
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="e.g. Brock"
            className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Type</label>
          <select
            value={bossType}
            onChange={(e) => setBossType(e.target.value as typeof bossType)}
            className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
          >
            {BOSS_TYPES.map((t) => (
              <option key={t.value} value={t.value}>
                {t.label}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Specialty</label>
          <select
            value={specialtyType}
            onChange={(e) => setSpecialtyType(e.target.value)}
            className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600 capitalize"
          >
            <option value="">None</option>
            {POKEMON_TYPES.map((t) => (
              <option key={t} value={t} className="capitalize">
                {t.charAt(0).toUpperCase() + t.slice(1)}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div>
        <label className="block text-sm font-medium mb-1">Location</label>
        <input
          type="text"
          required
          value={location}
          onChange={(e) => setLocation(e.target.value)}
          placeholder="e.g. Pewter City Gym"
          className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
        />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">Level Cap</label>
          <input
            type="number"
            required
            min={1}
            value={levelCap}
            onChange={(e) => setLevelCap(e.target.value)}
            className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Order</label>
          <input
            type="number"
            required
            min={1}
            value={order}
            onChange={(e) => setOrder(e.target.value)}
            className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
          />
        </div>
      </div>

      <div>
        <label className="block text-sm font-medium mb-1">Section</label>
        <input
          type="text"
          value={section}
          onChange={(e) => setSection(e.target.value)}
          placeholder="e.g. Main Story, Endgame"
          className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
        />
      </div>

      <div>
        <label className="block text-sm font-medium mb-1">Position After Route</label>
        <select
          value={afterRouteId}
          onChange={(e) => setAfterRouteId(e.target.value)}
          className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
        >
          <option value="">None</option>
          {sortedRoutes.map((r) => (
            <option key={r.id} value={r.id}>
              {r.order}. {r.name}
            </option>
          ))}
        </select>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">Badge Name</label>
          <input
            type="text"
            value={badgeName}
            onChange={(e) => setBadgeName(e.target.value)}
            placeholder="Optional"
            className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Badge Image URL</label>
          <input
            type="text"
            value={badgeImageUrl}
            onChange={(e) => setBadgeImageUrl(e.target.value)}
            placeholder="Optional"
            className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
          />
        </div>
      </div>

      <div>
        <label className="block text-sm font-medium mb-1">Sprite URL</label>
        <input
          type="text"
          value={spriteUrl}
          onChange={(e) => setSpriteUrl(e.target.value)}
          placeholder="Optional"
          className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
        />
      </div>
    </FormModal>
  )
}
