// components/staff/BulkInvoiceNotifyModal.tsx
"use client";

import React, { useState, useMemo } from "react";
import { X, Send, AlertCircle, CheckCircle, Mail, Loader2, ChevronDown, ChevronUp } from "lucide-react";

type InvoiceForNotification = {
  id: string;
  numero?: string | null;
  organization_name?: string;
  montant_ttc?: number;
  invoice_type?: string | null;
  payment_method?: string | null;
  email_notifs?: string;
  email_notifs_cc?: string | null;
  periode?: string | null;
};

type BulkInvoiceNotifyModalProps = {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: () => Promise<void>;
  invoices: InvoiceForNotification[];
  isLoading: boolean;
};

const fmtEUR = new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" });

// Obtenir le nom du template selon le type de facture
function getInvoiceTemplateName(invoiceType: string | null | undefined, paymentMethod?: string | null): string {
  if (!invoiceType) return 'Facture (type non défini)';
  
  switch (invoiceType) {
    case 'paie_mensuelle':
      return paymentMethod === 'virement' ? 'Paie Mensuelle (Virement)' : 'Paie Mensuelle (SEPA)';
    case 'paie_ouverture':
      return 'Paie Ouverture';
    case 'studio_site_web':
      return paymentMethod === 'virement' ? 'Studio Site Web (Virement)' : 'Studio Site Web (SEPA)';
    case 'studio_renouvellement':
      return paymentMethod === 'virement' ? 'Studio Renouvellement (Virement)' : 'Studio Renouvellement (SEPA)';
    default:
      return `Type personnalisé : ${invoiceType}`;
  }
}

// Obtenir la couleur du badge selon le type de facture
function getTemplateColor(invoiceType: string | null | undefined): string {
  if (!invoiceType) return 'bg-slate-100 text-slate-800';
  
  switch (invoiceType) {
    case 'paie_mensuelle':
      return 'bg-blue-100 text-blue-800';
    case 'paie_ouverture':
      return 'bg-indigo-100 text-indigo-800';
    case 'studio_site_web':
      return 'bg-purple-100 text-purple-800';
    case 'studio_renouvellement':
      return 'bg-violet-100 text-violet-800';
    default:
      return 'bg-slate-100 text-slate-800';
  }
}

