"use client";

// components/staff/BulkEmailForm.tsx
import { useState, useRef } from "react";
import { Eye, Send, Users, Mail, X, Check, Filter, Search, FileText, Palette } from "lucide-react";
import BulkEmailProgressModal from "./BulkEmailProgressModal";

interface User {
  id: string;
  email: string;
  emailConfirmed: boolean;
  createdAt: string;
  lastSignIn: string | null;
  organizations: Array<{
    id: string;
    name: string;
    role: string;
    structure_api: string | null;
  }>;
}

interface BulkEmailFormProps {
  users: User[];
}

type EmailProgress = {
  id: string;
  email: string;
  organizationName?: string;
  status: 'pending' | 'sending' | 'success' | 'error';
  error?: string;
  sentAt?: string;
};

export default function BulkEmailForm({ users }: BulkEmailFormProps) {
  const [subject, setSubject] = useState("");
  const [htmlContent, setHtmlContent] = useState(`<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email - Espace Paie Odentas</title>
    <style>
        body { margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .container { max-width: 600px; margin: 0 auto; background-color: #ffffff; }
        .header { background: linear-gradient(135deg, #171424 0%, #2d1b3d 100%); color: white; padding: 30px 20px; text-align: center; }
        .header h1 { margin: 0; font-size: 28px; font-weight: 300; }
        .content { padding: 40px 30px; background-color: #f8f9fa; }
        .content h2 { color: #171424; margin-top: 0; margin-bottom: 20px; font-size: 24px; }
        .content p { line-height: 1.6; color: #333; margin-bottom: 16px; }
        .button { display: inline-block; background-color: #efc543; color: #000; padding: 15px 30px; text-decoration: none; border-radius: 8px; font-weight: 600; margin: 20px 0; transition: background-color 0.3s; }
        .button:hover { background-color: #d4a834; }
        .footer { background-color: #f1f3f4; padding: 20px; text-align: center; color: #666; font-size: 12px; }
        .highlight { background-color: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin: 20px 0; }
        @media only screen and (max-width: 600px) {
            .content { padding: 20px 15px; }
            .header { padding: 20px 15px; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🏢 Espace Paie Odentas</h1>
            <p style="margin: 10px 0 0 0; opacity: 0.9; font-size: 16px;">Votre partenaire RH de confiance</p>
        </div>
        
        <div class="content">
            <h2>Bonjour,</h2>
            
            <p>Nous espérons que vous allez bien. Nous vous contactons aujourd'hui pour vous informer de...</p>
            
            <div class="highlight">
                <strong>📢 Information importante :</strong> N'hésitez pas à personnaliser ce message selon vos besoins.
            </div>
            
            <p>Pour plus d'informations ou pour toute question, n'hésitez pas à nous contacter.</p>
            
            <div style="text-align: center; margin: 30px 0;">
                <a href="#" class="button">Accéder à mon espace</a>
            </div>
            
            <p>Cordialement,<br><strong>L'équipe Odentas</strong></p>
        </div>
        
        <div class="footer">
            <p><strong>Odentas Media SAS</strong><br>
            Votre partenaire pour la gestion de la paie et des RH</p>
            <p>📧 contact@odentas.com | 🌐 www.odentas.com</p>
            <p style="margin-top: 15px;">
                <span style="color: #666;">🇫🇷 Données hébergées en France</span><br>
                © ${new Date().getFullYear()} Odentas Media SAS - Tous droits réservés
            </p>
        </div>
    </div>
</body>
</html>`);
  
  const [selectedUsers, setSelectedUsers] = useState<Set<string>>(new Set());
  const [showPreview, setShowPreview] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [roleFilter, setRoleFilter] = useState("all");
  const [orgFilter, setOrgFilter] = useState("all");
  const [showUsersPanel, setShowUsersPanel] = useState(true);
  const [showTemplates, setShowTemplates] = useState(false);
  
  // États pour le modal de progression
  const [showProgressModal, setShowProgressModal] = useState(false);
  const [emailProgress, setEmailProgress] = useState<EmailProgress[]>([]);
  const [progressStats, setProgressStats] = useState({
    total: 0,
    completed: 0,
    success: 0,
    errors: 0
  });
  const [currentStream, setCurrentStream] = useState<AbortController | null>(null);
  
  const previewRef = useRef<HTMLDivElement>(null);

  // Templates prédéfinis
  const templates = [
    {
      name: "Maintenance programmée",
      subject: "Maintenance programmée - Espace Paie Odentas",
      description: "Informer les utilisateurs d'une maintenance"
    },
    {
      name: "Nouvelle fonctionnalité",
      subject: "Nouvelle fonctionnalité disponible",
      description: "Annoncer une nouvelle fonctionnalité"
    },
    {
      name: "Information importante",
      subject: "Information importante - Espace Paie",
      description: "Communication générale importante"
    }
  ];

  const loadTemplate = (templateName: string) => {
    setSubject(templates.find(t => t.name === templateName)?.subject || "");
    // Vous pouvez ajouter du contenu HTML spécifique pour chaque template ici
    setShowTemplates(false);
  };

  // Filtrer les utilisateurs
  const filteredUsers = users.filter(user => {
    // Validation basique de l'email
    const isValidEmail = user.email && 
                        user.email.includes('@') && 
                        user.email.includes('.') && 
                        user.email.length > 5 &&
                        !user.email.includes(' ');
    
    const matchesSearch = user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          user.organizations.some(org => org.name.toLowerCase().includes(searchTerm.toLowerCase()));
    
    const matchesRole = roleFilter === "all" || user.organizations.some(org => org.role === roleFilter);
    
    const matchesOrg = orgFilter === "all" || user.organizations.some(org => org.id === orgFilter);
    
    return isValidEmail && matchesSearch && matchesRole && matchesOrg && user.emailConfirmed;
  });

  // Obtenir les organisations uniques
  const allOrganizations = Array.from(new Set(
    users.flatMap(user => user.organizations.map(org => ({ id: org.id, name: org.name })))
  )).filter((org, index, self) => 
    index === self.findIndex(o => o.id === org.id)
  );

  const handleSelectAll = () => {
    if (selectedUsers.size === filteredUsers.length) {
      setSelectedUsers(new Set());
    } else {
      setSelectedUsers(new Set(filteredUsers.map(user => user.id)));
    }
  };

  const toggleUserSelection = (userId: string) => {
    const newSelected = new Set(selectedUsers);
    if (newSelected.has(userId)) {
      newSelected.delete(userId);
    } else {
      newSelected.add(userId);
    }
    setSelectedUsers(newSelected);
  };

  const handleSendEmails = async () => {
    if (!subject.trim() || !htmlContent.trim() || selectedUsers.size === 0) {
      alert("Veuillez remplir tous les champs et sélectionner au moins un destinataire.");
      return;
    }

    const selectedUsersList = users.filter(user => selectedUsers.has(user.id));
    
    // Initialiser le modal de progression
    const initialProgress: EmailProgress[] = selectedUsersList.map(user => ({
      id: user.id,
      email: user.email,
      organizationName: user.organizations[0]?.name || 'Organisation inconnue',
      status: 'pending'
    }));
    
    setEmailProgress(initialProgress);
    setProgressStats({
      total: selectedUsersList.length,
      completed: 0,
      success: 0,
      errors: 0
    });
    setShowProgressModal(true);
    setIsLoading(true);

    // Créer AbortController pour pouvoir annuler
    const abortController = new AbortController();
    setCurrentStream(abortController);

    try {
      const response = await fetch("/api/staff/bulk-email-stream", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          subject,
          htmlContent,
          recipients: selectedUsersList.map(user => ({
            id: user.id,
            email: user.email,
            organizations: user.organizations
          }))
        }),
        signal: abortController.signal
      });

      if (!response.ok) {
        throw new Error(`Erreur HTTP: ${response.status}`);
      }

      const reader = response.body?.getReader();
      const decoder = new TextDecoder();

      if (!reader) {
        throw new Error("Impossible de lire la réponse streaming");
      }

      while (true) {
        const { done, value } = await reader.read();
        
        if (done) break;
        
        const chunk = decoder.decode(value, { stream: true });
        const lines = chunk.split('\n');
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const data = JSON.parse(line.slice(6));
              
              switch (data.type) {
                case 'init':
                  // Initialisation déjà faite
                  break;
                  
                case 'progress':
                  // Mettre à jour le statut d'un email spécifique
                  setEmailProgress(prev => 
                    prev.map(email => 
                      email.id === data.recipientId 
                        ? { 
                            ...email, 
                            status: data.status, 
                            error: data.error,
                            sentAt: data.sentAt 
                          }
                        : email
                    )
                  );
                  break;
                  
                case 'batch_complete':
                  // Mettre à jour les statistiques globales
                  setProgressStats({
                    total: data.total,
                    completed: data.completed,
                    success: data.success,
                    errors: data.errors
                  });
                  break;
                  
                case 'complete':
                  // Envoi terminé
                  setProgressStats({
                    total: data.total,
                    completed: data.total,
                    success: data.success,
                    errors: data.errors
                  });
                  setIsLoading(false);
                  setCurrentStream(null);
                  break;
                  
                case 'error':
                  throw new Error(data.error);
              }
            } catch (parseError) {
              console.error("Erreur parsing SSE:", parseError);
            }
          }
        }
      }

    } catch (error: any) {
      console.error("Erreur:", error);
      if (error.name !== 'AbortError') {
        alert(`Erreur lors de l'envoi des emails: ${error.message}`);
      }
      setIsLoading(false);
      setCurrentStream(null);
    }
  };

  const handleCancelSending = () => {
    if (currentStream) {
      currentStream.abort();
      setCurrentStream(null);
      setIsLoading(false);
    }
  };

  const handleCloseProgressModal = () => {
    setShowProgressModal(false);
    // Réinitialiser la sélection après un envoi réussi
    if (!isLoading && progressStats.completed === progressStats.total) {
      setSelectedUsers(new Set());
      setSubject("");
    }
  };

  return (
    <div className="flex gap-6 h-[calc(100vh-200px)]">
      {/* Panneau de sélection des utilisateurs */}
      <div className={`${showUsersPanel ? 'w-1/3' : 'w-12'} transition-all duration-300 bg-white rounded-lg border shadow-sm flex flex-col`}>
        <div className="p-4 border-b flex items-center justify-between">
          {showUsersPanel ? (
            <>
              <div className="flex items-center gap-2">
                <Users className="w-5 h-5 text-blue-600" />
                <h3 className="font-semibold">Destinataires</h3>
                <span className="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full">
                  {selectedUsers.size} sélectionné(s)
                </span>
              </div>
              <button
                onClick={() => setShowUsersPanel(false)}
                className="text-gray-400 hover:text-gray-600 p-1"
              >
                <X className="w-4 h-4" />
              </button>
            </>
          ) : (
            <button
              onClick={() => setShowUsersPanel(true)}
              className="w-full flex items-center justify-center text-gray-400 hover:text-gray-600 p-2"
            >
              <Users className="w-5 h-5" />
            </button>
          )}
        </div>

        {showUsersPanel && (
          <>
            {/* Filtres */}
            <div className="p-4 border-b space-y-3">
              <div className="relative">
                <Search className="w-4 h-4 absolute left-3 top-3 text-gray-400" />
                <input
                  type="text"
                  placeholder="Rechercher par email ou organisation..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 border rounded-lg text-sm"
                />
              </div>
              
              <div className="flex gap-2">
                <select
                  value={roleFilter}
                  onChange={(e) => setRoleFilter(e.target.value)}
                  className="flex-1 px-3 py-2 border rounded-lg text-sm"
                >
                  <option value="all">Tous les rôles</option>
                  <option value="admin">Admin</option>
                  <option value="user">Utilisateur</option>
                  <option value="viewer">Viewer</option>
                </select>
                
                <select
                  value={orgFilter}
                  onChange={(e) => setOrgFilter(e.target.value)}
                  className="flex-1 px-3 py-2 border rounded-lg text-sm"
                >
                  <option value="all">Toutes les orgs</option>
                  {allOrganizations.map(org => (
                    <option key={org.id} value={org.id}>{org.name}</option>
                  ))}
                </select>
              </div>

              <button
                onClick={handleSelectAll}
                className="w-full px-3 py-2 text-sm bg-blue-50 text-blue-700 rounded-lg hover:bg-blue-100 transition-colors"
              >
                {selectedUsers.size === filteredUsers.length ? "Désélectionner tout" : "Sélectionner tout"}
              </button>
            </div>

            {/* Liste des utilisateurs */}
            <div className="flex-1 overflow-y-auto">
              {filteredUsers.map(user => (
                <div
                  key={user.id}
                  className={`p-3 border-b cursor-pointer hover:bg-gray-50 ${
                    selectedUsers.has(user.id) ? 'bg-blue-50 border-blue-200' : ''
                  }`}
                  onClick={() => toggleUserSelection(user.id)}
                >
                  <div className="flex items-center gap-3">
                    <div className={`w-4 h-4 rounded border-2 flex items-center justify-center ${
                      selectedUsers.has(user.id) 
                        ? 'bg-blue-600 border-blue-600' 
                        : 'border-gray-300'
                    }`}>
                      {selectedUsers.has(user.id) && (
                        <Check className="w-3 h-3 text-white" />
                      )}
                    </div>
                    
                    <div className="flex-1 min-w-0">
                      <div className="font-medium text-sm truncate">{user.email}</div>
                      <div className="text-xs text-gray-500">
                        {user.organizations.map(org => org.name).join(", ")}
                      </div>
                      <div className="text-xs text-gray-400">
                        {user.organizations.map(org => org.role).join(", ")}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
              
              {filteredUsers.length === 0 && (
                <div className="p-6 text-center text-gray-500">
                  Aucun utilisateur trouvé avec ces filtres
                </div>
              )}
            </div>
          </>
        )}
      </div>

      {/* Formulaire de composition */}
      <div className="flex-1 bg-white rounded-lg border shadow-sm flex flex-col">
        <div className="p-4 border-b">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <Mail className="w-5 h-5 text-green-600" />
              <h3 className="font-semibold">Composition de l'email</h3>
            </div>
            
            <div className="flex gap-2">
              <button
                onClick={() => setShowTemplates(!showTemplates)}
                className="flex items-center gap-2 px-4 py-2 bg-purple-100 text-purple-700 rounded-lg hover:bg-purple-200 transition-colors"
              >
                <FileText className="w-4 h-4" />
                Templates
              </button>
              
              <button
                onClick={() => setShowPreview(!showPreview)}
                className="flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
              >
                <Eye className="w-4 h-4" />
                {showPreview ? "Éditer" : "Aperçu"}
              </button>
              
              <button
                onClick={handleSendEmails}
                disabled={isLoading || selectedUsers.size === 0}
                className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <Send className="w-4 h-4" />
                {isLoading ? "Envoi..." : `Envoyer (${selectedUsers.size})`}
              </button>
            </div>
          </div>

          {/* Sujet et Templates */}
          <div className="space-y-3">
            <input
              type="text"
              placeholder="Sujet de l'email"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              className="w-full px-4 py-3 border rounded-lg text-lg"
              disabled={isLoading}
            />
            
            {/* Panel Templates */}
            {showTemplates && (
              <div className="bg-purple-50 border border-purple-200 rounded-lg p-4">
                <h4 className="font-semibold text-purple-800 mb-3">Templates disponibles</h4>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-2">
                  {templates.map((template) => (
                    <button
                      key={template.name}
                      onClick={() => loadTemplate(template.name)}
                      className="p-3 text-left bg-white border border-purple-200 rounded-lg hover:bg-purple-100 transition-colors"
                    >
                      <div className="font-medium text-sm">{template.name}</div>
                      <div className="text-xs text-gray-600 mt-1">{template.description}</div>
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Contenu */}
        <div className="flex-1 flex">
          {!showPreview ? (
            <textarea
              value={htmlContent}
              onChange={(e) => setHtmlContent(e.target.value)}
              placeholder="Contenu HTML de l'email..."
              className="w-full p-4 font-mono text-sm resize-none border-0 outline-none"
              disabled={isLoading}
            />
          ) : (
            <div className="w-full p-4 overflow-auto bg-gray-50">
              <div className="max-w-2xl mx-auto bg-white rounded-lg shadow-sm">
                <div
                  ref={previewRef}
                  dangerouslySetInnerHTML={{ __html: htmlContent }}
                  className="prose max-w-none"
                />
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Modal de progression */}
      <BulkEmailProgressModal
        isOpen={showProgressModal}
        onClose={handleCloseProgressModal}
        emails={emailProgress}
        onCancel={isLoading ? handleCancelSending : undefined}
        isProcessing={isLoading}
        totalCount={progressStats.total}
        completedCount={progressStats.completed}
        successCount={progressStats.success}
        errorCount={progressStats.errors}
        subject={subject}
      />
    </div>
  );
}