"use client";

import { useState } from "react";
import { Send, Loader2, CheckCircle2, XCircle } from "lucide-react";

export default function SendTestEmailButton() {
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<{ ok: boolean; msg: string } | null>(null);

  const handleSend = async () => {
    if (!email || !email.includes("@")) return;
    setLoading(true);
    setResult(null);
    try {
      const res = await fetch(`/api/admin/send-test-email`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ to: email }),
      });
      const data = await res.json();
      setResult({ ok: res.ok, msg: data.message || data.error || "Error desconocido" });
      if (res.ok) window.dispatchEvent(new CustomEvent("email-sent"));
    } catch {
      setResult({ ok: false, msg: "Error de red al enviar" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="bg-white/5 border border-white/10 rounded-xl p-5 flex flex-col sm:flex-row items-start sm:items-center gap-4">
      <div className="flex-1 min-w-0">
        <p className="text-sm font-semibold text-white mb-1">Disparar correo de prueba real</p>
        <p className="text-xs text-gray-400">
          Envía el correo de confirmación con códigos de ejemplo al correo que ingreses, usando el SMTP configurado.
        </p>
      </div>
      <div className="flex gap-2 w-full sm:w-auto">
        <input
          type="email"
          value={email}
          onChange={(e) => { setEmail(e.target.value); setResult(null); }}
          placeholder="tu@correo.com"
          className="flex-1 sm:w-56 bg-black/40 border border-white/10 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-neon-blue placeholder:text-gray-600"
        />
        <button
          onClick={handleSend}
          disabled={loading || !email.includes("@")}
          className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-neon-blue to-neon-purple text-white text-sm font-semibold rounded-xl disabled:opacity-50 hover:opacity-90 transition-opacity"
        >
          {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
          Enviar
        </button>
      </div>
      {result && (
        <div className={`w-full sm:w-auto flex items-center gap-2 text-sm rounded-lg px-3 py-2 ${
          result.ok ? "bg-green-500/10 text-green-400 border border-green-500/20" : "bg-red-500/10 text-red-400 border border-red-500/20"
        }`}>
          {result.ok ? <CheckCircle2 className="w-4 h-4 shrink-0" /> : <XCircle className="w-4 h-4 shrink-0" />}
          {result.msg}
        </div>
      )}
    </div>
  );
}
