import { useState } from 'react';
import { X, Skull, Heart, Check, AlertTriangle } from 'lucide-react';
import { Button } from '@/shared/components/ui';

type OutcomeType = 'critical_success' | 'success' | 'failure' | 'critical_failure';

interface RecoveryCheckResult {
  result: OutcomeType;
  dieRoll: number;
  dc: number;
  newDyingValue: number;
  stabilized: boolean;
  died: boolean;
  message: string;
  woundedAdded: boolean;
}

interface RecoveryCheckModalProps {
  dyingValue: number;
  doomedValue: number;
  onClose: () => void;
  onRoll: (dieRoll: number) => Promise<RecoveryCheckResult>;
}

export function RecoveryCheckModal({
  dyingValue,
  doomedValue,
  onClose,
  onRoll,
}: RecoveryCheckModalProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [result, setResult] = useState<RecoveryCheckResult | null>(null);

  const dc = 10 + dyingValue;
  const deathThreshold = 4 - doomedValue;

  // Map outcome to a fake die roll that produces that outcome
  const getSimulatedRoll = (outcome: OutcomeType): number => {
    switch (outcome) {
      case 'critical_success':
        return 20; // Natural 20 = crit success
      case 'success':
        return dc; // Exactly DC = success
      case 'failure':
        return dc - 1; // Below DC = failure
      case 'critical_failure':
        return 1; // Natural 1 = crit failure
    }
  };

  const handleOutcome = async (outcome: OutcomeType) => {
    setIsSubmitting(true);

    try {
      const simulatedRoll = getSimulatedRoll(outcome);
      const res = await onRoll(simulatedRoll);
      setResult(res);
    } catch (error) {
      console.error('Recovery check failed:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const getResultColor = (res: OutcomeType) => {
    switch (res) {
      case 'critical_success':
        return 'text-green-400';
      case 'success':
        return 'text-blue-400';
      case 'failure':
        return 'text-orange-400';
      case 'critical_failure':
        return 'text-red-400';
    }
  };

  const getResultName = (res: OutcomeType) => {
    switch (res) {
      case 'critical_success':
        return 'Kritischer Erfolg!';
      case 'success':
        return 'Erfolg!';
      case 'failure':
        return 'Fehlschlag!';
      case 'critical_failure':
        return 'Kritischer Fehlschlag!';
    }
  };

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

      {/* Modal */}
      <div className="relative w-full max-w-sm mx-4 bg-bg-secondary rounded-2xl overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-border bg-red-500/10">
          <div className="flex items-center gap-2">
            <Skull className="h-5 w-5 text-red-400" />
            <h2 className="text-lg font-semibold text-red-400">Genesungswurf</h2>
          </div>
          <Button variant="ghost" size="icon" onClick={onClose}>
            <X className="h-5 w-5" />
          </Button>
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          {/* Dying Status */}
          <div className="flex items-center justify-between p-3 rounded-lg bg-bg-tertiary">
            <div className="flex items-center gap-2">
              <Skull className="h-5 w-5 text-orange-400" />
              <span className="font-medium text-text-primary">Sterbend {dyingValue}</span>
            </div>
            <div className="flex items-center gap-1">
              {Array.from({ length: deathThreshold }).map((_, i) => (
                <div
                  key={i}
                  className={`w-3 h-3 rounded-full border ${
                    i < dyingValue
                      ? 'bg-red-500 border-red-400'
                      : 'bg-transparent border-gray-500'
                  }`}
                />
              ))}
            </div>
          </div>

          {/* DC Display */}
          <div className="text-center py-2">
            <p className="text-sm text-text-secondary">Schwierigkeitsgrad</p>
            <p className="text-5xl font-bold text-text-primary">{dc}</p>
          </div>

          {/* Result Display */}
          {result && (
            <div
              className={`p-4 rounded-lg ${
                result.died
                  ? 'bg-red-500/20 border border-red-500/50'
                  : result.stabilized
                    ? 'bg-green-500/20 border border-green-500/50'
                    : result.result === 'failure' || result.result === 'critical_failure'
                      ? 'bg-orange-500/20 border border-orange-500/50'
                      : 'bg-blue-500/20 border border-blue-500/50'
              }`}
            >
              <div className="flex items-center justify-center gap-2 mb-2">
                {result.died ? (
                  <Skull className="h-6 w-6 text-red-400" />
                ) : result.stabilized ? (
                  <Heart className="h-6 w-6 text-green-400" />
                ) : result.result === 'critical_success' || result.result === 'success' ? (
                  <Check className="h-6 w-6" />
                ) : (
                  <AlertTriangle className="h-6 w-6" />
                )}
                <span className={`font-bold text-lg ${getResultColor(result.result)}`}>
                  {getResultName(result.result)}
                </span>
              </div>
              <p className="text-sm text-text-primary text-center">{result.message}</p>
              {result.woundedAdded && !result.died && (
                <p className="text-xs text-yellow-400 mt-2 flex items-center justify-center gap-1">
                  <Heart className="h-3 w-3" />
                  Verwundet hinzugefugt
                </p>
              )}
            </div>
          )}

          {/* Outcome Buttons - Only show if no result yet */}
          {!result && (
            <div className="space-y-3">
              <p className="text-sm text-text-secondary text-center">Ergebnis des Wurfs:</p>

              {/* Success buttons */}
              <div className="grid grid-cols-2 gap-3">
                <button
                  onClick={() => handleOutcome('critical_success')}
                  disabled={isSubmitting}
                  className="py-4 rounded-xl bg-green-500/20 hover:bg-green-500/30 border border-green-500/50 text-green-400 font-semibold transition-colors disabled:opacity-50 flex flex-col items-center gap-1"
                >
                  <Check className="h-6 w-6" />
                  <span>Krit. Erfolg</span>
                  <span className="text-xs opacity-70">Sterbend -2</span>
                </button>
                <button
                  onClick={() => handleOutcome('success')}
                  disabled={isSubmitting}
                  className="py-4 rounded-xl bg-blue-500/20 hover:bg-blue-500/30 border border-blue-500/50 text-blue-400 font-semibold transition-colors disabled:opacity-50 flex flex-col items-center gap-1"
                >
                  <Check className="h-5 w-5" />
                  <span>Erfolg</span>
                  <span className="text-xs opacity-70">Sterbend -1</span>
                </button>
              </div>

              {/* Failure buttons */}
              <div className="grid grid-cols-2 gap-3">
                <button
                  onClick={() => handleOutcome('failure')}
                  disabled={isSubmitting}
                  className="py-4 rounded-xl bg-orange-500/20 hover:bg-orange-500/30 border border-orange-500/50 text-orange-400 font-semibold transition-colors disabled:opacity-50 flex flex-col items-center gap-1"
                >
                  <AlertTriangle className="h-5 w-5" />
                  <span>Fehlschlag</span>
                  <span className="text-xs opacity-70">Sterbend +1</span>
                </button>
                <button
                  onClick={() => handleOutcome('critical_failure')}
                  disabled={isSubmitting}
                  className="py-4 rounded-xl bg-red-500/20 hover:bg-red-500/30 border border-red-500/50 text-red-400 font-semibold transition-colors disabled:opacity-50 flex flex-col items-center gap-1"
                >
                  <Skull className="h-6 w-6" />
                  <span>Krit. Fehlschlag</span>
                  <span className="text-xs opacity-70">Sterbend +2</span>
                </button>
              </div>
            </div>
          )}

          {/* Close Button (after result) */}
          {result && (
            <Button
              className="w-full h-12"
              variant="outline"
              onClick={onClose}
            >
              Schliessen
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}
