import { useState, useEffect } from 'react';
import { X, Search, Package, Swords, Shield, FlaskConical, ChevronLeft, ChevronRight } from 'lucide-react';
import { Button, Input, Spinner } from '@/shared/components/ui';
import { api } from '@/shared/lib/api';
import type { Equipment, EquipmentSearchResult } from '@/shared/types';

interface AddItemModalProps {
  onClose: () => void;
  onAdd: (item: {
    equipmentId: string;
    name: string;
    nameGerman?: string;
    quantity: number;
    bulk: number;
    equipped: boolean;
  }) => Promise<void>;
  existingItemNames: string[];
}

type CategoryFilter = 'all' | 'Weapons' | 'Armor' | 'Shields' | 'Consumables' | 'Alchemical Items';

const CATEGORY_ICONS: Record<CategoryFilter, React.ReactNode> = {
  all: <Package className="h-4 w-4" />,
  Weapons: <Swords className="h-4 w-4" />,
  Armor: <Shield className="h-4 w-4" />,
  Shields: <Shield className="h-4 w-4" />,
  Consumables: <FlaskConical className="h-4 w-4" />,
  'Alchemical Items': <FlaskConical className="h-4 w-4" />,
};

const CATEGORY_LABELS: Record<CategoryFilter, string> = {
  all: 'Alle',
  Weapons: 'Waffen',
  Armor: 'Rüstung',
  Shields: 'Schilde',
  Consumables: 'Verbrauchsgüter',
  'Alchemical Items': 'Alchemie',
};

function parseBulk(bulkStr?: string): number {
  if (!bulkStr || bulkStr === '-' || bulkStr === '') return 0;
  if (bulkStr === 'L') return 0.1;
  const num = parseFloat(bulkStr);
  return isNaN(num) ? 0 : num;
}

