import { useState } from 'react';
import { Heart, Swords, Sparkles, X, Skull, RotateCcw } from 'lucide-react';
import { Button, Card, CardContent, Input } from '@/shared/components/ui';
import { DyingIndicator } from './dying-indicator';

interface HpControlProps {
  hpCurrent: number;
  hpMax: number;
  hpTemp?: number;
  dyingValue?: number;
  woundedValue?: number;
  doomedValue?: number;
  onHpChange: (newHp: number) => Promise<void>;
  onRecoveryCheck?: () => void;
  onRevive?: () => void;
}

type Mode = 'view' | 'damage' | 'heal' | 'direct';

export function HpControl({
  hpCurrent,
  hpMax,
  hpTemp = 0,
  dyingValue = 0,
  woundedValue = 0,
  doomedValue = 0,
  onHpChange,
  onRecoveryCheck,
  onRevive,
}: HpControlProps) {
  const [mode, setMode] = useState<Mode>('view');
  const [pendingChange, setPendingChange] = useState(0);
  const [directValue, setDirectValue] = useState(hpCurrent);
  const [isUpdating, setIsUpdating] = useState(false);

  const hpPercentage = (hpCurrent / hpMax) * 100;

  const getHpColor = () => {
    if (hpPercentage <= 25) return 'text-red-500';
    if (hpPercentage <= 50) return 'text-yellow-500';
    return 'text-green-500';
  };

  const getBarColor = () => {
    if (hpPercentage <= 25) return 'bg-red-500';
    if (hpPercentage <= 50) return 'bg-yellow-500';
    return 'bg-green-500';
  };

  const handleQuickChange = (amount: number) => {
    setPendingChange((prev) => {
      const newValue = prev + amount;
      // Prevent going below 0 or above max in damage/heal mode
      if (mode === 'damage') {
        return Math.min(newValue, hpCurrent);
      } else if (mode === 'heal') {
        return Math.min(newValue, hpMax - hpCurrent);
      }
      return Math.max(0, newValue);
    });
  };

  const handleApply = async () => {
    if (isUpdating) return;
    setIsUpdating(true);

    let newHp: number;
    if (mode === 'damage') {
      newHp = Math.max(0, hpCurrent - pendingChange);
    } else if (mode === 'heal') {
      newHp = Math.min(hpMax, hpCurrent + pendingChange);
    } else if (mode === 'direct') {
      newHp = Math.max(0, Math.min(hpMax, directValue));
    } else {
      setIsUpdating(false);
      return;
    }

    try {
      await onHpChange(newHp);
      setMode('view');
      setPendingChange(0);
    } catch (error) {
      console.error('Failed to update HP:', error);
    } finally {
      setIsUpdating(false);
    }
  };

  const handleCancel = () => {
    setMode('view');
    setPendingChange(0);
    setDirectValue(hpCurrent);
  };

  const openMode = (newMode: Mode) => {
    setMode(newMode);
    setPendingChange(0);
    setDirectValue(hpCurrent);
  };

  // View Mode - Main Display
  if (mode === 'view') {
    const deathThreshold = 4 - doomedValue;
    const isDead = dyingValue >= deathThreshold;
    const isDying = dyingValue > 0 && !isDead;

    // When dead, show death overlay
    if (isDead) {
      return (
        <Card className="border-gray-500/50 bg-gray-900/50">
          <CardContent className="py-8">
            <div className="flex flex-col items-center text-center">
              {/* Death Icon */}
              <div className="w-20 h-20 rounded-full bg-gray-800 flex items-center justify-center mb-4 border-2 border-gray-600">
                <Skull className="h-10 w-10 text-gray-400" />
              </div>

              {/* Death Text */}
              <h3 className="text-2xl font-bold text-gray-400 mb-2">Tot</h3>
              <p className="text-sm text-gray-500 mb-6">
                Dieser Charakter ist gestorben.
              </p>

              {/* Revive Button */}
              {onRevive && (
                <Button
                  variant="outline"
                  className="h-14 px-8 text-base font-semibold border-primary-500/50 text-primary-400 hover:bg-primary-500/20 hover:border-primary-500"
                  onClick={onRevive}
                >
                  <RotateCcw className="h-5 w-5 mr-2" />
                  Wiederbeleben
                </Button>
              )}
            </div>
          </CardContent>
        </Card>
      );
    }

    // When dying, show a completely different view focused on recovery
    if (isDying) {
      return (
        <Card className="border-red-500/30">
          <CardContent className="py-4">
            {/* Dying State - Full Width */}
            <DyingIndicator
              dyingValue={dyingValue}
              woundedValue={woundedValue}
              doomedValue={doomedValue}
              onRecoveryCheck={onRecoveryCheck}
            />

            {/* Heal Button - Primary action when dying */}
            <div className="mt-4">
              <Button
                variant="outline"
                className="w-full h-14 text-base font-semibold border-green-500/50 text-green-400 hover:bg-green-500/20 hover:border-green-500"
                onClick={() => openMode('heal')}
              >
                <Sparkles className="h-5 w-5 mr-2" />
                Heilung erhalten
              </Button>
            </div>
          </CardContent>
        </Card>
      );
    }

    return (
      <Card>
        <CardContent className="py-4">
          {/* HP Display */}
          <div className="flex items-center gap-3 mb-3">
            <Heart className="h-6 w-6 text-red-500 flex-shrink-0" />
            <div className="flex-1">
              <div className="flex items-center justify-between mb-1">
                <span className="text-sm font-medium text-text-primary">Trefferpunkte</span>
                <button
                  onClick={() => openMode('direct')}
                  className={`font-bold text-lg ${getHpColor()}`}
                >
                  {hpCurrent} / {hpMax}
                  {hpTemp > 0 && (
                    <span className="text-sm text-blue-400 ml-1">(+{hpTemp})</span>
                  )}
                </button>
              </div>
              <div className="h-4 bg-bg-tertiary rounded-full overflow-hidden">
                <div
                  className={`h-full transition-all duration-300 ${getBarColor()}`}
                  style={{ width: `${hpPercentage}%` }}
                />
              </div>
            </div>
          </div>

          {/* Wounded/Doomed indicators (when not dying) */}
          {(woundedValue > 0 || doomedValue > 0) && (
            <div className="mb-3">
              <DyingIndicator
                dyingValue={0}
                woundedValue={woundedValue}
                doomedValue={doomedValue}
              />
            </div>
          )}

          {/* Quick Action Buttons */}
          <div className="grid grid-cols-2 gap-3">
            <Button
              variant="outline"
              className="h-14 text-base font-semibold border-red-500/50 text-red-400 hover:bg-red-500/20 hover:border-red-500"
              onClick={() => openMode('damage')}
            >
              <Swords className="h-5 w-5 mr-2" />
              Schaden
            </Button>
            <Button
              variant="outline"
              className="h-14 text-base font-semibold border-green-500/50 text-green-400 hover:bg-green-500/20 hover:border-green-500"
              onClick={() => openMode('heal')}
            >
              <Sparkles className="h-5 w-5 mr-2" />
              Heilung
            </Button>
          </div>
        </CardContent>
      </Card>
    );
  }

  // Direct Edit Mode
  if (mode === 'direct') {
    return (
      <Card>
        <CardContent className="py-4">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <Heart className="h-6 w-6 text-red-500" />
              <span className="font-medium text-text-primary">HP direkt setzen</span>
            </div>
            <Button variant="ghost" size="icon" onClick={handleCancel} className="h-10 w-10">
              <X className="h-5 w-5" />
            </Button>
          </div>

          <div className="flex items-center justify-center gap-4 mb-4">
            <Input
              type="number"
              value={directValue}
              onChange={(e) => setDirectValue(parseInt(e.target.value) || 0)}
              className="w-24 h-14 text-center text-2xl font-bold"
              min={0}
              max={hpMax}
            />
            <span className="text-2xl text-text-secondary">/</span>
            <span className="text-2xl font-bold text-text-primary">{hpMax}</span>
          </div>

          {/* Quick Set Buttons */}
          <div className="grid grid-cols-4 gap-2 mb-4">
            <Button
              variant="outline"
              className="h-12"
              onClick={() => setDirectValue(0)}
            >
              0
            </Button>
            <Button
              variant="outline"
              className="h-12"
              onClick={() => setDirectValue(Math.floor(hpMax * 0.25))}
            >
              25%
            </Button>
            <Button
              variant="outline"
              className="h-12"
              onClick={() => setDirectValue(Math.floor(hpMax * 0.5))}
            >
              50%
            </Button>
            <Button
              variant="outline"
              className="h-12"
              onClick={() => setDirectValue(hpMax)}
            >
              Max
            </Button>
          </div>

          <Button
            className="w-full h-14 text-lg font-semibold"
            onClick={handleApply}
            disabled={isUpdating || directValue === hpCurrent}
          >
            {isUpdating ? 'Speichere...' : 'Übernehmen'}
          </Button>
        </CardContent>
      </Card>
    );
  }

  // Damage / Heal Mode
  const isDamage = mode === 'damage';
  const accentColor = isDamage ? 'red' : 'green';
  const Icon = isDamage ? Swords : Sparkles;
  const title = isDamage ? 'Schaden' : 'Heilung';
  const previewHp = isDamage
    ? Math.max(0, hpCurrent - pendingChange)
    : Math.min(hpMax, hpCurrent + pendingChange);

  return (
    <Card>
      <CardContent className="py-4">
        {/* Header */}
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <Icon className={`h-6 w-6 text-${accentColor}-500`} />
            <span className="font-medium text-text-primary">{title}</span>
          </div>
          <Button variant="ghost" size="icon" onClick={handleCancel} className="h-10 w-10">
            <X className="h-5 w-5" />
          </Button>
        </div>

        {/* Preview */}
        <div className="text-center mb-4">
          <div className="text-4xl font-bold text-text-primary mb-1">
            {isDamage ? '-' : '+'}{pendingChange}
          </div>
          <div className="text-sm text-text-secondary">
            {hpCurrent} → <span className={`font-semibold text-${accentColor}-400`}>{previewHp}</span>
          </div>
        </div>

        {/* Quick Buttons - Large Touch Targets */}
        <div className="grid grid-cols-4 gap-2 mb-4">
          <Button
            variant="outline"
            className={`h-14 text-lg font-bold border-${accentColor}-500/50 text-${accentColor}-400 hover:bg-${accentColor}-500/20`}
            onClick={() => handleQuickChange(1)}
          >
            +1
          </Button>
          <Button
            variant="outline"
            className={`h-14 text-lg font-bold border-${accentColor}-500/50 text-${accentColor}-400 hover:bg-${accentColor}-500/20`}
            onClick={() => handleQuickChange(5)}
          >
            +5
          </Button>
          <Button
            variant="outline"
            className={`h-14 text-lg font-bold border-${accentColor}-500/50 text-${accentColor}-400 hover:bg-${accentColor}-500/20`}
            onClick={() => handleQuickChange(10)}
          >
            +10
          </Button>
          <Button
            variant="outline"
            className={`h-14 text-lg font-bold border-${accentColor}-500/50 text-${accentColor}-400 hover:bg-${accentColor}-500/20`}
            onClick={() => handleQuickChange(20)}
          >
            +20
          </Button>
        </div>

        {/* Subtract Row */}
        <div className="grid grid-cols-4 gap-2 mb-4">
          <Button
            variant="ghost"
            className="h-12 text-base text-text-secondary"
            onClick={() => handleQuickChange(-1)}
            disabled={pendingChange <= 0}
          >
            -1
          </Button>
          <Button
            variant="ghost"
            className="h-12 text-base text-text-secondary"
            onClick={() => handleQuickChange(-5)}
            disabled={pendingChange < 5}
          >
            -5
          </Button>
          <Button
            variant="ghost"
            className="h-12 text-base text-text-secondary"
            onClick={() => handleQuickChange(-10)}
            disabled={pendingChange < 10}
          >
            -10
          </Button>
          <Button
            variant="ghost"
            className="h-12 text-base"
            onClick={() => setPendingChange(0)}
            disabled={pendingChange === 0}
          >
            Reset
          </Button>
        </div>

        {/* Apply Button */}
        <Button
          className={`w-full h-14 text-lg font-semibold ${
            isDamage
              ? 'bg-red-600 hover:bg-red-700'
              : 'bg-green-600 hover:bg-green-700'
          }`}
          onClick={handleApply}
          disabled={isUpdating || pendingChange === 0}
        >
          {isUpdating ? 'Speichere...' : `${pendingChange} ${title} anwenden`}
        </Button>
      </CardContent>
    </Card>
  );
}
