import { useState, useEffect } from 'react';
import { Moon, Heart, Shield, Sparkles, FlaskConical, X, Loader2 } from 'lucide-react';
import { Button, Card, CardContent } from '@/shared/components/ui';
import { api } from '@/shared/lib/api';
import type { RestPreview, RestResult } from '@/shared/types';

interface RestModalProps {
  campaignId: string;
  characterId: string;
  onClose: () => void;
  onRestComplete: (result: RestResult) => void;
}

export function RestModal({ campaignId, characterId, onClose, onRestComplete }: RestModalProps) {
  const [preview, setPreview] = useState<RestPreview | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isResting, setIsResting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadPreview();
  }, [campaignId, characterId]);

  const loadPreview = async () => {
    try {
      setIsLoading(true);
      const data = await api.getRestPreview(campaignId, characterId);
      setPreview(data);
    } catch (err) {
      setError('Fehler beim Laden der Vorschau');
      console.error('Failed to load rest preview:', err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleRest = async () => {
    try {
      setIsResting(true);
      const result = await api.performRest(campaignId, characterId);
      onRestComplete(result);
      onClose();
    } catch (err) {
      setError('Fehler beim Rasten');
      console.error('Failed to perform rest:', err);
    } finally {
      setIsResting(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={onClose}>
      <Card className="w-full max-w-md" onClick={(e) => e.stopPropagation()}>
        <div className="p-4 border-b border-border">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-full bg-indigo-500/20 flex items-center justify-center">
                <Moon className="h-5 w-5 text-indigo-400" />
              </div>
              <div>
                <h2 className="text-lg font-bold text-text-primary">Rasten</h2>
                <p className="text-xs text-text-secondary">8 Stunden + Tägliche Vorbereitung</p>
              </div>
            </div>
            <Button variant="ghost" size="icon" onClick={onClose}>
              <X className="h-5 w-5" />
            </Button>
          </div>
        </div>

        <CardContent className="p-4">
          {isLoading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-6 w-6 animate-spin text-primary-500" />
            </div>
          ) : error ? (
            <div className="text-center py-4 text-red-400">{error}</div>
          ) : preview ? (
            <div className="space-y-4">
              {/* HP Healing */}
              {preview.hpToHeal > 0 && (
                <div className="flex items-center gap-3 p-3 rounded-lg bg-green-500/10 border border-green-500/20">
                  <Heart className="h-5 w-5 text-green-400 flex-shrink-0" />
                  <div>
                    <p className="text-sm font-medium text-green-400">HP-Heilung</p>
                    <p className="text-xs text-text-secondary">
                      +{preview.hpToHeal} HP (auf {preview.hpAfterRest})
                    </p>
                  </div>
                </div>
              )}

              {/* Conditions to Remove */}
              {preview.conditionsToRemove.length > 0 && (
                <div className="flex items-start gap-3 p-3 rounded-lg bg-red-500/10 border border-red-500/20">
                  <Shield className="h-5 w-5 text-red-400 flex-shrink-0 mt-0.5" />
                  <div>
                    <p className="text-sm font-medium text-red-400">Zustände entfernen</p>
                    <div className="flex flex-wrap gap-1 mt-1">
                      {preview.conditionsToRemove.map((c, i) => (
                        <span key={i} className="text-xs px-2 py-0.5 rounded bg-red-500/20 text-red-300">
                          {c}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {/* Conditions to Reduce */}
              {preview.conditionsToReduce.length > 0 && (
                <div className="flex items-start gap-3 p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20">
                  <Shield className="h-5 w-5 text-yellow-400 flex-shrink-0 mt-0.5" />
                  <div>
                    <p className="text-sm font-medium text-yellow-400">Zustände reduzieren</p>
                    <div className="flex flex-wrap gap-1 mt-1">
                      {preview.conditionsToReduce.map((c, i) => (
                        <span key={i} className="text-xs px-2 py-0.5 rounded bg-yellow-500/20 text-yellow-300">
                          {c.name} {c.oldValue} → {c.newValue}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {/* Resources to Reset */}
              {preview.resourcesToReset.length > 0 && (
                <div className="flex items-start gap-3 p-3 rounded-lg bg-blue-500/10 border border-blue-500/20">
                  <Sparkles className="h-5 w-5 text-blue-400 flex-shrink-0 mt-0.5" />
                  <div>
                    <p className="text-sm font-medium text-blue-400">Ressourcen auffüllen</p>
                    <div className="flex flex-wrap gap-1 mt-1">
                      {preview.resourcesToReset.map((r, i) => (
                        <span key={i} className="text-xs px-2 py-0.5 rounded bg-blue-500/20 text-blue-300">
                          {r}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {/* Alchemy Reset */}
              {preview.alchemyReset && (
                <div className="flex items-center gap-3 p-3 rounded-lg bg-purple-500/10 border border-purple-500/20">
                  <FlaskConical className="h-5 w-5 text-purple-400 flex-shrink-0" />
                  <div>
                    <p className="text-sm font-medium text-purple-400">Alchemie zurücksetzen</p>
                    <p className="text-xs text-text-secondary">
                      {preview.infusedItemsCount > 0
                        ? `${preview.infusedItemsCount} infundierte Items verfallen, Phiolen werden aufgefüllt`
                        : 'Phiolen werden aufgefüllt'}
                    </p>
                  </div>
                </div>
              )}

              {/* Nothing to do */}
              {preview.hpToHeal === 0 &&
               preview.conditionsToRemove.length === 0 &&
               preview.conditionsToReduce.length === 0 &&
               preview.resourcesToReset.length === 0 &&
               !preview.alchemyReset && (
                <div className="text-center py-4 text-text-secondary">
                  <p>Dein Charakter ist bereits vollständig erholt.</p>
                </div>
              )}
            </div>
          ) : null}

          {/* Action Buttons */}
          <div className="flex gap-2 mt-6">
            <Button variant="outline" className="flex-1" onClick={onClose}>
              Abbrechen
            </Button>
            <Button
              className="flex-1 bg-indigo-600 hover:bg-indigo-700"
              onClick={handleRest}
              disabled={isLoading || isResting}
            >
              {isResting ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Raste...
                </>
              ) : (
                <>
                  <Moon className="h-4 w-4 mr-2" />
                  Rasten
                </>
              )}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