export default function BulkInvoiceNotifyModal({
  isOpen,
  onClose,
  onConfirm,
  invoices,
  isLoading
}: BulkInvoiceNotifyModalProps) {
  const [expandedInvoices, setExpandedInvoices] = useState<Set<string>>(new Set());

  const toggleExpanded = (invoiceId: string) => {
    setExpandedInvoices(prev => {
      const newSet = new Set(prev);
      if (newSet.has(invoiceId)) {
        newSet.delete(invoiceId);
      } else {
        newSet.add(invoiceId);
      }
      return newSet;
    });
  };

  const expandAll = () => {
    setExpandedInvoices(new Set(invoices.map(inv => inv.id)));
  };

  const collapseAll = () => {
    setExpandedInvoices(new Set());
  };

  // Calculer les statistiques
  const stats = useMemo(() => {
    const total = invoices.length;
    const totalAmount = invoices.reduce((sum, inv) => sum + (inv.montant_ttc || 0), 0);
    const withEmail = invoices.filter(inv => inv.email_notifs).length;
    const withoutEmail = total - withEmail;
    
    return {
      total,
      totalAmount,
      withEmail,
      withoutEmail
    };
  }, [invoices]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg w-full max-w-4xl max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b bg-gray-50">
          <div className="flex items-center gap-3">
            <Send className="size-5 text-blue-600" />
            <div>
              <h2 className="text-lg font-semibold">Envoi de notifications en masse</h2>
              <p className="text-sm text-gray-600">
                {stats.total} facture{stats.total > 1 ? 's' : ''} sélectionnée{stats.total > 1 ? 's' : ''}
              </p>
            </div>
          </div>
          
          <button
            onClick={onClose}
            disabled={isLoading}
            className="p-2 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50"
          >
            <X className="size-5" />
          </button>
        </div>

        {/* Statistiques */}
        <div className="p-4 bg-blue-50 border-b">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div>
              <div className="text-xs text-gray-600 mb-1">Total factures</div>
              <div className="text-xl font-bold text-blue-600">{stats.total}</div>
            </div>
            <div>
              <div className="text-xs text-gray-600 mb-1">Montant total TTC</div>
              <div className="text-xl font-bold text-blue-600">{fmtEUR.format(stats.totalAmount)}</div>
            </div>
            <div>
              <div className="text-xs text-gray-600 mb-1">Avec email</div>
              <div className="text-xl font-bold text-green-600">{stats.withEmail}</div>
            </div>
            <div>
              <div className="text-xs text-gray-600 mb-1">Sans email</div>
              <div className="text-xl font-bold text-red-600">{stats.withoutEmail}</div>
            </div>
          </div>
        </div>

        {/* Alerte si factures sans email */}
        {stats.withoutEmail > 0 && (
          <div className="mx-4 mt-4 p-3 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
            <AlertCircle className="size-5 text-red-600 flex-shrink-0 mt-0.5" />
            <div className="flex-1">
              <p className="text-sm font-medium text-red-800">
                Attention : {stats.withoutEmail} facture{stats.withoutEmail > 1 ? 's n\'ont' : ' n\'a'} pas d'email de notification
              </p>
              <p className="text-xs text-red-600 mt-1">
                Ces factures seront ignorées lors de l'envoi
              </p>
            </div>
          </div>
        )}

        {/* Actions d'expansion */}
        <div className="px-4 pt-4 pb-2 flex items-center justify-between">
          <h3 className="font-medium text-sm text-gray-700">Liste des factures</h3>
          <div className="flex items-center gap-2">
            <button
              onClick={expandAll}
              className="text-xs text-blue-600 hover:text-blue-800 underline"
            >
              Tout développer
            </button>
            <span className="text-gray-300">|</span>
            <button
              onClick={collapseAll}
              className="text-xs text-blue-600 hover:text-blue-800 underline"
            >
              Tout réduire
            </button>
          </div>
        </div>

        {/* Liste des factures */}
        <div className="flex-1 overflow-y-auto px-4 pb-4">
          <div className="space-y-2">
            {invoices.map((invoice) => {
              const isExpanded = expandedInvoices.has(invoice.id);
              const hasEmail = !!invoice.email_notifs;
              const templateName = getInvoiceTemplateName(invoice.invoice_type, invoice.payment_method);
              const templateColor = getTemplateColor(invoice.invoice_type);

              return (
                <div
                  key={invoice.id}
                  className={`border rounded-lg transition-colors ${
                    hasEmail ? 'border-gray-200 bg-white' : 'border-red-200 bg-red-50'
                  }`}
                >
                  {/* Header - toujours visible */}
                  <button
                    onClick={() => toggleExpanded(invoice.id)}
                    className="w-full p-3 flex items-center justify-between hover:bg-gray-50 transition-colors"
                  >
                    <div className="flex items-center gap-3 flex-1 min-w-0">
                      <div className="flex-shrink-0">
                        {hasEmail ? (
                          <CheckCircle className="size-5 text-green-500" />
                        ) : (
                          <AlertCircle className="size-5 text-red-500" />
                        )}
                      </div>
                      <div className="flex-1 min-w-0 text-left">
                        <div className="flex items-center gap-2">
                          <span className="font-medium truncate">
                            {invoice.numero || `Facture ${invoice.id.slice(0, 8)}`}
                          </span>
                          {invoice.periode && (
                            <span className="text-xs text-gray-500">({invoice.periode})</span>
                          )}
                        </div>
                        <div className="text-sm text-gray-600 truncate">
                          {invoice.organization_name || 'Client inconnu'}
                        </div>
                      </div>
                      <div className="flex-shrink-0 text-right">
                        <div className="font-medium text-blue-600">
                          {fmtEUR.format(invoice.montant_ttc || 0)}
                        </div>
                      </div>
                    </div>
                    <div className="flex-shrink-0 ml-2">
                      {isExpanded ? (
                        <ChevronUp className="size-4 text-gray-400" />
                      ) : (
                        <ChevronDown className="size-4 text-gray-400" />
                      )}
                    </div>
                  </button>

                  {/* Détails - affichés si expanded */}
                  {isExpanded && (
                    <div className="px-3 pb-3 border-t bg-gray-50 space-y-3">
                      {/* Template utilisé */}
                      <div>
                        <div className="text-xs text-gray-500 mb-1">Template email</div>
                        <span className={`inline-flex items-center gap-1 px-2 py-1 text-xs rounded-full ${templateColor}`}>
                          <Mail className="size-3" />
                          {templateName}
                        </span>
                      </div>

                      {/* Email de notification */}
                      <div>
                        <div className="text-xs text-gray-500 mb-1">Email de notification</div>
                        {hasEmail ? (
                          <div className="text-sm font-mono bg-white px-2 py-1 rounded border">
                            {invoice.email_notifs}
                          </div>
                        ) : (
                          <div className="text-sm text-red-600 italic">
                            Aucun email configuré
                          </div>
                        )}
                      </div>

                      {/* Email CC */}
                      {invoice.email_notifs_cc && (
                        <div>
                          <div className="text-xs text-gray-500 mb-1">Email CC</div>
                          <div className="text-sm font-mono bg-white px-2 py-1 rounded border">
                            {invoice.email_notifs_cc}
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* Footer */}
        <div className="p-4 border-t bg-gray-50 flex items-center justify-between">
          <div className="text-sm text-gray-600">
            {stats.withEmail > 0 ? (
              <span>
                <strong>{stats.withEmail}</strong> notification{stats.withEmail > 1 ? 's' : ''} sera{stats.withEmail > 1 ? 'ont' : ''} envoyée{stats.withEmail > 1 ? 's' : ''}
              </span>
            ) : (
              <span className="text-red-600">Aucune notification ne peut être envoyée</span>
            )}
          </div>
          <div className="flex items-center gap-3">
            <button
              onClick={onClose}
              disabled={isLoading}
              className="px-4 py-2 text-gray-600 hover:text-gray-800 disabled:opacity-50"
            >
              Annuler
            </button>
            <button
              onClick={onConfirm}
              disabled={isLoading || stats.withEmail === 0}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  Envoi en cours...
                </>
              ) : (
                <>
                  <Send className="w-4 h-4" />
                  Envoyer les notifications
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
