import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Plus, Users, Swords } from 'lucide-react';
import { Button, Card, CardHeader, CardTitle, CardDescription, CardContent, Spinner } from '@/shared/components/ui';
import { api } from '@/shared/lib/api';
import type { Campaign } from '@/shared/types';
import { CreateCampaignModal } from './create-campaign-modal';

export function CampaignsPage() {
  const [campaigns, setCampaigns] = useState<Campaign[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showCreateModal, setShowCreateModal] = useState(false);

  const fetchCampaigns = async () => {
    try {
      const data = await api.getCampaigns();
      setCampaigns(data);
    } catch (error) {
      console.error('Failed to fetch campaigns:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchCampaigns();
  }, []);

  const handleCampaignCreated = () => {
    setShowCreateModal(false);
    fetchCampaigns();
  };

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

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-text-primary">Kampagnen</h1>
          <p className="text-text-secondary mt-1">
            Verwalte deine Pathfinder 2e Kampagnen
          </p>
        </div>
        <Button onClick={() => setShowCreateModal(true)}>
          <Plus className="h-4 w-4" />
          Neue Kampagne
        </Button>
      </div>

      {/* Campaigns Grid */}
      {campaigns.length === 0 ? (
        <Card className="p-12 text-center">
          <div className="mx-auto h-12 w-12 rounded-xl bg-primary-500/10 flex items-center justify-center mb-4">
            <Swords className="h-6 w-6 text-primary-500" />
          </div>
          <h3 className="text-lg font-medium text-text-primary mb-2">
            Keine Kampagnen
          </h3>
          <p className="text-text-secondary mb-6">
            Erstelle deine erste Kampagne, um loszulegen.
          </p>
          <Button onClick={() => setShowCreateModal(true)}>
            <Plus className="h-4 w-4" />
            Kampagne erstellen
          </Button>
        </Card>
      ) : (
        <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {campaigns.map((campaign) => (
            <Link key={campaign.id} to={`/campaigns/${campaign.id}`}>
              <Card className="h-full hover:border-border-hover transition-colors cursor-pointer">
                {campaign.imageUrl ? (
                  <div className="h-32 bg-bg-tertiary rounded-t-xl overflow-hidden">
                    <img
                      src={campaign.imageUrl}
                      alt={campaign.name}
                      className="w-full h-full object-cover"
                    />
                  </div>
                ) : (
                  <div className="h-32 bg-gradient-to-br from-primary-500/20 to-secondary-800/20 rounded-t-xl flex items-center justify-center">
                    <Swords className="h-8 w-8 text-primary-500/50" />
                  </div>
                )}
                <CardHeader>
                  <CardTitle className="text-lg">{campaign.name}</CardTitle>
                  {campaign.description && (
                    <CardDescription className="line-clamp-2">
                      {campaign.description}
                    </CardDescription>
                  )}
                </CardHeader>
                <CardContent className="pt-0">
                  <div className="flex items-center gap-4 text-sm text-text-secondary">
                    <div className="flex items-center gap-1">
                      <Users className="h-4 w-4" />
                      <span>{campaign.members?.length || 0} Spieler</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Swords className="h-4 w-4" />
                      <span>{campaign._count?.characters || 0} Charaktere</span>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </Link>
          ))}
        </div>
      )}

      {/* Create Campaign Modal */}
      {showCreateModal && (
        <CreateCampaignModal
          onClose={() => setShowCreateModal(false)}
          onCreated={handleCampaignCreated}
        />
      )}
    </div>
  );
}
