import { useState, useEffect } from 'react';
import { X, Star, Trash2, ExternalLink } from 'lucide-react';
import { Button, Spinner } from '@/shared/components/ui';
import { api } from '@/shared/lib/api';
import type { CharacterFeat, Feat } from '@/shared/types';

interface FeatDetailModalProps {
  feat: CharacterFeat;
  onClose: () => void;
  onRemove: () => void;
}

const SOURCE_LABELS: Record<string, string> = {
  CLASS: 'Klassentalent',
  ANCESTRY: 'Abstammungstalent',
  GENERAL: 'Allgemeines Talent',
  SKILL: 'Fertigkeitstalent',
  ARCHETYPE: 'Archetypentalent',
  BONUS: 'Bonustalent',
};

const SOURCE_COLORS: Record<string, string> = {
  CLASS: 'bg-red-500/20 text-red-400',
  ANCESTRY: 'bg-blue-500/20 text-blue-400',
  GENERAL: 'bg-yellow-500/20 text-yellow-400',
  SKILL: 'bg-green-500/20 text-green-400',
  ARCHETYPE: 'bg-purple-500/20 text-purple-400',
  BONUS: 'bg-cyan-500/20 text-cyan-400',
};

export function FeatDetailModal({ feat, onClose, onRemove }: FeatDetailModalProps) {
  const [featDetails, setFeatDetails] = useState<Feat | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [notFound, setNotFound] = useState(false);

  // Try to load feat details from database
  useEffect(() => {
    const fetchFeatDetails = async () => {
      // If we have a featId, try to fetch from database
      if (feat.featId) {
        setIsLoading(true);
        try {
          const data = await api.getFeatById(feat.featId);
          setFeatDetails(data);
        } catch (error) {
          console.error('Failed to fetch feat details:', error);
          setNotFound(true);
        } finally {
          setIsLoading(false);
        }
      } else {
        // Try to find by name
        setIsLoading(true);
        try {
          const data = await api.getFeatByName(feat.name);
          setFeatDetails(data);
        } catch {
          // Feat not in database, that's OK
          setNotFound(true);
        } finally {
          setIsLoading(false);
        }
      }
    };

    fetchFeatDetails();
  }, [feat.featId, feat.name]);

  const getActionsDisplay = (actions?: string) => {
    if (!actions) return null;
    switch (actions) {
      case '1':
        return <span className="text-sm px-2 py-0.5 rounded bg-primary-500/20 text-primary-400">1 Aktion</span>;
      case '2':
        return <span className="text-sm px-2 py-0.5 rounded bg-primary-500/20 text-primary-400">2 Aktionen</span>;
      case '3':
        return <span className="text-sm px-2 py-0.5 rounded bg-primary-500/20 text-primary-400">3 Aktionen</span>;
      case 'free':
        return <span className="text-sm px-2 py-0.5 rounded bg-green-500/20 text-green-400">Freie Aktion</span>;
      case 'reaction':
        return <span className="text-sm px-2 py-0.5 rounded bg-yellow-500/20 text-yellow-400">Reaktion</span>;
      default:
        return null;
    }
  };

  const displayName = feat.nameGerman || feat.name;
  const sourceLabel = SOURCE_LABELS[feat.source] || feat.source;
  const sourceColor = SOURCE_COLORS[feat.source] || 'bg-bg-tertiary text-text-secondary';

  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 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="relative w-full sm:max-w-lg bg-bg-primary rounded-t-2xl sm:rounded-2xl border border-border max-h-[85vh] flex flex-col animate-in slide-in-from-bottom-4 sm:slide-in-from-bottom-0 sm:zoom-in-95 duration-200">
        {/* Header */}
        <div className="flex items-start justify-between p-4 border-b border-border">
          <div className="flex items-center gap-3">
            <Star className="h-5 w-5 text-yellow-400" />
            <div>
              <div className="flex items-center gap-2 flex-wrap">
                <h2 className="text-lg font-bold text-text-primary">
                  {displayName}
                </h2>
                {featDetails?.actions && getActionsDisplay(featDetails.actions)}
              </div>
              {feat.nameGerman && feat.name !== feat.nameGerman && (
                <p className="text-sm text-text-muted">{feat.name}</p>
              )}
            </div>
          </div>
          <Button variant="ghost" size="icon" onClick={onClose}>
            <X className="h-5 w-5" />
          </Button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4 space-y-4">
          {isLoading ? (
            <div className="flex items-center justify-center py-8">
              <Spinner />
            </div>
          ) : (
            <>
              {/* Basic Info */}
              <div className="flex flex-wrap gap-2">
                <span className={`px-2 py-1 rounded text-sm font-medium ${sourceColor}`}>
                  {sourceLabel}
                </span>
                <span className="px-2 py-1 rounded text-sm bg-bg-tertiary text-text-secondary">
                  Level {feat.level} erhalten
                </span>
                {featDetails?.level && (
                  <span className="px-2 py-1 rounded text-sm bg-bg-tertiary text-text-secondary">
                    Benötigt Level {featDetails.level}+
                  </span>
                )}
                {featDetails?.rarity && featDetails.rarity !== 'Common' && (
                  <span className={`px-2 py-1 rounded text-sm ${
                    featDetails.rarity === 'Uncommon' ? 'bg-orange-500/20 text-orange-400' :
                    featDetails.rarity === 'Rare' ? 'bg-blue-500/20 text-blue-400' :
                    'bg-purple-500/20 text-purple-400'
                  }`}>
                    {featDetails.rarity}
                  </span>
                )}
              </div>

              {/* Prerequisites */}
              {featDetails?.prerequisites && (
                <div className="p-3 rounded-lg bg-bg-secondary">
                  <p className="text-xs text-text-secondary mb-1">Voraussetzungen</p>
                  <p className="text-sm text-text-primary">{featDetails.prerequisites}</p>
                </div>
              )}

              {/* Traits */}
              {featDetails?.traits && featDetails.traits.length > 0 && (
                <div>
                  <p className="text-xs text-text-secondary mb-2">Merkmale</p>
                  <div className="flex flex-wrap gap-1">
                    {featDetails.traits.map((trait) => (
                      <span
                        key={trait}
                        className="px-2 py-0.5 rounded text-xs bg-primary-500/20 text-primary-400"
                      >
                        {trait}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* Summary/Description */}
              {featDetails?.summary && (
                <div className="p-3 rounded-lg bg-bg-secondary">
                  <p className="text-xs text-text-secondary mb-1">Beschreibung</p>
                  <p className="text-sm text-text-primary leading-relaxed">
                    {featDetails.summaryGerman || featDetails.summary}
                  </p>
                  {featDetails.summaryGerman && featDetails.summary && (
                    <p className="text-xs text-text-muted mt-2 italic">
                      Original: {featDetails.summary}
                    </p>
                  )}
                </div>
              )}

              {/* Full Description */}
              {featDetails?.description && (
                <div className="p-3 rounded-lg bg-bg-secondary">
                  <p className="text-xs text-text-secondary mb-1">
                    Vollständige Beschreibung <span className="text-text-muted">(Englisch)</span>
                  </p>
                  <p className="text-sm text-text-primary leading-relaxed whitespace-pre-wrap">
                    {featDetails.description}
                  </p>
                </div>
              )}

              {/* Not found in database message */}
              {notFound && !featDetails && (
                <div className="p-3 rounded-lg bg-bg-secondary text-center">
                  <p className="text-sm text-text-muted">
                    Detaillierte Informationen nicht verfügbar.
                  </p>
                  <p className="text-xs text-text-muted mt-1">
                    Dieses Talent ist nicht in der Datenbank.
                  </p>
                </div>
              )}

              {/* Archives of Nethys Link */}
              {featDetails?.url && (
                <a
                  href={`https://2e.aonprd.com${featDetails.url}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-2 text-sm text-primary-400 hover:text-primary-300"
                >
                  <ExternalLink className="h-4 w-4" />
                  Auf Archives of Nethys anzeigen
                </a>
              )}
            </>
          )}
        </div>

        {/* Footer Actions */}
        <div className="p-4 border-t border-border">
          <Button
            className="w-full"
            variant="destructive"
            onClick={() => {
              onRemove();
              onClose();
            }}
          >
            <Trash2 className="h-4 w-4 mr-2" />
            Talent entfernen
          </Button>
        </div>
      </div>
    </div>
  );
}
