import { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ArrowLeft, Map, Users, Plus, Trash2, Image, Swords } from 'lucide-react';
import { api } from '@/shared/lib/api';
import { useAuthStore } from '@/features/auth';
import { UploadMapModal } from './upload-map-modal';
import { CreateCombatantModal } from './create-combatant-modal';
import type { BattleMap, Combatant } from '@/shared/types';
import { cn } from '@/shared/lib/utils';

type Tab = 'maps' | 'combatants';

const API_URL = import.meta.env.VITE_API_URL?.replace('/api', '') || 'http://localhost:5000';

export function LibraryPage() {
  const { id: campaignId } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { user } = useAuthStore();

  const [activeTab, setActiveTab] = useState<Tab>('maps');
  const [showUploadMap, setShowUploadMap] = useState(false);
  const [showCreateCombatant, setShowCreateCombatant] = useState(false);

  // Fetch campaign to check GM status
  const { data: campaign } = useQuery({
    queryKey: ['campaign', campaignId],
    queryFn: () => api.getCampaign(campaignId!),
    enabled: !!campaignId,
  });

  const isGM = campaign?.gmId === user?.id;

  // Redirect non-GMs
  if (campaign && !isGM) {
    navigate(`/campaigns/${campaignId}`);
    return null;
  }

  // Fetch battle maps
  const { data: maps = [], isLoading: mapsLoading } = useQuery({
    queryKey: ['battleMaps', campaignId],
    queryFn: () => api.getBattleMaps(campaignId!),
    enabled: !!campaignId,
  });

  // Fetch combatants
  const { data: combatants = [], isLoading: combatantsLoading } = useQuery({
    queryKey: ['combatants', campaignId],
    queryFn: () => api.getCombatants(campaignId!),
    enabled: !!campaignId,
  });

  // Upload map mutation
  const uploadMapMutation = useMutation({
    mutationFn: (data: Parameters<typeof api.uploadBattleMap>[1]) =>
      api.uploadBattleMap(campaignId!, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['battleMaps', campaignId] });
      setShowUploadMap(false);
    },
  });

  // Delete map mutation
  const deleteMapMutation = useMutation({
    mutationFn: (mapId: string) => api.deleteBattleMap(campaignId!, mapId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['battleMaps', campaignId] });
    },
  });

  // Create combatant mutation
  const createCombatantMutation = useMutation({
    mutationFn: (data: Parameters<typeof api.createCombatant>[1]) =>
      api.createCombatant(campaignId!, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['combatants', campaignId] });
      setShowCreateCombatant(false);
    },
  });

  // Delete combatant mutation
  const deleteCombatantMutation = useMutation({
    mutationFn: (combatantId: string) => api.deleteCombatant(campaignId!, combatantId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['combatants', campaignId] });
    },
  });

  return (
    <div className="min-h-screen bg-bg-primary">
      {/* Header */}
      <header className="sticky top-0 z-10 bg-bg-secondary border-b border-border-default">
        <div className="max-w-6xl mx-auto px-4 py-3">
          <div className="flex items-center gap-3">
            <button
              onClick={() => navigate(`/campaigns/${campaignId}`)}
              className="p-2 rounded-lg hover:bg-white/10 text-text-secondary transition-colors"
            >
              <ArrowLeft className="w-5 h-5" />
            </button>
            <div>
              <h1 className="text-lg font-semibold text-text-primary">Bibliothek</h1>
              <p className="text-sm text-text-secondary">{campaign?.name}</p>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div className="max-w-6xl mx-auto px-4">
          <div className="flex gap-1">
            <button
              onClick={() => setActiveTab('maps')}
              className={cn(
                'flex items-center gap-2 px-4 py-2 text-sm font-medium border-b-2 transition-colors',
                activeTab === 'maps'
                  ? 'border-primary text-primary'
                  : 'border-transparent text-text-secondary hover:text-text-primary'
              )}
            >
              <Map className="w-4 h-4" />
              Karten ({maps.length})
            </button>
            <button
              onClick={() => setActiveTab('combatants')}
              className={cn(
                'flex items-center gap-2 px-4 py-2 text-sm font-medium border-b-2 transition-colors',
                activeTab === 'combatants'
                  ? 'border-primary text-primary'
                  : 'border-transparent text-text-secondary hover:text-text-primary'
              )}
            >
              <Users className="w-4 h-4" />
              NPCs ({combatants.length})
            </button>
          </div>
        </div>
      </header>

      {/* Content */}
      <main className="max-w-6xl mx-auto px-4 py-6">
        {activeTab === 'maps' ? (
          <div>
            {/* Add Map Button */}
            <div className="flex justify-end mb-4">
              <button
                onClick={() => setShowUploadMap(true)}
                className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/80 transition-colors"
              >
                <Plus className="w-4 h-4" />
                Karte hochladen
              </button>
            </div>

            {/* Maps Grid */}
            {mapsLoading ? (
              <div className="text-center py-12 text-text-secondary">Laden...</div>
            ) : maps.length === 0 ? (
              <div className="text-center py-12">
                <Image className="w-12 h-12 text-text-secondary mx-auto mb-3" />
                <p className="text-text-secondary">Noch keine Karten hochgeladen</p>
                <button
                  onClick={() => setShowUploadMap(true)}
                  className="mt-4 text-primary hover:text-primary/80"
                >
                  Erste Karte hochladen
                </button>
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                {maps.map((map: BattleMap) => (
                  <div
                    key={map.id}
                    className="bg-bg-secondary border border-border-default rounded-lg overflow-hidden group"
                  >
                    {/* Map Preview */}
                    <div className="aspect-video bg-black/30 relative">
                      <img
                        src={`${API_URL}${map.imageUrl}`}
                        alt={map.name}
                        className="w-full h-full object-cover"
                      />
                      {/* Overlay with actions */}
                      <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
                        <button
                          onClick={() => {
                            if (confirm('Karte wirklich löschen?')) {
                              deleteMapMutation.mutate(map.id);
                            }
                          }}
                          className="p-2 bg-red-500/20 text-red-400 rounded-lg hover:bg-red-500/30"
                        >
                          <Trash2 className="w-5 h-5" />
                        </button>
                      </div>
                    </div>
                    {/* Map Info */}
                    <div className="p-3">
                      <h3 className="font-medium text-text-primary truncate">{map.name}</h3>
                      <p className="text-sm text-text-secondary">
                        {map.gridSizeX} x {map.gridSizeY} Grid
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        ) : (
          <div>
            {/* Add Combatant Button */}
            <div className="flex justify-end mb-4">
              <button
                onClick={() => setShowCreateCombatant(true)}
                className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/80 transition-colors"
              >
                <Plus className="w-4 h-4" />
                NPC erstellen
              </button>
            </div>

            {/* Combatants List */}
            {combatantsLoading ? (
              <div className="text-center py-12 text-text-secondary">Laden...</div>
            ) : combatants.length === 0 ? (
              <div className="text-center py-12">
                <Swords className="w-12 h-12 text-text-secondary mx-auto mb-3" />
                <p className="text-text-secondary">Noch keine NPCs erstellt</p>
                <button
                  onClick={() => setShowCreateCombatant(true)}
                  className="mt-4 text-primary hover:text-primary/80"
                >
                  Ersten NPC erstellen
                </button>
              </div>
            ) : (
              <div className="space-y-2">
                {combatants.map((combatant: Combatant) => (
                  <div
                    key={combatant.id}
                    className="bg-bg-secondary border border-border-default rounded-lg p-4 flex items-center justify-between gap-4"
                  >
                    <div className="flex items-center gap-4 min-w-0 flex-1">
                      {/* Avatar */}
                      <div className={cn(
                        'w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0',
                        combatant.type === 'MONSTER' ? 'bg-red-500/20' : 'bg-blue-500/20'
                      )}>
                        <Swords className={cn(
                          'w-6 h-6',
                          combatant.type === 'MONSTER' ? 'text-red-400' : 'text-blue-400'
                        )} />
                      </div>

                      {/* Info */}
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-2">
                          <h3 className="font-medium text-text-primary truncate">{combatant.name}</h3>
                          <span className={cn(
                            'text-xs px-1.5 py-0.5 rounded',
                            combatant.type === 'MONSTER'
                              ? 'bg-red-500/20 text-red-400'
                              : 'bg-blue-500/20 text-blue-400'
                          )}>
                            {combatant.type === 'MONSTER' ? 'Monster' : 'NPC'}
                          </span>
                        </div>
                        <div className="flex items-center gap-4 text-sm text-text-secondary mt-1">
                          <span>Lvl {combatant.level}</span>
                          <span>HP {combatant.hpMax}</span>
                          <span>RK {combatant.ac}</span>
                          <span className="hidden sm:inline">
                            Rett: +{combatant.fortitude}/+{combatant.reflex}/+{combatant.will}
                          </span>
                        </div>
                        {combatant.abilities && combatant.abilities.length > 0 && (
                          <p className="text-xs text-text-secondary mt-1">
                            {combatant.abilities.length} Fähigkeit{combatant.abilities.length > 1 ? 'en' : ''}
                          </p>
                        )}
                      </div>
                    </div>

                    {/* Actions */}
                    <div className="flex items-center gap-2 flex-shrink-0">
                      <button
                        onClick={() => {
                          if (confirm('NPC wirklich löschen?')) {
                            deleteCombatantMutation.mutate(combatant.id);
                          }
                        }}
                        className="p-2 text-text-secondary hover:text-red-400 transition-colors"
                      >
                        <Trash2 className="w-5 h-5" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </main>

      {/* Modals */}
      {showUploadMap && (
        <UploadMapModal
          onClose={() => setShowUploadMap(false)}
          onUpload={(data) => uploadMapMutation.mutate(data)}
          isLoading={uploadMapMutation.isPending}
        />
      )}

      {showCreateCombatant && (
        <CreateCombatantModal
          onClose={() => setShowCreateCombatant(false)}
          onCreate={(data) => createCombatantMutation.mutate(data)}
          isLoading={createCombatantMutation.isPending}
        />
      )}
    </div>
  );
}
