import { useState, useEffect } from 'react';
import { X, Swords, Shield, Package, Minus, Plus, Trash2, Pencil } from 'lucide-react';
import { Button, Input } from '@/shared/components/ui';
import { api } from '@/shared/lib/api';
import type { CharacterItem, Equipment } from '@/shared/types';

interface ItemDetailModalProps {
  item: CharacterItem;
  isGM: boolean;
  onClose: () => void;
  onUpdateQuantity: (quantity: number) => void;
  onRemove: () => void;
  onToggleEquipped: (equipped: boolean) => void;
  onUpdateItem: (data: {
    alias?: string;
    customName?: string;
    customDamage?: string;
    customDamageType?: string;
    customTraits?: string[];
    customRange?: string;
    customHands?: string;
  }) => void;
}

export function ItemDetailModal({
  item,
  isGM,
  onClose,
  onUpdateQuantity,
  onRemove,
  onToggleEquipped,
  onUpdateItem,
}: ItemDetailModalProps) {
  const [equipment, setEquipment] = useState<Equipment | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isEditing, setIsEditing] = useState(false);

  // Edit state
  const [alias, setAlias] = useState(item.alias || '');
  const [customName, setCustomName] = useState(item.customName || '');
  const [customDamage, setCustomDamage] = useState(item.customDamage || '');
  const [customDamageType, setCustomDamageType] = useState(item.customDamageType || '');
  const [customTraits, setCustomTraits] = useState(item.customTraits?.join(', ') || '');
  const [customRange, setCustomRange] = useState(item.customRange || '');
  const [customHands, setCustomHands] = useState(item.customHands || '');

  useEffect(() => {
    const fetchEquipmentDetails = async () => {
      if (!item.equipmentId) return;

      setIsLoading(true);
      try {
        const data = await api.getEquipmentById(item.equipmentId);
        setEquipment(data);
      } catch (error) {
        console.error('Failed to fetch equipment details:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchEquipmentDetails();
  }, [item.equipmentId]);

  const handleQuantityChange = (delta: number) => {
    const newQuantity = Math.max(1, item.quantity + delta);
    onUpdateQuantity(newQuantity);
  };

  const handleSaveEdit = () => {
    const updateData: any = { alias: alias || undefined };

    if (isGM) {
      updateData.customName = customName || undefined;
      updateData.customDamage = customDamage || undefined;
      updateData.customDamageType = customDamageType || undefined;
      updateData.customTraits = customTraits ? customTraits.split(',').map(t => t.trim()).filter(Boolean) : undefined;
      updateData.customRange = customRange || undefined;
      updateData.customHands = customHands || undefined;
    }

    onUpdateItem(updateData);
    setIsEditing(false);
  };

  const getCategoryIcon = () => {
    const category = equipment?.itemCategory?.toLowerCase() || '';
    if (category.includes('weapon')) return <Swords className="h-5 w-5 text-red-400" />;
    if (category.includes('armor') || category.includes('shield')) return <Shield className="h-5 w-5 text-blue-400" />;
    return <Package className="h-5 w-5 text-text-secondary" />;
  };

  const formatBulk = (bulk: number | string | undefined) => {
    if (bulk === undefined || bulk === null) return '—';
    if (bulk === 0 || bulk === '0') return '—';
    if (bulk === 'L' || (typeof bulk === 'number' && bulk < 1 && bulk > 0)) return 'L';
    return `${bulk}`;
  };

  // Get effective values (custom overrides base equipment)
  const effectiveDamage = item.customDamage || equipment?.damage;
  const effectiveDamageType = item.customDamageType || equipment?.damageType;
  const effectiveTraits = item.customTraits?.length ? item.customTraits : equipment?.traits;
  const effectiveRange = item.customRange || equipment?.range;
  const effectiveHands = item.customHands || equipment?.hands;
  const displayName = item.alias || item.customName || item.nameGerman || item.name;

  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">
            {getCategoryIcon()}
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-lg font-bold text-text-primary">
                  {displayName}
                </h2>
                {item.alias && (
                  <span className="px-1.5 py-0.5 text-xs rounded bg-primary-500/20 text-primary-400">
                    Alias
                  </span>
                )}
                {formatBulk(item.bulk) !== '—' && (
                  <span className="px-1.5 py-0.5 text-xs rounded bg-bg-tertiary text-text-secondary">
                    {formatBulk(item.bulk)} Bulk
                  </span>
                )}
              </div>
              {(item.alias || item.customName) && (
                <p className="text-sm text-text-secondary">{item.nameGerman || item.name}</p>
              )}
            </div>
          </div>
          <div className="flex items-center gap-1">
            <Button variant="ghost" size="icon" onClick={() => setIsEditing(!isEditing)}>
              <Pencil className="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="icon" onClick={onClose}>
              <X className="h-5 w-5" />
            </Button>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4 space-y-4">
          {isLoading ? (
            <div className="flex items-center justify-center py-8">
              <div className="animate-spin h-6 w-6 border-2 border-primary-500 border-t-transparent rounded-full" />
            </div>
          ) : isEditing ? (
            /* Edit Mode */
            <div className="space-y-4">
              {/* Player: Alias */}
              <div>
                <label className="block text-sm font-medium text-text-primary mb-1.5">
                  Alias / Spitzname
                </label>
                <Input
                  value={alias}
                  onChange={(e) => setAlias(e.target.value)}
                  placeholder="z.B. 'Opa's Schwert'"
                />
                <p className="text-xs text-text-muted mt-1">Dein persönlicher Name für diesen Gegenstand</p>
              </div>

              {/* GM-only fields */}
              {isGM && (
                <>
                  <div className="pt-2 border-t border-border">
                    <p className="text-xs text-primary-400 font-medium mb-3">GM-Anpassungen</p>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-text-primary mb-1.5">
                      Custom Name
                    </label>
                    <Input
                      value={customName}
                      onChange={(e) => setCustomName(e.target.value)}
                      placeholder={item.name}
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-sm font-medium text-text-primary mb-1.5">
                        Schaden
                      </label>
                      <Input
                        value={customDamage}
                        onChange={(e) => setCustomDamage(e.target.value)}
                        placeholder={equipment?.damage || '1d6'}
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-text-primary mb-1.5">
                        Schadenstyp
                      </label>
                      <Input
                        value={customDamageType}
                        onChange={(e) => setCustomDamageType(e.target.value)}
                        placeholder={equipment?.damageType || 'S'}
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-sm font-medium text-text-primary mb-1.5">
                        Reichweite
                      </label>
                      <Input
                        value={customRange}
                        onChange={(e) => setCustomRange(e.target.value)}
                        placeholder={equipment?.range || ''}
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-text-primary mb-1.5">
                        Hände
                      </label>
                      <Input
                        value={customHands}
                        onChange={(e) => setCustomHands(e.target.value)}
                        placeholder={equipment?.hands || '1'}
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-text-primary mb-1.5">
                      Traits (kommagetrennt)
                    </label>
                    <Input
                      value={customTraits}
                      onChange={(e) => setCustomTraits(e.target.value)}
                      placeholder={equipment?.traits?.join(', ') || 'Finesse, Agile'}
                    />
                  </div>
                </>
              )}

              <div className="flex gap-2 pt-2">
                <Button variant="outline" onClick={() => setIsEditing(false)} className="flex-1">
                  Abbrechen
                </Button>
                <Button onClick={handleSaveEdit} className="flex-1">
                  Speichern
                </Button>
              </div>
            </div>
          ) : (
            /* View Mode */
            <>
              {/* Weapon Stats */}
              {effectiveDamage && (
                <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20">
                  <p className="text-xs text-red-400 mb-1">Schaden</p>
                  <p className="text-lg font-bold text-red-400">
                    {effectiveDamage} {effectiveDamageType}
                    {item.customDamage && <span className="text-xs ml-2">(angepasst)</span>}
                  </p>
                  {effectiveRange && (
                    <p className="text-sm text-text-secondary mt-1">
                      Reichweite: {effectiveRange}
                    </p>
                  )}
                  {effectiveHands && (
                    <p className="text-sm text-text-secondary">
                      Hände: {effectiveHands}
                    </p>
                  )}
                </div>
              )}

              {/* Armor Stats */}
              {equipment?.ac && (
                <div className="p-3 rounded-lg bg-blue-500/10 border border-blue-500/20">
                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <p className="text-xs text-blue-400 mb-1">RK-Bonus</p>
                      <p className="text-lg font-bold text-blue-400">+{equipment.ac}</p>
                    </div>
                    {equipment.dexCap !== null && equipment.dexCap !== undefined && (
                      <div>
                        <p className="text-xs text-blue-400 mb-1">GES-Limit</p>
                        <p className="text-lg font-bold text-blue-400">+{equipment.dexCap}</p>
                      </div>
                    )}
                  </div>
                  {(equipment.checkPenalty || equipment.speedPenalty) && (
                    <div className="mt-2 text-sm text-text-secondary">
                      {equipment.checkPenalty && <span>Prüfungsmalus: {equipment.checkPenalty} </span>}
                      {equipment.speedPenalty && <span>Tempo: -{equipment.speedPenalty} ft</span>}
                    </div>
                  )}
                </div>
              )}

              {/* Traits */}
              {effectiveTraits && effectiveTraits.length > 0 && (
                <div>
                  <p className="text-xs text-text-secondary mb-2">
                    Merkmale {item.customTraits?.length ? '(angepasst)' : ''}
                  </p>
                  <div className="flex flex-wrap gap-1">
                    {effectiveTraits.map((trait) => (
                      <span
                        key={trait}
                        className="px-2 py-0.5 rounded text-xs bg-bg-tertiary text-text-secondary"
                      >
                        {trait}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* Summary/Description */}
              {(equipment?.summaryGerman || equipment?.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">
                    {equipment.summaryGerman || equipment.summary}
                  </p>
                  {equipment.summaryGerman && equipment.summary && (
                    <p className="text-xs text-text-muted mt-2 italic">
                      Original: {equipment.summary}
                    </p>
                  )}
                </div>
              )}

              {/* Quantity Control */}
              {!['Weapons', 'Armor', 'Shields'].includes(equipment?.itemCategory || item.equipment?.itemCategory || '') && (
                <div className="p-3 rounded-lg bg-bg-secondary">
                  <p className="text-xs text-text-secondary mb-2">Anzahl</p>
                  <div className="flex items-center justify-center gap-4">
                    <Button
                      size="icon"
                      variant="outline"
                      className="h-10 w-10"
                      onClick={() => handleQuantityChange(-1)}
                      disabled={item.quantity <= 1}
                    >
                      <Minus className="h-4 w-4" />
                    </Button>
                    <span className="text-2xl font-bold text-text-primary min-w-[60px] text-center">
                      {item.quantity}
                    </span>
                    <Button
                      size="icon"
                      variant="outline"
                      className="h-10 w-10"
                      onClick={() => handleQuantityChange(1)}
                    >
                      <Plus className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              )}

              {/* Notes */}
              {item.notes && (
                <div className="p-3 rounded-lg bg-bg-secondary">
                  <p className="text-xs text-text-secondary mb-1">Notizen</p>
                  <p className="text-sm text-text-primary">{item.notes}</p>
                </div>
              )}
            </>
          )}
        </div>

        {/* Footer Actions */}
        {!isEditing && (
          <div className="p-4 border-t border-border space-y-2">
            {['Weapons', 'Armor', 'Shields', 'Worn Items'].includes(equipment?.itemCategory || item.equipment?.itemCategory || '') && (
              <Button
                className="w-full"
                variant={item.equipped ? 'outline' : 'default'}
                onClick={() => onToggleEquipped(!item.equipped)}
              >
                {item.equipped ? 'Ablegen' : 'Anlegen'}
              </Button>
            )}
            <Button
              className="w-full"
              variant="destructive"
              onClick={() => {
                onRemove();
                onClose();
              }}
            >
              <Trash2 className="h-4 w-4 mr-2" />
              Entfernen
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
