import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  ArrowLeft,
  Settings,
  Users,
  Swords,
  UserPlus,
  Trash2,
  Crown,
  Shield,
  Heart,
  FileJson
} from 'lucide-react';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Spinner
} from '@/shared/components/ui';
import { api } from '@/shared/lib/api';
import { useAuthStore } from '@/features/auth';
import type { Campaign, CharacterSummary } from '@/shared/types';
import { AddMemberModal } from './add-member-modal';
import { EditCampaignModal } from './edit-campaign-modal';
import { CreateCharacterModal, ImportCharacterModal } from '@/features/characters';

export function CampaignDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { user } = useAuthStore();

  const [campaign, setCampaign] = useState<Campaign | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [showAddMember, setShowAddMember] = useState(false);
  const [showEditCampaign, setShowEditCampaign] = useState(false);
  const [showCreateCharacter, setShowCreateCharacter] = useState(false);
  const [showImportCharacter, setShowImportCharacter] = useState(false);

  const isGM = campaign?.gmId === user?.id;
  const isAdmin = user?.role === 'ADMIN';
  const canManage = isGM || isAdmin;

  const fetchCampaign = async () => {
    if (!id) return;
    try {
      const data = await api.getCampaign(id);
      setCampaign(data);
    } catch (error) {
      console.error('Failed to fetch campaign:', error);
      navigate('/');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchCampaign();
  }, [id]);

  const handleRemoveMember = async (userId: string) => {
    if (!id || !confirm('Mitglied wirklich entfernen?')) return;
    try {
      await api.removeCampaignMember(id, userId);
      fetchCampaign();
    } catch (error) {
      console.error('Failed to remove member:', error);
    }
  };

  const handleDeleteCampaign = async () => {
    if (!id || !confirm('Kampagne wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.')) return;
    try {
      await api.deleteCampaign(id);
      navigate('/');
    } catch (error) {
      console.error('Failed to delete campaign:', error);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Spinner size="lg" />
      </div>
    );
  }

  if (!campaign) {
    return (
      <div className="text-center py-12">
        <p className="text-text-secondary">Kampagne nicht gefunden</p>
      </div>
    );
  }

  return (
    <div className="space-y-6 overflow-x-hidden">
      {/* Header */}
      <div className="space-y-4">
        <div className="flex items-start gap-3">
          <Button variant="ghost" size="icon" onClick={() => navigate('/')} className="flex-shrink-0">
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div className="min-w-0 flex-1">
            <h1 className="text-xl sm:text-2xl font-bold text-text-primary truncate">{campaign.name}</h1>
            {campaign.description && (
              <p className="text-text-secondary mt-1 text-sm sm:text-base line-clamp-2">{campaign.description}</p>
            )}
            <div className="flex items-center gap-2 mt-2 text-sm text-text-secondary">
              <Crown className="h-4 w-4 text-primary-500 flex-shrink-0" />
              <span className="truncate">GM: {campaign.gm.username}</span>
            </div>
          </div>
        </div>
        {canManage && (
          <div className="flex items-center gap-2 ml-11 sm:ml-0 sm:justify-end">
            <Button variant="outline" size="sm" onClick={() => setShowEditCampaign(true)}>
              <Settings className="h-4 w-4" />
              <span className="hidden sm:inline ml-1">Bearbeiten</span>
            </Button>
            <Button variant="destructive" size="sm" onClick={handleDeleteCampaign}>
              <Trash2 className="h-4 w-4" />
            </Button>
          </div>
        )}
      </div>

      {/* Campaign Image */}
      {campaign.imageUrl && (
        <div className="h-48 rounded-xl overflow-hidden bg-bg-tertiary">
          <img
            src={campaign.imageUrl}
            alt={campaign.name}
            className="w-full h-full object-cover"
          />
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6 w-full">
        {/* Members Section */}
        <Card>
          <CardHeader className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <CardTitle className="flex items-center gap-2">
              <Users className="h-5 w-5" />
              Mitglieder ({campaign.members.length})
            </CardTitle>
            {canManage && (
              <Button size="sm" onClick={() => setShowAddMember(true)} className="w-full sm:w-auto">
                <UserPlus className="h-4 w-4" />
                Hinzufügen
              </Button>
            )}
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {campaign.members.map((member) => (
                <div
                  key={member.userId}
                  className="flex items-center justify-between gap-2 p-2 sm:p-3 rounded-lg bg-bg-tertiary overflow-hidden"
                >
                  <div className="flex items-center gap-2 sm:gap-3 min-w-0 flex-1 overflow-hidden">
                    <div className="h-8 w-8 sm:h-10 sm:w-10 rounded-full bg-primary-500/20 flex items-center justify-center flex-shrink-0">
                      {member.user.avatarUrl ? (
                        <img
                          src={member.user.avatarUrl}
                          alt={member.user.username}
                          className="h-8 w-8 sm:h-10 sm:w-10 rounded-full object-cover"
                        />
                      ) : (
                        <span className="text-primary-500 font-medium text-sm">
                          {member.user.username.charAt(0).toUpperCase()}
                        </span>
                      )}
                    </div>
                    <div className="min-w-0 flex-1 overflow-hidden">
                      <p className="font-medium text-text-primary flex items-center gap-1 sm:gap-2 text-sm sm:text-base">
                        <span className="truncate">{member.user.username}</span>
                        {member.userId === campaign.gmId && (
                          <Crown className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary-500 flex-shrink-0" />
                        )}
                      </p>
                      <p className="text-xs sm:text-sm text-text-secondary truncate">{member.user.email}</p>
                    </div>
                  </div>
                  {canManage && member.userId !== campaign.gmId && (
                    <Button
                      variant="ghost"
                      size="icon"
                      className="flex-shrink-0 h-8 w-8"
                      onClick={() => handleRemoveMember(member.userId)}
                    >
                      <Trash2 className="h-4 w-4 text-text-secondary hover:text-red-500" />
                    </Button>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Characters Section */}
        <Card>
          <CardHeader className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <CardTitle className="flex items-center gap-2">
              <Swords className="h-5 w-5" />
              Charaktere ({campaign.characters?.length || 0})
            </CardTitle>
            <div className="grid grid-cols-2 sm:flex sm:items-center gap-2">
              <Button size="sm" variant="outline" onClick={() => setShowImportCharacter(true)}>
                <FileJson className="h-4 w-4" />
                <span className="ml-1">Import</span>
              </Button>
              <Button size="sm" onClick={() => setShowCreateCharacter(true)}>
                <UserPlus className="h-4 w-4" />
                <span className="ml-1">Neu</span>
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {!campaign.characters?.length ? (
              <div className="text-center py-8">
                <Swords className="h-8 w-8 text-text-secondary mx-auto mb-2" />
                <p className="text-text-secondary">Noch keine Charaktere</p>
              </div>
            ) : (
              <div className="space-y-2">
                {campaign.characters.map((character: CharacterSummary) => (
                  <div
                    key={character.id}
                    className="flex items-center justify-between gap-2 p-2 sm:p-3 rounded-lg bg-bg-tertiary hover:bg-bg-elevated cursor-pointer transition-colors overflow-hidden"
                    onClick={() => navigate(`/campaigns/${id}/characters/${character.id}`)}
                  >
                    <div className="flex items-center gap-2 sm:gap-3 min-w-0 flex-1 overflow-hidden">
                      <div className="h-8 w-8 sm:h-10 sm:w-10 rounded-full bg-primary-500/20 flex items-center justify-center flex-shrink-0">
                        {character.avatarUrl ? (
                          <img
                            src={character.avatarUrl}
                            alt={character.name}
                            className="h-8 w-8 sm:h-10 sm:w-10 rounded-full object-cover"
                          />
                        ) : (
                          <Shield className="h-4 w-4 sm:h-5 sm:w-5 text-primary-500" />
                        )}
                      </div>
                      <div className="min-w-0 flex-1 overflow-hidden">
                        <p className="font-medium text-text-primary truncate text-sm sm:text-base">{character.name}</p>
                        <p className="text-xs sm:text-sm text-text-secondary truncate">
                          Lv. {character.level} {character.type}
                          {character.owner && ` • ${character.owner.username}`}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-1 text-xs sm:text-sm flex-shrink-0">
                      <Heart className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-red-500" />
                      <span className={character.hpCurrent < character.hpMax / 2 ? 'text-red-500' : 'text-text-secondary'}>
                        {character.hpCurrent}/{character.hpMax}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Quick Actions */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
        <Card className="p-4 hover:border-border-hover cursor-pointer transition-colors active:scale-[0.98]" onClick={() => navigate(`/campaigns/${id}/battle`)}>
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-lg bg-red-500/20 flex items-center justify-center flex-shrink-0">
              <Swords className="h-5 w-5 text-red-500" />
            </div>
            <div className="min-w-0">
              <p className="font-medium text-text-primary">Kampfbildschirm</p>
              <p className="text-sm text-text-secondary">Kämpfe verwalten</p>
            </div>
          </div>
        </Card>
        <Card className="p-4 hover:border-border-hover cursor-pointer transition-colors opacity-50">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-lg bg-blue-500/20 flex items-center justify-center flex-shrink-0">
              <Users className="h-5 w-5 text-blue-500" />
            </div>
            <div className="min-w-0">
              <p className="font-medium text-text-primary">Dokumente</p>
              <p className="text-sm text-text-secondary">Bald verfügbar</p>
            </div>
          </div>
        </Card>
        <Card className="p-4 hover:border-border-hover cursor-pointer transition-colors opacity-50">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-lg bg-green-500/20 flex items-center justify-center flex-shrink-0">
              <Users className="h-5 w-5 text-green-500" />
            </div>
            <div className="min-w-0">
              <p className="font-medium text-text-primary">Notizen</p>
              <p className="text-sm text-text-secondary">Bald verfügbar</p>
            </div>
          </div>
        </Card>
      </div>

      {/* Modals */}
      {showAddMember && (
        <AddMemberModal
          campaignId={campaign.id}
          onClose={() => setShowAddMember(false)}
          onMemberAdded={fetchCampaign}
        />
      )}
      {showEditCampaign && (
        <EditCampaignModal
          campaign={campaign}
          onClose={() => setShowEditCampaign(false)}
          onUpdated={fetchCampaign}
        />
      )}
      {showCreateCharacter && (
        <CreateCharacterModal
          campaignId={campaign.id}
          onClose={() => setShowCreateCharacter(false)}
          onCreated={fetchCampaign}
        />
      )}
      {showImportCharacter && (
        <ImportCharacterModal
          campaignId={campaign.id}
          onClose={() => setShowImportCharacter(false)}
          onImported={fetchCampaign}
        />
      )}
    </div>
  );
}
