// app/(app)/staff/email-logs/EmailLogsClient.tsx
'use client';

import React, { useState, useEffect } from 'react';
import { PageTitle } from '@/components/PageTitle';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { RefreshCw, Search, Download, Mail, Clock, CheckCircle, XCircle, Zap, Eye } from 'lucide-react';
import EmailLogDetailModal from '@/components/staff/EmailLogDetailModal';

interface EmailLog {
  id: string;
  sender_email: string;
  recipient_email: string;
  cc_emails: string[] | null;
  subject: string;
  email_type: string;
  template_name: string | null;
  email_status: 'sending' | 'sent' | 'failed' | 'bounced' | 'complained';
  ses_message_id: string | null;
  failure_reason: string | null;
  sent_at: string | null;
  created_at: string;
  organization_id: string | null;
  contract_id: string | null;
  tags: Record<string, any> | null;
  context: Record<string, any> | null;
}

interface EmailStats {
  total: number;
  sent: number;
  failed: number;
  sending: number;
  successRate: number;
}

interface EmailLogsClientProps {
  initialLogs: EmailLog[];
  initialCount: number;
  initialStats: EmailStats;
}

export default function EmailLogsClient({ initialLogs, initialCount, initialStats }: EmailLogsClientProps) {
  const [logs, setLogs] = useState<EmailLog[]>(initialLogs);
  const [stats, setStats] = useState<EmailStats>(initialStats);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(Math.ceil(initialCount / 20));
  const [selectedLog, setSelectedLog] = useState<EmailLog | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const itemsPerPage = 20;

  // Charger les données au montage
  useEffect(() => {
    // Charger les données seulement si on a des filtres ou une pagination différente
    if (searchTerm || statusFilter !== 'all' || typeFilter !== 'all' || currentPage !== 1) {
      loadEmailLogs();
    }
  }, [searchTerm, statusFilter, typeFilter, currentPage]);

  const loadEmailLogs = async () => {
    try {
      setLoading(true);
      
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: itemsPerPage.toString(),
        ...(searchTerm && { search: searchTerm }),
        ...(statusFilter !== 'all' && { status: statusFilter }),
        ...(typeFilter !== 'all' && { type: typeFilter })
      });

      const response = await fetch(`/api/staff/email-logs?${params}`);
      const data = await response.json();

      if (!response.ok) {
        console.error('Erreur lors du chargement des logs:', data.error);
        return;
      }

      setLogs(data.logs || []);
      setTotalPages(Math.ceil((data.count || 0) / itemsPerPage));
    } catch (error) {
      console.error('Erreur lors du chargement des logs:', error);
    } finally {
      setLoading(false);
    }
  };

  const refreshData = async () => {
    await Promise.all([loadEmailLogs()]);
  };

  const openLogDetail = (log: EmailLog) => {
    setSelectedLog(log);
    setIsModalOpen(true);
  };

  const closeLogDetail = () => {
    setSelectedLog(null);
    setIsModalOpen(false);
  };

  // Recharger les logs quand les filtres changent
  useEffect(() => {
    if (logs.length > 0 || !loading) { // Éviter le double chargement initial
      setCurrentPage(1); // Reset à la première page
      loadEmailLogs();
    }
  }, [searchTerm, statusFilter, typeFilter]);

  // Recharger les logs quand la page change
  useEffect(() => {
    if (logs.length > 0 || !loading) { // Éviter le double chargement initial
      loadEmailLogs();
    }
  }, [currentPage]);

  const exportLogs = async () => {
    try {
      const params = new URLSearchParams({
        page: '1',
        limit: '10000', // Grande limite pour l'export
        ...(searchTerm && { search: searchTerm }),
        ...(statusFilter !== 'all' && { status: statusFilter }),
        ...(typeFilter !== 'all' && { type: typeFilter })
      });

      const response = await fetch(`/api/staff/email-logs?${params}`);
      const data = await response.json();

      if (!response.ok) {
        console.error('Erreur lors de l\'export des logs:', data.error);
        return;
      }

      const allLogs = data.logs || [];

      // Créer le CSV
      const csvHeader = [
        'Date création', 'Date envoi', 'Expéditeur', 'Destinataire', 'CC', 
        'Sujet', 'Type', 'Template', 'Statut', 'ID SES', 'Erreur', 
        'Organisation', 'Contrat'
      ].join(',');

      const csvRows = allLogs.map((log: EmailLog) => [
        new Date(log.created_at).toLocaleString('fr-FR'),
        log.sent_at ? new Date(log.sent_at).toLocaleString('fr-FR') : '',
        log.sender_email,
        log.recipient_email,
        log.cc_emails?.join('; ') || '',
        `"${log.subject.replace(/"/g, '""')}"`, // Échapper les guillemets
        log.email_type,
        log.template_name || '',
        log.email_status,
        log.ses_message_id || '',
        log.failure_reason ? `"${log.failure_reason.replace(/"/g, '""')}"` : '',
        log.organization_id || '',
        log.contract_id || ''
      ].join(','));

      const csvContent = [csvHeader, ...csvRows].join('\n');
      
      // Télécharger le fichier
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `email-logs-${new Date().toISOString().split('T')[0]}.csv`;
      link.click();
    } catch (error) {
      console.error('Erreur lors de l\'export:', error);
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'sent': return <CheckCircle className="h-4 w-4 text-green-500" />;
      case 'failed': return <XCircle className="h-4 w-4 text-red-500" />;
      case 'sending': return <Zap className="h-4 w-4 text-yellow-500" />;
      default: return <Clock className="h-4 w-4 text-gray-500" />;
    }
  };

  const getStatusBadge = (status: string) => {
    const statusStyles: Record<string, string> = {
      sent: 'bg-green-100 text-green-800 border-green-200',
      failed: 'bg-red-100 text-red-800 border-red-200', 
      sending: 'bg-yellow-100 text-yellow-800 border-yellow-200',
      bounced: 'bg-red-100 text-red-800 border-red-200',
      complained: 'bg-gray-100 text-gray-800 border-gray-200'
    };
    
    return (
      <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 text-xs font-semibold rounded-full border ${statusStyles[status] || 'bg-gray-100 text-gray-800 border-gray-200'}`}>
        {getStatusIcon(status)}
        {status}
      </span>
    );
  };

  return (
    <div className="space-y-6">
      <PageTitle 
        title="Logs des emails" 
      />

      {/* Statistiques */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total</CardTitle>
            <Mail className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total.toLocaleString()}</div>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Envoyés</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{stats.sent.toLocaleString()}</div>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Échecs</CardTitle>
            <XCircle className="h-4 w-4 text-red-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">{stats.failed.toLocaleString()}</div>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Taux de succès</CardTitle>
            <Zap className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">{stats.successRate.toFixed(1)}%</div>
          </CardContent>
        </Card>
      </div>

      {/* Filtres et actions */}
      <Card>
        <CardHeader>
          <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
            <div className="flex flex-col sm:flex-row gap-2 flex-1">
              <div className="relative flex-1 max-w-sm">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Rechercher par email, sujet..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-8"
                />
              </div>
              
              <select 
                value={statusFilter} 
                onChange={(e) => setStatusFilter(e.target.value)}
                className="h-10 w-40 rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
              >
                <option value="all">Tous les statuts</option>
                <option value="sending">En cours</option>
                <option value="sent">Envoyés</option>
                <option value="failed">Échecs</option>
                <option value="bounced">Rebonds</option>
                <option value="complained">Plaintes</option>
              </select>
              
              <select 
                value={typeFilter} 
                onChange={(e) => setTypeFilter(e.target.value)}
                className="h-10 w-48 rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
              >
                <option value="all">Tous les types</option>
                <option value="bulk_communication">Communications groupées</option>
                <option value="contract_signature">Signature contrat</option>
                <option value="password_reset">Réinitialisation mot de passe</option>
                <option value="account_activation">Activation compte</option>
                <option value="invoice_generated">Facture générée</option>
                <option value="system_notification">Notification système</option>
              </select>
            </div>
            
            <div className="flex gap-2">
              <Button onClick={refreshData} variant="outline" size="sm">
                <RefreshCw className="h-4 w-4 mr-2" />
                Actualiser
              </Button>
              <Button onClick={exportLogs} variant="outline" size="sm">
                <Download className="h-4 w-4 mr-2" />
                Exporter CSV
              </Button>
            </div>
          </div>
        </CardHeader>
        
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center py-8">
              <RefreshCw className="h-6 w-6 animate-spin" />
              <span className="ml-2">Chargement...</span>
            </div>
          ) : logs.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              Aucun log trouvé pour les critères sélectionnés
            </div>
          ) : (
            <div className="space-y-4">
              {/* Liste des logs */}
              <div className="space-y-2">
                {logs.map((log) => (
                  <div 
                    key={log.id} 
                    className="group border rounded-lg p-4 hover:bg-muted/50 cursor-pointer transition-all hover:shadow-md"
                    onClick={() => openLogDetail(log)}
                  >
                    <div className="flex flex-col sm:flex-row gap-4 items-start">
                      <div className="flex-1 space-y-1">
                        <div className="flex items-center gap-2">
                          {getStatusBadge(log.email_status)}
                          <span className="text-sm font-medium">{log.email_type}</span>
                          {log.template_name && (
                            <span className="inline-flex items-center px-2.5 py-0.5 text-xs font-semibold rounded-full border bg-gray-100 text-gray-800 border-gray-200">
                              {log.template_name}
                            </span>
                          )}
                        </div>
                        
                        <div className="text-sm">
                          <span className="font-medium">À:</span> {log.recipient_email}
                          {log.cc_emails && log.cc_emails.length > 0 && (
                            <>
                              <span className="ml-2 font-medium">CC:</span> {log.cc_emails.join(', ')}
                            </>
                          )}
                        </div>
                        
                        <div className="text-sm text-muted-foreground">
                          <span className="font-medium">Sujet:</span> {log.subject}
                        </div>
                        
                        {log.failure_reason && (
                          <div className="text-sm text-red-600">
                            <span className="font-medium">Erreur:</span> {log.failure_reason}
                          </div>
                        )}
                      </div>
                      
                      <div className="text-right text-sm text-muted-foreground space-y-1">
                        <div>
                          <span className="font-medium">Créé:</span>{' '}
                          {new Date(log.created_at).toLocaleString('fr-FR')}
                        </div>
                        {log.sent_at && (
                          <div>
                            <span className="font-medium">Envoyé:</span>{' '}
                            {new Date(log.sent_at).toLocaleString('fr-FR')}
                          </div>
                        )}
                        {log.ses_message_id && (
                          <div className="text-xs">
                            <span className="font-medium">SES ID:</span> {log.ses_message_id.substring(0, 12)}...
                          </div>
                        )}
                        <div className="pt-2">
                          <Button 
                            variant="outline" 
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              openLogDetail(log);
                            }}
                            className="opacity-0 group-hover:opacity-100 transition-opacity"
                          >
                            <Eye className="h-4 w-4 mr-1" />
                            Voir détails
                          </Button>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
              
              {/* Pagination */}
              {totalPages > 1 && (
                <div className="flex items-center justify-between">
                  <div className="text-sm text-muted-foreground">
                    Page {currentPage} sur {totalPages}
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                      disabled={currentPage === 1}
                    >
                      Précédent
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                      disabled={currentPage === totalPages}
                    >
                      Suivant
                    </Button>
                  </div>
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Modal de détails */}
      <EmailLogDetailModal 
        log={selectedLog}
        isOpen={isModalOpen}
        onClose={closeLogDetail}
      />
    </div>
  );
}