export function AddItemModal({ onClose, onAdd, existingItemNames }: AddItemModalProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [category, setCategory] = useState<CategoryFilter>('all');
  const [searchResult, setSearchResult] = useState<EquipmentSearchResult | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedItem, setSelectedItem] = useState<Equipment | null>(null);
  const [quantity, setQuantity] = useState(1);
  const [isAdding, setIsAdding] = useState(false);
  const [page, setPage] = useState(1);

  // Search equipment
  useEffect(() => {
    const searchEquipment = async () => {
      setIsLoading(true);
      try {
        const result = await api.searchEquipment({
          query: searchQuery || undefined,
          category: category !== 'all' ? category : undefined,
          page,
          limit: 30,
        });
        setSearchResult(result);
      } catch (error) {
        console.error('Failed to search equipment:', error);
      } finally {
        setIsLoading(false);
      }
    };

    const debounce = setTimeout(searchEquipment, 300);
    return () => clearTimeout(debounce);
  }, [searchQuery, category, page]);

  // Reset page when search/category changes
  useEffect(() => {
    setPage(1);
  }, [searchQuery, category]);

  const handleAdd = async () => {
    if (!selectedItem) return;
    setIsAdding(true);
    try {
      const isIndividualItem = ['Weapons', 'Armor', 'Shields'].includes(selectedItem.itemCategory);

      if (isIndividualItem && quantity > 1) {
        // Waffen/Rüstung/Schilde einzeln hinzufügen
        for (let i = 0; i < quantity; i++) {
          await onAdd({
            equipmentId: selectedItem.id,
            name: selectedItem.name,
            quantity: 1,
            bulk: parseBulk(selectedItem.bulk),
            equipped: false,
          });
        }
      } else {
        // Normale Items mit Anzahl hinzufügen
        await onAdd({
          equipmentId: selectedItem.id,
          name: selectedItem.name,
          quantity,
          bulk: parseBulk(selectedItem.bulk),
          equipped: false,
        });
      }
      onClose();
    } catch (error) {
      console.error('Failed to add item:', error);
    } finally {
      setIsAdding(false);
    }
  };

  const isAlreadyOwned = (itemName: string) =>
    existingItemNames.some((n) => n.toLowerCase() === itemName.toLowerCase());

  const getCategoryColor = (itemCategory: string) => {
    switch (itemCategory) {
      case 'Weapons':
        return 'text-red-400';
      case 'Armor':
        return 'text-blue-400';
      case 'Shields':
        return 'text-cyan-400';
      case 'Consumables':
        return 'text-green-400';
      case 'Alchemical Items':
        return 'text-purple-400';
      default:
        return '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" onClick={onClose} />

      {/* Modal */}
      <div className="relative w-full sm:max-w-2xl max-h-[90vh] bg-bg-secondary rounded-t-2xl sm:rounded-2xl flex flex-col overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-border">
          <h2 className="text-lg font-semibold text-text-primary">
            {selectedItem ? 'Gegenstand hinzufügen' : 'Gegenstand suchen'}
          </h2>
          <Button variant="ghost" size="icon" onClick={onClose}>
            <X className="h-5 w-5" />
          </Button>
        </div>

        {selectedItem ? (
          // Selected item detail view
          <div className="flex-1 overflow-y-auto p-4 space-y-4">
            <button
              onClick={() => setSelectedItem(null)}
              className="text-sm text-primary-500 hover:text-primary-400"
            >
              &larr; Zurück zur Suche
            </button>

            <div className="p-4 rounded-xl bg-bg-tertiary">
              <div>
                <h3 className="font-semibold text-text-primary text-lg">
                  {selectedItem.name}
                </h3>
                <p className={`text-sm ${getCategoryColor(selectedItem.itemCategory)}`}>
                  {selectedItem.itemCategory}
                  {selectedItem.itemSubcategory && ` • ${selectedItem.itemSubcategory}`}
                </p>
              </div>

              {/* Item Stats */}
              <div className="mt-3 grid grid-cols-2 gap-2 text-sm">
                {selectedItem.bulk && (
                  <div>
                    <span className="text-text-secondary">Gewicht:</span>{' '}
                    <span className="text-text-primary">{selectedItem.bulk === 'L' ? 'Leicht' : selectedItem.bulk}</span>
                  </div>
                )}
                {selectedItem.damage && (
                  <div>
                    <span className="text-text-secondary">Schaden:</span>{' '}
                    <span className="text-text-primary">{selectedItem.damage}</span>
                  </div>
                )}
                {selectedItem.hands && (
                  <div>
                    <span className="text-text-secondary">Hände:</span>{' '}
                    <span className="text-text-primary">{selectedItem.hands}</span>
                  </div>
                )}
                {selectedItem.ac !== undefined && selectedItem.ac !== null && (
                  <div>
                    <span className="text-text-secondary">RK:</span>{' '}
                    <span className="text-text-primary">+{selectedItem.ac}</span>
                  </div>
                )}
                {selectedItem.weaponCategory && (
                  <div>
                    <span className="text-text-secondary">Kategorie:</span>{' '}
                    <span className="text-text-primary">{selectedItem.weaponCategory}</span>
                  </div>
                )}
              </div>

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

              {/* Summary */}
              {selectedItem.summary && (
                <p className="mt-3 text-sm text-text-secondary leading-relaxed">
                  {selectedItem.summary}
                </p>
              )}
            </div>

            {/* Quantity */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-text-primary">Anzahl</label>
              <div className="flex items-center gap-3">
                <Button
                  variant="outline"
                  size="icon"
                  onClick={() => setQuantity((q) => Math.max(1, q - 1))}
                  disabled={quantity <= 1}
                >
                  -
                </Button>
                <span className="text-2xl font-bold text-text-primary w-12 text-center">
                  {quantity}
                </span>
                <Button
                  variant="outline"
                  size="icon"
                  onClick={() => setQuantity((q) => Math.min(99, q + 1))}
                  disabled={quantity >= 99}
                >
                  +
                </Button>
              </div>
            </div>

            <Button
              className="w-full h-12"
              onClick={handleAdd}
              disabled={isAdding}
            >
              {isAdding ? 'Wird hinzugefügt...' : `${selectedItem.name} hinzufügen`}
            </Button>
          </div>
        ) : (
          // Search view
          <>
            {/* Search */}
            <div className="p-4 border-b border-border space-y-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text-secondary" />
                <Input
                  placeholder="Nach Gegenstand suchen..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10"
                  autoFocus
                />
              </div>

              {/* Category Filter */}
              <div className="flex gap-1 overflow-x-auto pb-1">
                {(Object.keys(CATEGORY_LABELS) as CategoryFilter[]).map((cat) => (
                  <button
                    key={cat}
                    onClick={() => setCategory(cat)}
                    className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${
                      category === cat
                        ? 'bg-primary-500 text-white'
                        : 'bg-bg-tertiary text-text-secondary hover:bg-bg-elevated hover:text-text-primary'
                    }`}
                  >
                    {CATEGORY_ICONS[cat]}
                    {CATEGORY_LABELS[cat]}
                  </button>
                ))}
              </div>
            </div>

            {/* Results */}
            <div className="flex-1 overflow-y-auto p-4">
              {isLoading ? (
                <div className="flex items-center justify-center py-8">
                  <Spinner />
                </div>
              ) : !searchResult?.items.length ? (
                <p className="text-center text-text-secondary py-8">
                  Keine Gegenstände gefunden
                </p>
              ) : (
                <div className="space-y-2">
                  {searchResult.items.map((item) => {
                    const owned = isAlreadyOwned(item.name);
                    return (
                      <button
                        key={item.id}
                        onClick={() => !owned && setSelectedItem(item)}
                        disabled={owned}
                        className={`w-full text-left p-3 rounded-lg transition-colors ${
                          owned
                            ? 'bg-bg-tertiary/50 opacity-50 cursor-not-allowed'
                            : 'bg-bg-tertiary hover:bg-bg-elevated'
                        }`}
                      >
                        <div className="flex items-center justify-between gap-2">
                          <div className="min-w-0 flex-1">
                            <p className="font-medium text-text-primary truncate">
                              {item.name}
                            </p>
                            <p className={`text-xs ${getCategoryColor(item.itemCategory)}`}>
                              {item.itemCategory}
                              {item.bulk && ` • ${item.bulk === 'L' ? 'Leicht' : `${item.bulk} Bulk`}`}
                            </p>
                          </div>
                          {owned && (
                            <span className="text-xs text-text-muted flex-shrink-0">Bereits im Inventar</span>
                          )}
                        </div>
                      </button>
                    );
                  })}
                </div>
              )}
            </div>

            {/* Pagination */}
            {searchResult && searchResult.totalPages > 1 && (
              <div className="flex items-center justify-between p-4 border-t border-border">
                <span className="text-sm text-text-secondary">
                  {searchResult.total} Ergebnisse
                </span>
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setPage((p) => Math.max(1, p - 1))}
                    disabled={page <= 1}
                  >
                    <ChevronLeft className="h-4 w-4" />
                  </Button>
                  <span className="text-sm text-text-primary">
                    {page} / {searchResult.totalPages}
                  </span>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setPage((p) => Math.min(searchResult.totalPages, p + 1))}
                    disabled={page >= searchResult.totalPages}
                  >
                    <ChevronRight className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
