'use client';

import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { X, Mail, Clock, User, Hash, Tag, AlertCircle, CheckCircle, XCircle, Zap, Copy, Eye, RefreshCw } from 'lucide-react';

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 EmailLogDetailModalProps {
  log: EmailLog | null;
  isOpen: boolean;
  onClose: () => void;
}

export default function EmailLogDetailModal({ log, isOpen, onClose }: EmailLogDetailModalProps) {
  const [htmlContent, setHtmlContent] = useState<string | null>(null);
  const [loadingContent, setLoadingContent] = useState(false);
  const [activeTab, setActiveTab] = useState<'details' | 'html' | 'raw'>('details');

  useEffect(() => {
    if (isOpen && log && activeTab === 'html') {
      loadEmailContent();
    }
  }, [isOpen, log, activeTab]);

  const loadEmailContent = async () => {
    if (!log) return;
    
    try {
      setLoadingContent(true);
      const response = await fetch(`/api/staff/email-logs/${log.id}/content`);
      
      if (response.ok) {
        const data = await response.json();
        setHtmlContent(data.html_content || '<p>Aucun contenu HTML disponible</p>');
      } else {
        setHtmlContent('<p>Erreur lors du chargement du contenu</p>');
      }
    } catch (error) {
      console.error('Erreur lors du chargement du contenu:', error);
      setHtmlContent('<p>Erreur lors du chargement du contenu</p>');
    } finally {
      setLoadingContent(false);
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'sent': return <CheckCircle className="h-5 w-5 text-green-500" />;
      case 'failed': return <XCircle className="h-5 w-5 text-red-500" />;
      case 'sending': return <Zap className="h-5 w-5 text-yellow-500" />;
      case 'bounced': return <AlertCircle className="h-5 w-5 text-red-500" />;
      case 'complained': return <AlertCircle className="h-5 w-5 text-orange-500" />;
      default: return <Clock className="h-5 w-5 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-orange-100 text-orange-800 border-orange-200'
    };
    
    return (
      <span className={`inline-flex items-center gap-2 px-3 py-1 text-sm font-semibold rounded-full border ${statusStyles[status] || 'bg-gray-100 text-gray-800 border-gray-200'}`}>
        {getStatusIcon(status)}
        {status}
      </span>
    );
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
  };

  if (!isOpen || !log) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b">
          <div className="flex items-center gap-3">
            <Mail className="h-6 w-6 text-blue-500" />
            <div>
              <h2 className="text-xl font-semibold">Détails de l'email</h2>
              <p className="text-sm text-gray-500">ID: {log.id}</p>
            </div>
          </div>
          <Button variant="ghost" size="sm" onClick={onClose}>
            <X className="h-5 w-5" />
          </Button>
        </div>

        {/* Tabs */}
        <div className="border-b">
          <div className="flex space-x-1 p-2">
            <button
              onClick={() => setActiveTab('details')}
              className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                activeTab === 'details' 
                  ? 'bg-blue-100 text-blue-700 border border-blue-200' 
                  : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'
              }`}
            >
              Détails
            </button>
            <button
              onClick={() => setActiveTab('html')}
              className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                activeTab === 'html' 
                  ? 'bg-blue-100 text-blue-700 border border-blue-200' 
                  : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'
              }`}
            >
              <Eye className="h-4 w-4 mr-1 inline" />
              Rendu HTML
            </button>
            <button
              onClick={() => setActiveTab('raw')}
              className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                activeTab === 'raw' 
                  ? 'bg-blue-100 text-blue-700 border border-blue-200' 
                  : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'
              }`}
            >
              Données brutes
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="p-6 overflow-y-auto max-h-[calc(90vh-180px)]">
          {activeTab === 'details' && (
            <div className="space-y-6">
              {/* Status et info principale */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="text-sm font-medium text-gray-500">Statut</CardTitle>
                  </CardHeader>
                  <CardContent>
                    {getStatusBadge(log.email_status)}
                    {log.failure_reason && (
                      <div className="mt-3 p-3 bg-red-50 border border-red-200 rounded-md">
                        <p className="text-sm text-red-800 font-medium">Raison de l'échec:</p>
                        <p className="text-sm text-red-700 mt-1">{log.failure_reason}</p>
                      </div>
                    )}
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle className="text-sm font-medium text-gray-500">Type et Template</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    <div className="flex items-center gap-2">
                      <Tag className="h-4 w-4 text-gray-400" />
                      <span className="text-sm font-medium">{log.email_type}</span>
                    </div>
                    {log.template_name && (
                      <div className="flex items-center gap-2">
                        <Hash className="h-4 w-4 text-gray-400" />
                        <span className="text-sm">{log.template_name}</span>
                      </div>
                    )}
                  </CardContent>
                </Card>
              </div>

              {/* Expéditeur et destinataires */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm font-medium text-gray-500">Expéditeur et Destinataires</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <User className="h-4 w-4 text-gray-400" />
                      <span className="text-sm font-medium">De:</span>
                      <span className="text-sm">{log.sender_email}</span>
                    </div>
                    <Button variant="ghost" size="sm" onClick={() => copyToClipboard(log.sender_email)}>
                      <Copy className="h-4 w-4" />
                    </Button>
                  </div>
                  
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <User className="h-4 w-4 text-gray-400" />
                      <span className="text-sm font-medium">À:</span>
                      <span className="text-sm">{log.recipient_email}</span>
                    </div>
                    <Button variant="ghost" size="sm" onClick={() => copyToClipboard(log.recipient_email)}>
                      <Copy className="h-4 w-4" />
                    </Button>
                  </div>

                  {log.cc_emails && log.cc_emails.length > 0 && (
                    <div className="flex items-start justify-between">
                      <div className="flex items-start gap-2">
                        <User className="h-4 w-4 text-gray-400 mt-0.5" />
                        <div>
                          <span className="text-sm font-medium">CC:</span>
                          <div className="text-sm mt-1">
                            {log.cc_emails.map((email, index) => (
                              <div key={index} className="flex items-center gap-2">
                                <span>{email}</span>
                                <Button variant="ghost" size="sm" onClick={() => copyToClipboard(email)}>
                                  <Copy className="h-3 w-3" />
                                </Button>
                              </div>
                            ))}
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* Sujet */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm font-medium text-gray-500">Sujet</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="flex items-center justify-between">
                    <p className="text-sm">{log.subject}</p>
                    <Button variant="ghost" size="sm" onClick={() => copyToClipboard(log.subject)}>
                      <Copy className="h-4 w-4" />
                    </Button>
                  </div>
                </CardContent>
              </Card>

              {/* Horodatage */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="text-sm font-medium text-gray-500">Créé le</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="flex items-center gap-2">
                      <Clock className="h-4 w-4 text-gray-400" />
                      <span className="text-sm">{new Date(log.created_at).toLocaleString('fr-FR')}</span>
                    </div>
                  </CardContent>
                </Card>

                {log.sent_at && (
                  <Card>
                    <CardHeader>
                      <CardTitle className="text-sm font-medium text-gray-500">Envoyé le</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center gap-2">
                        <CheckCircle className="h-4 w-4 text-green-500" />
                        <span className="text-sm">{new Date(log.sent_at).toLocaleString('fr-FR')}</span>
                      </div>
                    </CardContent>
                  </Card>
                )}
              </div>

              {/* Identifiants */}
              {(log.ses_message_id || log.organization_id || log.contract_id) && (
                <Card>
                  <CardHeader>
                    <CardTitle className="text-sm font-medium text-gray-500">Identifiants</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    {log.ses_message_id && (
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <Hash className="h-4 w-4 text-gray-400" />
                          <span className="text-sm font-medium">SES Message ID:</span>
                          <span className="text-sm font-mono">{log.ses_message_id}</span>
                        </div>
                        <Button variant="ghost" size="sm" onClick={() => copyToClipboard(log.ses_message_id!)}>
                          <Copy className="h-4 w-4" />
                        </Button>
                      </div>
                    )}
                    
                    {log.organization_id && (
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <Hash className="h-4 w-4 text-gray-400" />
                          <span className="text-sm font-medium">Organisation ID:</span>
                          <span className="text-sm font-mono">{log.organization_id}</span>
                        </div>
                        <Button variant="ghost" size="sm" onClick={() => copyToClipboard(log.organization_id!)}>
                          <Copy className="h-4 w-4" />
                        </Button>
                      </div>
                    )}
                    
                    {log.contract_id && (
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <Hash className="h-4 w-4 text-gray-400" />
                          <span className="text-sm font-medium">Contrat ID:</span>
                          <span className="text-sm font-mono">{log.contract_id}</span>
                        </div>
                        <Button variant="ghost" size="sm" onClick={() => copyToClipboard(log.contract_id!)}>
                          <Copy className="h-4 w-4" />
                        </Button>
                      </div>
                    )}
                  </CardContent>
                </Card>
              )}
            </div>
          )}

          {activeTab === 'html' && (
            <div className="space-y-4">
              {loadingContent ? (
                <div className="flex items-center justify-center py-8">
                  <RefreshCw className="h-6 w-6 animate-spin" />
                  <span className="ml-2">Chargement du contenu...</span>
                </div>
              ) : (
                <div className="border rounded-lg overflow-hidden">
                  <div className="bg-gray-50 p-3 border-b">
                    <h3 className="text-sm font-medium">Rendu de l'email</h3>
                  </div>
                  <div className="p-4 bg-white">
                    <iframe
                      srcDoc={htmlContent || ''}
                      className="w-full h-96 border-0"
                      title="Rendu de l'email"
                      sandbox="allow-same-origin"
                    />
                  </div>
                </div>
              )}
            </div>
          )}

          {activeTab === 'raw' && (
            <div className="space-y-4">
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm font-medium text-gray-500">Tags</CardTitle>
                </CardHeader>
                <CardContent>
                  <pre className="text-xs bg-gray-50 p-3 rounded-md overflow-auto">
                    {JSON.stringify(log.tags, null, 2)}
                  </pre>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="text-sm font-medium text-gray-500">Contexte</CardTitle>
                </CardHeader>
                <CardContent>
                  <pre className="text-xs bg-gray-50 p-3 rounded-md overflow-auto">
                    {JSON.stringify(log.context, null, 2)}
                  </pre>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="text-sm font-medium text-gray-500">Données complètes</CardTitle>
                </CardHeader>
                <CardContent>
                  <pre className="text-xs bg-gray-50 p-3 rounded-md overflow-auto">
                    {JSON.stringify(log, null, 2)}
                  </pre>
                </CardContent>
              </Card>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex justify-end gap-3 p-6 border-t bg-gray-50">
          <Button variant="outline" onClick={onClose}>
            Fermer
          </Button>
        </div>
      </div>
    </div>
  );
}