'use client';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Campaign, CampaignWithStats } from '@/types';
import { campaignService } from '@/lib/services';
import { authService } from '@/lib/auth';
import CreateCampaignModal from '@/components/CreateCampaignModal';
import EditCampaignModal from '@/components/EditCampaignModal';
import DeleteCampaignModal from '@/components/DeleteCampaignModal';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';


import AuthGuard from '@/components/AuthGuard';
import { FolderOpen, Users, FileText, Plus, BarChart3, Settings, Check, Copy } from 'lucide-react';
import StatusSwitch from '@/components/StatusSwitch';
import { MarkdownContent } from '@/components/MarkdownContent';

export const dynamic = 'force-dynamic';

function AdminPageContent() {
  const [campaigns, setCampaigns] = useState<CampaignWithStats[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedCampaign, setSelectedCampaign] = useState<Campaign | null>(null);

  const [copiedCampaignId, setCopiedCampaignId] = useState<string | null>(null);

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

  const loadCampaigns = async () => {
    try {
      setLoading(true);
      const campaignsData = await campaignService.getAll();
      const campaignsWithStats = await Promise.all(
        campaignsData.map(async (campaign) => {
          const stats = await campaignService.getStats(campaign.id);
          return {
            ...campaign,
            stats
          };
        })
      );
      setCampaigns(campaignsWithStats);
    } catch (error) {
      console.error('Erreur lors du chargement des campagnes:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleCampaignEdited = () => {
    setShowEditModal(false);
    loadCampaigns();
  };

  const handleCampaignDeleted = () => {
    setShowDeleteModal(false);
    loadCampaigns();
  };

  const handleStatusChange = async (campaignId: string, newStatus: 'deposit' | 'voting' | 'closed') => {
    try {
      await campaignService.update(campaignId, { status: newStatus });
      // Mettre à jour l'état local sans recharger toute la page
      setCampaigns(prevCampaigns => 
        prevCampaigns.map(campaign => 
          campaign.id === campaignId 
            ? { ...campaign, status: newStatus }
            : campaign
        )
      );
    } catch (error) {
      console.error('Erreur lors du changement de statut:', error);
      throw error; // Propager l'erreur pour que le composant puisse la gérer
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'deposit':
        return <Badge variant="secondary">Dépôt de propositions</Badge>;
      case 'voting':
        return <Badge variant="default">En cours de vote</Badge>;
      case 'closed':
        return <Badge variant="outline">Terminée</Badge>;
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };



  const copyToClipboard = async (text: string, campaignId: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedCampaignId(campaignId);
      setTimeout(() => setCopiedCampaignId(null), 2000);
    } catch (error) {
      console.error('Erreur lors de la copie:', error);
      // Fallback pour les navigateurs qui ne supportent pas l'API Clipboard
      const textArea = document.createElement('textarea');
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.select();
      try {
        document.execCommand('copy');
        setCopiedCampaignId(campaignId);
        setTimeout(() => setCopiedCampaignId(null), 2000);
      } catch (fallbackError) {
        console.error('Erreur avec la méthode de fallback:', fallbackError);
      }
      document.body.removeChild(textArea);
    }
  };





  if (loading) {
    return (
      <div className="min-h-screen bg-slate-50 dark:bg-slate-900">
        <div className="container mx-auto px-4 py-8">
          <div className="flex items-center justify-center h-64">
            <div className="text-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-slate-900 dark:border-slate-100 mx-auto mb-4"></div>
              <p className="text-slate-600 dark:text-slate-300">Chargement des campagnes...</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-900">
      <div className="container mx-auto px-4 py-8">
        
                {/* Header */}
        <div className="mb-10">
          <div className="relative overflow-hidden rounded-2xl bg-gradient-to-br from-slate-50 via-white to-gray-50 dark:from-slate-800 dark:via-slate-900 dark:to-slate-800 border border-slate-200 dark:border-slate-700">
            <div className="absolute inset-0 bg-grid-slate-100 dark:bg-grid-slate-800 [mask-image:linear-gradient(0deg,white,rgba(255,255,255,0.6))] dark:[mask-image:linear-gradient(0deg,rgba(255,255,255,0.1),rgba(255,255,255,0.05))]" />
            <div className="relative p-8">
              <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6">
                <div className="space-y-2">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-slate-100 dark:bg-slate-800 rounded-xl flex items-center justify-center">
                      <svg className="w-5 h-5 text-slate-600 dark:text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                    </div>
                    <div>
                      <h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100">
                        Mes Budgets Participatifs
                      </h1>
                      <p className="text-slate-600 dark:text-slate-400 font-medium">Administration</p>
                    </div>
                  </div>
                  <p className="text-slate-600 dark:text-slate-400 max-w-2xl">
                    Gérez vos campagnes de budget participatif, suivez les votes et analysez les résultats
                  </p>
                </div>
                <div className="flex flex-col sm:flex-row gap-3">
                  <Button
                    onClick={() => setShowCreateModal(true)}
                    size="lg"
                    className="bg-slate-900 hover:bg-slate-800 text-white shadow-lg hover:shadow-xl transition-all duration-200"
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    Nouvelle campagne
                  </Button>
                  <div className="flex gap-2">
                    <Button
                      asChild
                      variant="outline"
                      size="lg"
                      className="border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800 transition-all duration-200"
                    >
                      <Link href="/admin/settings">
                        <Settings className="w-4 h-4 mr-2" />
                        Paramètres
                      </Link>
                    </Button>
                    <Button
                      variant="outline"
                      size="lg"
                      className="border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800 transition-all duration-200"
                      onClick={async () => {
                        try {
                          await authService.signOut();
                          window.location.href = '/';
                        } catch (error) {
                          console.error('Erreur lors de la déconnexion:', error);
                        }
                      }}
                    >
                      Déconnexion
                    </Button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>





        {/* Campaigns List */}
                {campaigns.length === 0 ? (
          <div className="text-center py-16">
            <div className="w-20 h-20 bg-gradient-to-br from-slate-50 to-gray-100 dark:from-slate-800 dark:to-slate-700 rounded-2xl flex items-center justify-center mx-auto mb-6">
              <FolderOpen className="w-10 h-10 text-slate-600 dark:text-slate-400" />
            </div>
            <h3 className="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-3">
              Aucune campagne
            </h3>
            <p className="text-slate-600 dark:text-slate-400 mb-8 max-w-md mx-auto">
              Créez votre première campagne de budget participatif pour commencer à collecter les idées de votre communauté
            </p>
            <Button
              onClick={() => setShowCreateModal(true)}
              size="lg"
              className="bg-slate-900 hover:bg-slate-800 text-white shadow-lg hover:shadow-xl transition-all duration-200"
            >
              <Plus className="w-4 h-4 mr-2" />
              Créer une campagne
            </Button>
          </div>
        ) : (
          <div className="grid gap-6 group/campaigns">
            {campaigns.map((campaign) => (
              <Card key={campaign.id} className="group hover:shadow-xl hover:shadow-slate-100 dark:hover:shadow-slate-900/20 transition-all duration-300 border-slate-200 dark:border-slate-700 overflow-hidden group-hover/campaigns:opacity-30 hover:!opacity-100">
                <div className="relative">
                  
                  <CardHeader className="pb-4">
                    <div className="flex items-start justify-between">
                      <div className="flex-1 space-y-4">
                        <div className="flex items-start gap-3">
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-3 mb-2">
                              <CardTitle className="text-xl font-bold text-slate-900 dark:text-slate-100 group-hover:text-slate-600 dark:group-hover:text-slate-400 transition-colors duration-200">
                                {campaign.title}
                              </CardTitle>
                            </div>
                            <CardDescription className="text-slate-600 dark:text-slate-400 text-sm leading-relaxed mb-4">
                              <MarkdownContent content={campaign.description} />
                            </CardDescription>
                            
                            {/* Status Switch */}
                            <div className="mb-4">
                              <StatusSwitch
                                currentStatus={campaign.status}
                                onStatusChange={(newStatus) => handleStatusChange(campaign.id, newStatus)}
                              />
                            </div>
                          </div>
                        </div>
                        
                        {/* Stats avec icônes modernes et boutons intégrés */}
                        <div className="mb-3">
                          <p className="text-xs text-slate-500 dark:text-slate-400 text-center">
                            Cliquez sur les éléments pour les gérer
                          </p>
                        </div>
                        <div className="grid grid-cols-3 gap-4 pt-2">
                          <Button 
                            asChild 
                            variant="ghost" 
                            className="h-auto p-3 bg-slate-50 dark:bg-slate-800/50 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-lg border-0 group relative"
                          >
                            <Link href={`/admin/campaigns/${campaign.id}/propositions`}>
                              <div className="flex items-center gap-2 w-full">
                                <div className="w-8 h-8 bg-slate-100 dark:bg-slate-800 rounded-lg flex items-center justify-center">
                                  <FileText className="w-4 h-4 text-slate-600 dark:text-slate-400" />
                                </div>
                                <div className="text-left">
                                  <div className="text-lg font-bold text-slate-900 dark:text-slate-100">
                                    {campaign.stats.propositions}
                                  </div>
                                  <div className="text-xs text-slate-500 dark:text-slate-400">Propositions</div>
                                </div>
                                <div className="ml-auto opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                                  <svg className="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                  </svg>
                                </div>
                              </div>
                            </Link>
                          </Button>
                          
                          <Button 
                            asChild 
                            variant="ghost" 
                            className="h-auto p-3 bg-slate-50 dark:bg-slate-800/50 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-lg border-0 group relative"
                          >
                            <Link href={`/admin/campaigns/${campaign.id}/participants`}>
                              <div className="flex items-center gap-2 w-full">
                                <div className="w-8 h-8 bg-slate-100 dark:bg-slate-800 rounded-lg flex items-center justify-center">
                                  <Users className="w-4 h-4 text-slate-600 dark:text-slate-400" />
                                </div>
                                <div className="text-left">
                                  <div className="text-lg font-bold text-slate-900 dark:text-slate-100">
                                    {campaign.stats.participants}
                                  </div>
                                  <div className="text-xs text-slate-500 dark:text-slate-400">Participants</div>
                                </div>
                                <div className="ml-auto opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                                  <svg className="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                  </svg>
                                </div>
                              </div>
                            </Link>
                          </Button>
                          
                          <div className="flex items-center gap-2 p-3 bg-slate-50 dark:bg-slate-800/50 rounded-lg">
                                                         <div className="w-8 h-8 bg-slate-100 dark:bg-slate-800 rounded-lg flex items-center justify-center">
                               <BarChart3 className="w-4 h-4 text-slate-600 dark:text-slate-400" />
                            </div>
                            <div>
                              <div className="text-lg font-bold text-slate-900 dark:text-slate-100">
                                {campaign.budget_per_user}€
                              </div>
                              <div className="text-xs text-slate-500 dark:text-slate-400">Budget</div>
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      {/* Boutons discrets en haut à droite */}
                      <div className="flex gap-1 ml-4">
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-8 w-8 p-0 text-slate-400 hover:text-slate-600 hover:bg-slate-100 dark:hover:bg-slate-800"
                          onClick={() => {
                            setSelectedCampaign(campaign);
                            setShowEditModal(true);
                          }}
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                          </svg>
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-8 w-8 p-0 text-slate-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20"
                          onClick={() => {
                            setSelectedCampaign(campaign);
                            setShowDeleteModal(true);
                          }}
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                          </svg>
                        </Button>
                      </div>
                    </div>
                                    </CardHeader>
                  
                  <CardContent className="pt-0">
                    {/* Section actions - même espace pour lien public et statistiques */}
                    <div className="space-y-4">
                      {/* Lien public OU Bouton Statistiques */}
                      {campaign.status === 'deposit' ? (
                        /* Lien public pour les campagnes en dépôt */
                        <div className="p-3 bg-slate-50 dark:bg-slate-800/30 border border-slate-200 dark:border-slate-700 rounded-lg">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                              <svg className="w-4 h-4 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
                              </svg>
                              <span className="text-sm text-slate-600 dark:text-slate-400">Lien public pour déposer une proposition</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <div className="text-xs text-slate-500 dark:text-slate-400 font-mono">
                                {`${window.location.origin}/p/${campaign.slug || 'campagne'}`}
                              </div>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-7 w-7 p-0 text-slate-400 hover:text-slate-600"
                                onClick={() => {
                                  copyToClipboard(`${window.location.origin}/p/${campaign.slug || 'campagne'}`, campaign.id);
                                }}
                              >
                                {copiedCampaignId === campaign.id ? (
                                  <Check className="w-3 h-3" />
                                ) : (
                                  <Copy className="w-3 h-3" />
                                )}
                              </Button>
                            </div>
                          </div>
                        </div>
                      ) : (campaign.status === 'voting' || campaign.status === 'closed') ? (
                        /* Bouton Statistiques pour les campagnes en vote/fermées */
                        <div className="flex justify-center">
                          <Button asChild variant="outline" className="border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-300">
                            <Link href={`/admin/campaigns/${campaign.id}/stats`}>
                              <BarChart3 className="w-4 h-4 mr-2" />
                              Voir les statistiques
                            </Link>
                          </Button>
                        </div>
                      ) : (
                        /* Espace vide pour les autres statuts */
                        <div className="h-12"></div>
                      )}
                    </div>
                  </CardContent>
                </div>
              </Card>
            ))}
          </div>
        )}

        {/* Modals */}
        <CreateCampaignModal isOpen={showCreateModal} onClose={() => setShowCreateModal(false)} onSuccess={handleCampaignCreated} />
        {selectedCampaign && (
          <EditCampaignModal isOpen={showEditModal} onClose={() => setShowEditModal(false)} onSuccess={handleCampaignEdited} campaign={selectedCampaign} />
        )}
        {selectedCampaign && (
          <DeleteCampaignModal isOpen={showDeleteModal} onClose={() => setShowDeleteModal(false)} onSuccess={handleCampaignDeleted} campaign={selectedCampaign} />
        )}
      </div>
    </div>
  );
}

export default function AdminPage() {
  return (
    <AuthGuard>
      <AdminPageContent />
    </AuthGuard>
  );
}
