"use client";

import { useState, useEffect } from "react";
import { RefreshCw, CheckCircle2, XCircle, AlertTriangle, Image, FileImage } from "lucide-react";

type EmailLogEntry = {
  ts: string;
  to: string;
  subject: string;
  ok: boolean;
  messageId?: string;
  error?: string;
  context?: string;
};

type Status = {
  provider?: "resend" | "smtp" | "none";
  resend?: { active: boolean; hasKey: boolean; from: string | null };
  smtp: {
    configured: boolean;
    host: string | null;
    port: string | null;
    user: string | null;
    from: string | null;
    hasPassword: boolean;
  };
  paths: {
    ticketImagesDir: string;
    ticketImagesExists: boolean;
    ticketImagesCount: number;
    logoExists: boolean;
  };
  recentLog: EmailLogEntry[];
};

export default function EmailStatusPanel() {
  const [status, setStatus] = useState<Status | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchStatus = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/admin/email-status");
      if (!res.ok) throw new Error("No autorizado");
      const data = await res.json();
      setStatus(data);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Error al cargar");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStatus();
    const onEmailSent = () => fetchStatus();
    window.addEventListener("email-sent", onEmailSent);
    return () => window.removeEventListener("email-sent", onEmailSent);
  }, []);

  if (loading && !status) {
    return (
      <div className="bg-white/5 border border-white/10 rounded-xl p-6 animate-pulse">
        <div className="h-6 bg-white/10 rounded w-1/3 mb-4" />
        <div className="h-4 bg-white/5 rounded w-full mb-2" />
        <div className="h-4 bg-white/5 rounded w-2/3" />
      </div>
    );
  }

  if (error || !status) {
    return (
      <div className="bg-red-500/10 border border-red-500/20 rounded-xl p-6">
        <p className="text-red-400">{error ?? "Error desconocido"}</p>
      </div>
    );
  }

  const { smtp, paths, recentLog } = status;

  return (
    <div className="bg-white/5 border border-white/10 rounded-xl p-6 space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold text-white flex items-center gap-2">
          <AlertTriangle className="w-5 h-5 text-neon-blue" />
          Diagnóstico de correo
        </h2>
        <button
          onClick={fetchStatus}
          disabled={loading}
          className="flex items-center gap-2 px-3 py-1.5 text-sm rounded-lg bg-white/5 hover:bg-white/10 transition-colors disabled:opacity-50"
        >
          <RefreshCw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} />
          Actualizar
        </button>
      </div>

      {/* Provider y configuración */}
      <div>
        <h3 className="text-sm font-medium text-gray-400 mb-2">Proveedor de correo</h3>
        <div className="flex flex-wrap gap-4 text-sm">
          <span className={status.provider !== "none" ? "text-green-400" : "text-red-400"}>
            {status.provider !== "none" ? <CheckCircle2 className="inline w-4 h-4 mr-1" /> : <XCircle className="inline w-4 h-4 mr-1" />}
            {status.provider === "resend" ? "Resend API" : status.provider === "smtp" ? "SMTP" : "No configurado"}
          </span>
          {status.resend?.active && (
            <span className="text-gray-300">
              from: <code className="text-neon-purple">{status.resend.from ?? "—"}</code>
            </span>
          )}
          {!status.resend?.active && smtp.configured && (
            <>
              {smtp.host && <span className="text-gray-300">host: <code className="text-neon-blue">{smtp.host}</code></span>}
              {smtp.port && <span className="text-gray-300">puerto: {smtp.port}</span>}
              {smtp.from && <span className="text-gray-300">from: <code className="text-neon-purple">{smtp.from}</code></span>}
            </>
          )}
        </div>
        {status.provider === "resend" && (
          <p className="text-xs text-amber-400/90 mt-2">
            Resend: verifica que <code className="text-amber-300">{smtp.from ?? "tu remitente"}</code> esté permitido en tu dominio verificado en resend.com/domains
          </p>
        )}
      </div>

      {/* Rutas */}
      <div>
        <h3 className="text-sm font-medium text-gray-400 mb-2">Archivos necesarios</h3>
        <div className="flex flex-wrap gap-4 text-sm">
          <span className={paths.logoExists ? "text-green-400" : "text-red-400"}>
            {paths.logoExists ? <FileImage className="inline w-4 h-4 mr-1" /> : <XCircle className="inline w-4 h-4 mr-1" />}
            Logo: {paths.logoExists ? "OK" : "No encontrado"}
          </span>
          <span className={paths.ticketImagesExists ? "text-green-400" : "text-amber-400"}>
            {paths.ticketImagesExists ? <Image className="inline w-4 h-4 mr-1" /> : <XCircle className="inline w-4 h-4 mr-1" />}
            Láminas: {paths.ticketImagesExists ? `${paths.ticketImagesCount} imágenes` : "Carpeta vacía o no existe"}
          </span>
        </div>
      </div>

      {/* Log reciente */}
      <div>
        <h3 className="text-sm font-medium text-gray-400 mb-2">Últimos intentos de envío</h3>
        {recentLog.length === 0 ? (
          <p className="text-gray-500 text-sm">Aún no hay registros. Envía un correo de prueba o confirma una orden.</p>
        ) : (
          <div className="space-y-2 max-h-48 overflow-y-auto">
            {recentLog.map((entry, i) => (
              <div
                key={i}
                className={`text-xs font-mono px-3 py-2 rounded-lg border ${
                  entry.ok ? "bg-green-500/5 border-green-500/20 text-green-300" : "bg-red-500/5 border-red-500/20 text-red-300"
                }`}
              >
                <span className="text-gray-500">{new Date(entry.ts).toLocaleString("es-CL")}</span>
                {" · "}
                <span>{entry.to}</span>
                {entry.context && <span className="text-gray-500"> · {entry.context}</span>}
                {entry.ok ? (
                  <span className="text-green-400"> · OK</span>
                ) : (
                  <span className="text-red-400"> · {entry.error}</span>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      <p className="text-xs text-gray-500">
        También puedes revisar los logs de PM2: <code className="text-gray-400">pm2 logs</code> — busca líneas con prefijo <code className="text-neon-blue">[MAIL]</code>.
      </p>
    </div>
  );
}
