"use client";

import React from 'react';
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Mail, AlertTriangle, CheckCircle, XCircle, Clock, Loader2 } from "lucide-react";

export type ReminderAction = 'employer' | 'employee' | 'skip' | 'already-signed';
export type ReminderStatus = 'pending' | 'sending' | 'success' | 'error';

export interface SmartReminderContract {
  id: string;
  reference?: string | null;
  contract_number?: string | null;
  employee_name?: string | null;
  employee_email?: string | null;
  employer_email?: string | null;
  employer_signed: boolean;
  employee_signed: boolean;
  contract_processed: boolean; // État de la demande = "Traitée"
  action: ReminderAction;
  reason?: string;
  status?: ReminderStatus;
}

export interface SmartReminderModalProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (forceResend: boolean) => void;
  isLoading: boolean;
  contracts: SmartReminderContract[];
  progressContracts?: SmartReminderContract[]; // Contrats avec statut de progression
}

export const SmartReminderModal: React.FC<SmartReminderModalProps> = ({
  isOpen,
  onClose,
  onConfirm,
  isLoading,
  contracts,
  progressContracts
}) => {
  // State pour l'option de forcer l'envoi
  const [forceResend, setForceResend] = React.useState(false);
  
  // Utiliser progressContracts si disponible (pendant l'envoi), sinon contracts (avant l'envoi)
  const displayContracts = progressContracts || contracts;
  
  const employerReminders = contracts.filter(c => c.action === 'employer').length;
  const employeeReminders = contracts.filter(c => c.action === 'employee').length;
  const skipped = contracts.filter(c => c.action === 'skip').length;
  const skippedDueToCooldown = contracts.filter(c => c.action === 'skip' && c.reason?.includes('moins de 24h')).length;
  const alreadySigned = contracts.filter(c => c.action === 'already-signed').length;

  const getActionBadge = (contract: SmartReminderContract, status?: ReminderStatus) => {
    // Déterminer l'action finale selon forceResend
    const extended = contract as SmartReminderContract & { forcedAction?: ReminderAction };
    const finalAction = (forceResend && extended.forcedAction) ? extended.forcedAction : contract.action;
    
    // Si un statut de progression existe, l'afficher à la place
    if (status === 'sending') {
      return (
        <span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800">
          <Loader2 className="size-3 animate-spin" />
          Envoi en cours...
        </span>
      );
    }
    if (status === 'success') {
      return (
        <span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-800">
          <CheckCircle className="size-3" />
          Envoyé
        </span>
      );
    }
    if (status === 'error') {
      return (
        <span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-red-100 text-red-800">
          <XCircle className="size-3" />
          Erreur
        </span>
      );
    }

    // Sinon afficher l'action prévue (finale avec forceResend)
    switch (finalAction) {
      case 'employer':
        return (
          <span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800">
            <Mail className="size-3" />
            Relance employeur
          </span>
        );
      case 'employee':
        return (
          <span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-indigo-100 text-indigo-800">
            <Mail className="size-3" />
            Relance salarié
          </span>
        );
      case 'already-signed':
        return (
          <span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-800">
            <CheckCircle className="size-3" />
            Déjà signé
          </span>
        );
      case 'skip':
        return (
          <span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-amber-100 text-amber-800">
            <XCircle className="size-3" />
            Non traité
          </span>
        );
    }
  };

  const getEmailForAction = (contract: SmartReminderContract): string => {
    // Déterminer l'action finale selon forceResend
    const extended = contract as SmartReminderContract & { forcedAction?: ReminderAction };
    const finalAction = (forceResend && extended.forcedAction) ? extended.forcedAction : contract.action;
    
    if (finalAction === 'employer') {
      return contract.employer_email || '—';
    }
    if (finalAction === 'employee') {
      return contract.employee_email || '—';
    }
    return '—';
  };

  // Calculer le nombre de relances qui seront envoyées
  // Si forceResend est activé, inclure aussi les contrats en cooldown qui ont une forcedAction
  const getTotalToSend = () => {
    if (forceResend) {
      // Compter tous les contrats qui peuvent être envoyés (avec ou sans cooldown)
      return contracts.filter(c => {
        const extended = c as SmartReminderContract & { forcedAction?: ReminderAction };
        const finalAction = extended.forcedAction || c.action;
        return finalAction === 'employer' || finalAction === 'employee';
      }).length;
    } else {
      // Mode normal : uniquement les contrats sans cooldown
      return employerReminders + employeeReminders;
    }
  };

  const totalToSend = getTotalToSend();
  const totalSent = displayContracts.filter(c => c.status === 'success').length;
  const totalErrors = displayContracts.filter(c => c.status === 'error').length;

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[800px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Mail className="size-5 text-indigo-600" />
            Relances intelligentes - Analyse des contrats
          </DialogTitle>
          <DialogDescription>
            Le système a analysé les {contracts.length} contrat{contracts.length > 1 ? 's' : ''} sélectionné{contracts.length > 1 ? 's' : ''} et déterminé automatiquement qui relancer.
          </DialogDescription>
        </DialogHeader>

        {/* Résumé */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
          {employerReminders > 0 && (
            <div className="rounded border border-blue-200 bg-blue-50 p-3 text-center">
              <div className="text-2xl font-bold text-blue-800">{employerReminders}</div>
              <div className="text-xs text-blue-600 mt-1">Employeur</div>
            </div>
          )}
          {employeeReminders > 0 && (
            <div className="rounded border border-indigo-200 bg-indigo-50 p-3 text-center">
              <div className="text-2xl font-bold text-indigo-800">{employeeReminders}</div>
              <div className="text-xs text-indigo-600 mt-1">Salarié</div>
            </div>
          )}
          {alreadySigned > 0 && (
            <div className="rounded border border-green-200 bg-green-50 p-3 text-center">
              <div className="text-2xl font-bold text-green-800">{alreadySigned}</div>
              <div className="text-xs text-green-600 mt-1">Déjà signé</div>
            </div>
          )}
          {skipped > 0 && (
            <div className="rounded border border-amber-200 bg-amber-50 p-3 text-center">
              <div className="text-2xl font-bold text-amber-800">{skipped}</div>
              <div className="text-xs text-amber-600 mt-1">Non traité</div>
            </div>
          )}
        </div>

        {totalToSend === 0 && (
          <div className="mb-3 rounded border border-amber-200 bg-amber-50 p-3 text-amber-800 text-sm flex items-start gap-2">
            <AlertTriangle className="size-4 mt-0.5 flex-shrink-0" />
            <div>
              Aucune relance à envoyer. Tous les contrats sont soit déjà signés, soit en attente de traitement.
            </div>
          </div>
        )}

        {/* Option de forcer l'envoi si des contrats sont en cooldown */}
        {skippedDueToCooldown > 0 && !isLoading && !(totalSent > 0 && totalSent === totalToSend) && (
          <div className="mb-3 rounded border border-orange-200 bg-orange-50 p-3">
            <label className="flex items-start gap-3 cursor-pointer">
              <input
                type="checkbox"
                checked={forceResend}
                onChange={(e) => setForceResend(e.target.checked)}
                className="mt-0.5 size-4 rounded border-orange-300 text-orange-600 focus:ring-orange-500"
              />
              <div className="text-sm">
                <div className="font-medium text-orange-900">
                  Forcer l'envoi malgré le cooldown de 24h
                </div>
                <div className="text-orange-700 mt-1">
                  {skippedDueToCooldown} contrat{skippedDueToCooldown > 1 ? 's ont' : ' a'} été exclu{skippedDueToCooldown > 1 ? 's' : ''} car une relance a déjà été envoyée il y a moins de 24h. 
                  Cochez cette option pour les inclure quand même.
                </div>
              </div>
            </label>
          </div>
        )}

        {/* Barre de progression pendant l'envoi */}
        {isLoading && (
          <div className="mb-3 rounded border border-blue-200 bg-blue-50 p-3">
            <div className="flex items-center justify-between mb-2 text-sm">
              <span className="font-medium text-blue-900">Progression</span>
              <span className="text-blue-700">{totalSent} / {totalToSend}</span>
            </div>
            <div className="w-full bg-blue-200 rounded-full h-2">
              <div 
                className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                style={{ width: `${totalToSend > 0 ? (totalSent / totalToSend) * 100 : 0}%` }}
              />
            </div>
            {totalErrors > 0 && (
              <div className="mt-2 text-xs text-red-600">
                {totalErrors} erreur{totalErrors > 1 ? 's' : ''}
              </div>
            )}
          </div>
        )}

        {/* Liste des contrats */}
        <div className="max-h-[50vh] overflow-auto rounded border">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 text-slate-600 sticky top-0">
              <tr>
                <th className="text-left px-3 py-2 w-24">Référence</th>
                <th className="text-left px-3 py-2">Salarié</th>
                <th className="text-left px-3 py-2">Email</th>
                <th className="text-left px-3 py-2 w-40">Action</th>
                <th className="text-left px-3 py-2">Raison</th>
              </tr>
            </thead>
            <tbody>
              {displayContracts.map(c => (
                <tr key={c.id} className="border-t hover:bg-slate-50">
                  <td className="px-3 py-2 font-mono text-xs">{c.reference || c.contract_number || '—'}</td>
                  <td className="px-3 py-2">{c.employee_name || '—'}</td>
                  <td className="px-3 py-2 text-xs text-slate-600">
                    {getEmailForAction(c)}
                  </td>
                  <td className="px-3 py-2">
                    {getActionBadge(c, c.status)}
                  </td>
                  <td className="px-3 py-2 text-xs text-slate-600">{c.reason || '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <DialogFooter className="flex gap-2">
          {/* Afficher "Annuler" avant l'envoi, "Fermer" après */}
          <Button 
            variant="outline" 
            onClick={onClose}
            className={totalSent > 0 && totalSent === totalToSend ? "" : ""}
          >
            {totalSent > 0 && totalSent === totalToSend ? "Fermer" : "Annuler"}
          </Button>
          
          {/* Bouton d'envoi : masqué une fois terminé */}
          {!(totalSent > 0 && totalSent === totalToSend) && (
            <Button 
              onClick={() => onConfirm(forceResend)} 
              disabled={isLoading || totalToSend === 0} 
              className="bg-indigo-600 hover:bg-indigo-700 text-white"
            >
              {isLoading ? 'Envoi en cours…' : `Envoyer ${totalToSend} relance${totalToSend > 1 ? 's' : ''}`}
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
