import { useState, useEffect, useMemo } from 'react';
import { X, Search, AlertCircle } from 'lucide-react';
import { Button, Input } from '@/shared/components/ui';

interface Condition {
  name: string;
  name_german: string;
  description: string;
  traits: string[];
  source: string;
}

interface ConditionsData {
  conditions: Condition[];
}

// Conditions that have a value/level
const VALUE_CONDITIONS = [
  'Clumsy',
  'Doomed',
  'Drained',
  'Dying',
  'Enfeebled',
  'Frightened',
  'Sickened',
  'Slowed',
  'Stunned',
  'Stupefied',
  'Wounded',
  'Persistent Damage',
];

interface AddConditionModalProps {
  onClose: () => void;
  onAdd: (condition: { name: string; nameGerman: string; value?: number }) => Promise<void>;
  existingConditions: string[];
}

export function AddConditionModal({ onClose, onAdd, existingConditions }: AddConditionModalProps) {
  const [conditions, setConditions] = useState<Condition[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCondition, setSelectedCondition] = useState<Condition | null>(null);
  const [value, setValue] = useState<number>(1);
  const [isLoading, setIsLoading] = useState(false);

  // Load conditions from JSON
  useEffect(() => {
    fetch('/pathfinder_conditions.json')
      .then((res) => res.json())
      .then((data: ConditionsData) => {
        setConditions(data.conditions);
      })
      .catch((err) => console.error('Failed to load conditions:', err));
  }, []);

  // Filter conditions based on search
  const filteredConditions = useMemo(() => {
    if (!searchQuery.trim()) return conditions;
    const query = searchQuery.toLowerCase();
    return conditions.filter(
      (c) =>
        c.name.toLowerCase().includes(query) ||
        c.name_german.toLowerCase().includes(query)
    );
  }, [conditions, searchQuery]);

  // Check if condition needs a value
  const needsValue = selectedCondition && VALUE_CONDITIONS.includes(selectedCondition.name);

  const handleAdd = async () => {
    if (!selectedCondition) return;
    setIsLoading(true);
    try {
      await onAdd({
        name: selectedCondition.name,
        nameGerman: selectedCondition.name_german,
        value: needsValue ? value : undefined,
      });
      onClose();
    } catch (error) {
      console.error('Failed to add condition:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const isAlreadyApplied = (conditionName: string) =>
    existingConditions.some((c) => c.toLowerCase() === conditionName.toLowerCase());

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/60" onClick={onClose} />

      {/* Modal */}
      <div className="relative w-full sm:max-w-lg max-h-[85vh] bg-bg-secondary rounded-t-2xl sm:rounded-2xl flex flex-col overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-border">
          <h2 className="text-lg font-semibold text-text-primary">Zustand hinzufügen</h2>
          <Button variant="ghost" size="icon" onClick={onClose}>
            <X className="h-5 w-5" />
          </Button>
        </div>

        {/* Search */}
        <div className="p-4 border-b border-border">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text-secondary" />
            <Input
              placeholder="Zustand suchen..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
              autoFocus
            />
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4">
          {selectedCondition ? (
            // Selected condition detail view
            <div className="space-y-4">
              <button
                onClick={() => setSelectedCondition(null)}
                className="text-sm text-primary-500 hover:text-primary-400"
              >
                &larr; Zurück zur Liste
              </button>

              <div className="p-4 rounded-xl bg-bg-tertiary">
                <div className="flex items-start gap-3">
                  <AlertCircle className="h-5 w-5 text-red-400 flex-shrink-0 mt-0.5" />
                  <div>
                    <h3 className="font-semibold text-text-primary">
                      {selectedCondition.name_german}
                    </h3>
                    <p className="text-sm text-text-secondary">{selectedCondition.name}</p>
                  </div>
                </div>
                <p className="mt-3 text-sm text-text-secondary leading-relaxed">
                  {selectedCondition.description}
                </p>
                {selectedCondition.traits.length > 0 && (
                  <div className="mt-3 flex flex-wrap gap-1">
                    {selectedCondition.traits.map((trait) => (
                      <span
                        key={trait}
                        className="px-2 py-0.5 text-xs rounded bg-primary-500/20 text-primary-400"
                      >
                        {trait}
                      </span>
                    ))}
                  </div>
                )}
              </div>

              {/* Value input for conditions with levels */}
              {needsValue && (
                <div className="space-y-2">
                  <label className="text-sm font-medium text-text-primary">
                    Stufe / Wert
                  </label>
                  <div className="flex items-center gap-3">
                    <Button
                      variant="outline"
                      size="icon"
                      onClick={() => setValue((v) => Math.max(1, v - 1))}
                      disabled={value <= 1}
                    >
                      -
                    </Button>
                    <span className="text-2xl font-bold text-text-primary w-12 text-center">
                      {value}
                    </span>
                    <Button
                      variant="outline"
                      size="icon"
                      onClick={() => setValue((v) => Math.min(10, v + 1))}
                      disabled={value >= 10}
                    >
                      +
                    </Button>
                  </div>
                </div>
              )}

              <Button
                className="w-full h-12"
                onClick={handleAdd}
                disabled={isLoading}
              >
                {isLoading ? 'Wird hinzugefügt...' : `${selectedCondition.name_german} hinzufügen`}
              </Button>
            </div>
          ) : (
            // Condition list
            <div className="space-y-2">
              {filteredConditions.length === 0 ? (
                <p className="text-center text-text-secondary py-8">
                  Keine Zustände gefunden
                </p>
              ) : (
                filteredConditions.map((condition) => {
                  const applied = isAlreadyApplied(condition.name);
                  return (
                    <button
                      key={condition.name}
                      onClick={() => !applied && setSelectedCondition(condition)}
                      disabled={applied}
                      className={`w-full text-left p-3 rounded-lg transition-colors ${
                        applied
                          ? 'bg-bg-tertiary/50 opacity-50 cursor-not-allowed'
                          : 'bg-bg-tertiary hover:bg-bg-elevated'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium text-text-primary">
                            {condition.name_german}
                          </p>
                          <p className="text-xs text-text-secondary">{condition.name}</p>
                        </div>
                        {applied && (
                          <span className="text-xs text-text-muted">Bereits aktiv</span>
                        )}
                        {VALUE_CONDITIONS.includes(condition.name) && !applied && (
                          <span className="text-xs text-primary-400">Hat Stufe</span>
                        )}
                      </div>
                    </button>
                  );
                })
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
