"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 SmartReminderAvenant {
  id: string;
  numero_avenant?: string | null;
  contract_number?: string | null;
  employee_name?: string | null;
  employee_email?: string | null;
  employer_email?: string | null;
  employer_signed: boolean;
  employee_signed: boolean;
  action: ReminderAction;
  reason?: string;
  status?: ReminderStatus;
}

export interface SmartReminderAvenantModalProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (forceResend: boolean) => void;
  isLoading: boolean;
  avenants: SmartReminderAvenant[];
  progressAvenants?: SmartReminderAvenant[]; // Avenants avec statut de progression
}

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

  const getActionBadge = (avenant: SmartReminderAvenant, status?: ReminderStatus) => {
    // Déterminer l'action finale selon forceResend
    const extended = avenant as SmartReminderAvenant & { forcedAction?: ReminderAction };
    const finalAction = (forceResend && extended.forcedAction) ? extended.forcedAction : avenant.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-green-100 text-green-800">
            <Mail className="size-3" />
            Relance salarié
          </span>
        );
      case 'skip':
        return (
          <span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-slate-100 text-slate-700">
            <Clock className="size-3" />
            Ignoré
          </span>
        );
      case 'already-signed':
        return (
          <span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-emerald-100 text-emerald-800">
            <CheckCircle className="size-3" />
            Déjà signé
          </span>
        );
      default:
        return null;
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[85vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle>Relances intelligentes - Avenants</DialogTitle>
          <DialogDescription>
            Vérifiez les avenants sélectionnés pour l'envoi de relances automatiques
          </DialogDescription>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto space-y-4">
          {/* Statistiques */}
          <div className="grid grid-cols-2 gap-3 mb-4">
            <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
              <div className="text-sm font-medium text-blue-900">Relances employeur</div>
              <div className="text-2xl font-bold text-blue-600">{employerReminders}</div>
            </div>
            <div className="p-3 bg-green-50 rounded-lg border border-green-200">
              <div className="text-sm font-medium text-green-900">Relances salarié</div>
              <div className="text-2xl font-bold text-green-600">{employeeReminders}</div>
            </div>
            <div className="p-3 bg-slate-50 rounded-lg border border-slate-200">
              <div className="text-sm font-medium text-slate-900">Ignorés</div>
              <div className="text-2xl font-bold text-slate-600">{skipped}</div>
            </div>
            <div className="p-3 bg-emerald-50 rounded-lg border border-emerald-200">
              <div className="text-sm font-medium text-emerald-900">Déjà signés</div>
              <div className="text-2xl font-bold text-emerald-600">{alreadySigned}</div>
            </div>
          </div>

          {/* Option forcer renvoi */}
          {skippedDueToCooldown > 0 && !isLoading && (
            <div className="p-4 bg-orange-50 border border-orange-200 rounded-lg">
              <div className="flex items-start gap-3">
                <AlertTriangle className="size-5 text-orange-600 flex-shrink-0 mt-0.5" />
                <div className="flex-1">
                  <div className="font-medium text-orange-900 mb-1">
                    {skippedDueToCooldown} avenant(s) ignoré(s) - relance récente (moins de 24h)
                  </div>
                  <p className="text-sm text-orange-800 mb-3">
                    Ces avenants ont déjà reçu une relance dans les dernières 24h. 
                    Souhaitez-vous forcer un nouvel envoi ?
                  </p>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={forceResend}
                      onChange={(e) => setForceResend(e.target.checked)}
                      className="w-4 h-4 text-orange-600 border-orange-300 rounded focus:ring-orange-500"
                    />
                    <span className="text-sm font-medium text-orange-900">
                      Forcer le renvoi pour ces avenants
                    </span>
                  </label>
                </div>
              </div>
            </div>
          )}

          {/* Liste des avenants */}
          <div className="border rounded-lg overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-slate-50 border-b">
                <tr>
                  <th className="px-3 py-2 text-left text-xs font-medium text-slate-600">N° Avenant</th>
                  <th className="px-3 py-2 text-left text-xs font-medium text-slate-600">Salarié</th>
                  <th className="px-3 py-2 text-left text-xs font-medium text-slate-600">Action</th>
                  <th className="px-3 py-2 text-left text-xs font-medium text-slate-600">Raison</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {displayAvenants.map((avenant) => {
                  // Trouver le statut dans progressAvenants
                  const progressAvenant = progressAvenants?.find(c => c.id === avenant.id);
                  const currentStatus = progressAvenant?.status;
                  
                  return (
                    <tr key={avenant.id} className="hover:bg-slate-50">
                      <td className="px-3 py-2 font-medium">{avenant.numero_avenant || avenant.contract_number || 'N/A'}</td>
                      <td className="px-3 py-2">{avenant.employee_name || 'Inconnu'}</td>
                      <td className="px-3 py-2">{getActionBadge(avenant, currentStatus)}</td>
                      <td className="px-3 py-2 text-slate-600 text-xs">{avenant.reason || '-'}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        <DialogFooter className="border-t pt-4">
          <Button
            variant="outline"
            onClick={onClose}
            disabled={isLoading}
          >
            Annuler
          </Button>
          <Button
            onClick={() => onConfirm(forceResend)}
            disabled={isLoading || (employerReminders === 0 && employeeReminders === 0 && !forceResend)}
          >
            {isLoading ? (
              <>
                <Loader2 className="mr-2 size-4 animate-spin" />
                Envoi en cours...
              </>
            ) : (
              <>
                <Mail className="mr-2 size-4" />
                Envoyer les relances ({forceResend ? employerReminders + employeeReminders + skippedDueToCooldown : employerReminders + employeeReminders})
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
