import { useState } from 'react';
import { X, Plus, Trash2 } from 'lucide-react';
import { cn } from '@/shared/lib/utils';

interface CombatantAbility {
  name: string;
  actionCost: number;
  actionType: 'ACTION' | 'REACTION' | 'FREE';
  description: string;
  damage?: string;
  traits?: string[];
}

interface CreateCombatantModalProps {
  onClose: () => void;
  onCreate: (data: {
    name: string;
    type: 'NPC' | 'MONSTER';
    level: number;
    hpMax: number;
    ac: number;
    fortitude: number;
    reflex: number;
    will: number;
    perception: number;
    speed: number;
    description?: string;
    abilities: CombatantAbility[];
  }) => void;
  isLoading?: boolean;
}

export function CreateCombatantModal({ onClose, onCreate, isLoading }: CreateCombatantModalProps) {
  const [name, setName] = useState('');
  const [type, setType] = useState<'NPC' | 'MONSTER'>('NPC');
  const [level, setLevel] = useState(1);
  const [hpMax, setHpMax] = useState(20);
  const [ac, setAc] = useState(15);
  const [fortitude, setFortitude] = useState(5);
  const [reflex, setReflex] = useState(5);
  const [will, setWill] = useState(5);
  const [perception, setPerception] = useState(5);
  const [speed, setSpeed] = useState(25);
  const [description, setDescription] = useState('');
  const [abilities, setAbilities] = useState<CombatantAbility[]>([]);
  const [showAddAbility, setShowAddAbility] = useState(false);

  // Ability form state
  const [abilityName, setAbilityName] = useState('');
  const [abilityActionCost, setAbilityActionCost] = useState(1);
  const [abilityActionType, setAbilityActionType] = useState<'ACTION' | 'REACTION' | 'FREE'>('ACTION');
  const [abilityDescription, setAbilityDescription] = useState('');
  const [abilityDamage, setAbilityDamage] = useState('');

  const handleAddAbility = () => {
    if (!abilityName.trim() || !abilityDescription.trim()) return;

    setAbilities([
      ...abilities,
      {
        name: abilityName.trim(),
        actionCost: abilityActionCost,
        actionType: abilityActionType,
        description: abilityDescription.trim(),
        damage: abilityDamage.trim() || undefined,
      },
    ]);

    // Reset ability form
    setAbilityName('');
    setAbilityActionCost(1);
    setAbilityActionType('ACTION');
    setAbilityDescription('');
    setAbilityDamage('');
    setShowAddAbility(false);
  };

  const handleRemoveAbility = (index: number) => {
    setAbilities(abilities.filter((_, i) => i !== index));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;

    onCreate({
      name: name.trim(),
      type,
      level,
      hpMax,
      ac,
      fortitude,
      reflex,
      will,
      perception,
      speed,
      description: description.trim() || undefined,
      abilities,
    });
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70">
      <div className="bg-bg-secondary border border-border-default rounded-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-border-default sticky top-0 bg-bg-secondary z-10">
          <h2 className="text-lg font-semibold text-text-primary">NPC/Monster erstellen</h2>
          <button
            onClick={onClose}
            className="p-1 rounded-lg hover:bg-white/10 text-text-secondary transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-4 space-y-4">
          {/* Basic Info */}
          <div className="grid grid-cols-2 gap-4">
            <div className="col-span-2 sm:col-span-1">
              <label className="block text-sm font-medium text-text-secondary mb-2">Name</label>
              <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="z.B. Goblin Krieger"
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary placeholder:text-text-secondary focus:outline-none focus:border-primary"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">Typ</label>
              <select
                value={type}
                onChange={(e) => setType(e.target.value as 'NPC' | 'MONSTER')}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              >
                <option value="NPC">NPC</option>
                <option value="MONSTER">Monster</option>
              </select>
            </div>
          </div>

          {/* Stats Row 1 */}
          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">Level</label>
              <input
                type="number"
                value={level}
                onChange={(e) => setLevel(parseInt(e.target.value) || 0)}
                min={-1}
                max={30}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">HP</label>
              <input
                type="number"
                value={hpMax}
                onChange={(e) => setHpMax(parseInt(e.target.value) || 1)}
                min={1}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">RK</label>
              <input
                type="number"
                value={ac}
                onChange={(e) => setAc(parseInt(e.target.value) || 0)}
                min={0}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
          </div>

          {/* Saves */}
          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">Zähigkeit</label>
              <input
                type="number"
                value={fortitude}
                onChange={(e) => setFortitude(parseInt(e.target.value) || 0)}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">Reflex</label>
              <input
                type="number"
                value={reflex}
                onChange={(e) => setReflex(parseInt(e.target.value) || 0)}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">Wille</label>
              <input
                type="number"
                value={will}
                onChange={(e) => setWill(parseInt(e.target.value) || 0)}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
          </div>

          {/* Perception & Speed */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">Wahrnehmung</label>
              <input
                type="number"
                value={perception}
                onChange={(e) => setPerception(parseInt(e.target.value) || 0)}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">Geschwindigkeit (ft)</label>
              <input
                type="number"
                value={speed}
                onChange={(e) => setSpeed(parseInt(e.target.value) || 0)}
                min={0}
                step={5}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
          </div>

          {/* Description */}
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-2">Beschreibung (optional)</label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Notizen, Taktiken, besondere Merkmale..."
              rows={2}
              className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary placeholder:text-text-secondary focus:outline-none focus:border-primary resize-none"
            />
          </div>

          {/* Abilities */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="text-sm font-medium text-text-secondary">Fähigkeiten</label>
              <button
                type="button"
                onClick={() => setShowAddAbility(!showAddAbility)}
                className="text-sm text-primary hover:text-primary/80 flex items-center gap-1"
              >
                <Plus className="w-4 h-4" />
                Hinzufügen
              </button>
            </div>

            {/* Add Ability Form */}
            {showAddAbility && (
              <div className="p-3 bg-bg-tertiary rounded-lg space-y-3 mb-3">
                <div className="grid grid-cols-2 gap-3">
                  <input
                    type="text"
                    value={abilityName}
                    onChange={(e) => setAbilityName(e.target.value)}
                    placeholder="Name (z.B. Schwerthieb)"
                    className="px-3 py-2 bg-bg-secondary border border-border-default rounded-lg text-text-primary text-sm focus:outline-none focus:border-primary"
                  />
                  <div className="flex gap-2">
                    <select
                      value={abilityActionCost}
                      onChange={(e) => setAbilityActionCost(parseInt(e.target.value))}
                      className="flex-1 px-2 py-2 bg-bg-secondary border border-border-default rounded-lg text-text-primary text-sm focus:outline-none focus:border-primary"
                    >
                      <option value={0}>0</option>
                      <option value={1}>1</option>
                      <option value={2}>2</option>
                      <option value={3}>3</option>
                    </select>
                    <select
                      value={abilityActionType}
                      onChange={(e) => setAbilityActionType(e.target.value as 'ACTION' | 'REACTION' | 'FREE')}
                      className="flex-1 px-2 py-2 bg-bg-secondary border border-border-default rounded-lg text-text-primary text-sm focus:outline-none focus:border-primary"
                    >
                      <option value="ACTION">Aktion</option>
                      <option value="REACTION">Reaktion</option>
                      <option value="FREE">Frei</option>
                    </select>
                  </div>
                </div>
                <input
                  type="text"
                  value={abilityDamage}
                  onChange={(e) => setAbilityDamage(e.target.value)}
                  placeholder="Schaden (z.B. 1d8+4 Hieb)"
                  className="w-full px-3 py-2 bg-bg-secondary border border-border-default rounded-lg text-text-primary text-sm focus:outline-none focus:border-primary"
                />
                <textarea
                  value={abilityDescription}
                  onChange={(e) => setAbilityDescription(e.target.value)}
                  placeholder="Beschreibung..."
                  rows={2}
                  className="w-full px-3 py-2 bg-bg-secondary border border-border-default rounded-lg text-text-primary text-sm focus:outline-none focus:border-primary resize-none"
                />
                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={() => setShowAddAbility(false)}
                    className="flex-1 px-3 py-1.5 bg-bg-secondary text-text-secondary rounded-lg text-sm hover:bg-white/10"
                  >
                    Abbrechen
                  </button>
                  <button
                    type="button"
                    onClick={handleAddAbility}
                    disabled={!abilityName.trim() || !abilityDescription.trim()}
                    className="flex-1 px-3 py-1.5 bg-primary text-white rounded-lg text-sm hover:bg-primary/80 disabled:opacity-50"
                  >
                    Hinzufügen
                  </button>
                </div>
              </div>
            )}

            {/* Ability List */}
            {abilities.length > 0 ? (
              <div className="space-y-2">
                {abilities.map((ability, index) => (
                  <div
                    key={index}
                    className="flex items-start justify-between gap-2 p-2 bg-bg-tertiary rounded-lg"
                  >
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="font-medium text-text-primary text-sm">{ability.name}</span>
                        <span className="text-xs px-1.5 py-0.5 bg-primary/20 text-primary rounded">
                          {ability.actionCost > 0 ? `${ability.actionCost} Aktion${ability.actionCost > 1 ? 'en' : ''}` : ability.actionType === 'REACTION' ? 'Reaktion' : 'Frei'}
                        </span>
                      </div>
                      {ability.damage && (
                        <p className="text-xs text-red-400 mt-0.5">{ability.damage}</p>
                      )}
                      <p className="text-xs text-text-secondary mt-0.5 line-clamp-2">{ability.description}</p>
                    </div>
                    <button
                      type="button"
                      onClick={() => handleRemoveAbility(index)}
                      className="p-1 text-text-secondary hover:text-red-400"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-sm text-text-secondary text-center py-4 bg-bg-tertiary rounded-lg">
                Keine Fähigkeiten hinzugefügt
              </p>
            )}
          </div>

          {/* Actions */}
          <div className="flex gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-4 py-2 bg-bg-tertiary text-text-primary rounded-lg hover:bg-white/10 transition-colors"
            >
              Abbrechen
            </button>
            <button
              type="submit"
              disabled={!name.trim() || isLoading}
              className={cn(
                'flex-1 px-4 py-2 rounded-lg font-medium transition-colors',
                name.trim() && !isLoading
                  ? 'bg-primary text-white hover:bg-primary/80'
                  : 'bg-primary/50 text-white/50 cursor-not-allowed'
              )}
            >
              {isLoading ? 'Erstellen...' : 'Erstellen'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
