"use client";
import { Suspense, useState, useEffect } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Mail, RefreshCw, CheckCircle2, XCircle, Eye, EyeOff } from "lucide-react";
import { ToolLayout } from "@/components/ToolLayout";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { toast } from "sonner";

interface TestResult {
  success: boolean;
  message?: string;
  error?: string;
  messageId?: string;
}

function SmtpTestContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [form, setForm] = useState({
    host: searchParams.get("host") ?? "",
    port: searchParams.get("port") ?? "587",
    user: searchParams.get("user") ?? "",
    password: "",
    secure: false,
    from: "",
    to: "",
    subject: "",
  });
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<TestResult | null>(null);
  const [showPass, setShowPass] = useState(false);

  const updateUrl = () => {
    const params = new URLSearchParams();
    if (form.host) params.set("host", form.host);
    if (form.port) params.set("port", form.port);
    if (form.user) params.set("user", form.user);
    router.replace(`/smtp-test?${params}`, { scroll: false });
  };

  useEffect(() => {
    const h = searchParams.get("host");
    const p = searchParams.get("port");
    const u = searchParams.get("user");
    if (h || p || u) {
      setForm((f) => ({ ...f, host: h ?? f.host, port: p ?? f.port, user: u ?? f.user }));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const set = (k: string, v: string | boolean) => setForm((f) => ({ ...f, [k]: v }));

  const handleTest = async () => {
    if (!form.host || !form.port) { toast.error("Host and port are required"); return; }
    setLoading(true);
    setResult(null);
    updateUrl();
    try {
      const res = await fetch("/api/smtp-test", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const json = await res.json();
      setResult(json);
    } catch {
      toast.error("Request failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <ToolLayout icon={Mail} title="SMTP Mailer Test" description="Test SMTP connection and optionally send a test email.">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Config */}
        <div className="glass-card rounded-xl p-5 space-y-4">
          <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60">Server Configuration</p>

          <div className="grid grid-cols-3 gap-2">
            <div className="col-span-2 space-y-1">
              <Label>SMTP Host</Label>
              <Input value={form.host} onChange={(e) => set("host", e.target.value)} placeholder="smtp.example.com" />
            </div>
            <div className="space-y-1">
              <Label>Port</Label>
              <Input value={form.port} onChange={(e) => set("port", e.target.value)} placeholder="587" />
            </div>
          </div>

          <div className="space-y-1">
            <Label>Username</Label>
            <Input value={form.user} onChange={(e) => set("user", e.target.value)} placeholder="user@example.com" />
          </div>

          <div className="space-y-1">
            <Label>Password</Label>
            <div className="relative">
              <Input
                type={showPass ? "text" : "password"}
                value={form.password}
                onChange={(e) => set("password", e.target.value)}
                placeholder="••••••••"
                className="pr-9"
              />
              <button
                type="button"
                onClick={() => setShowPass((v) => !v)}
                className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
              >
                {showPass ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </div>

          <label className="flex items-center gap-2 cursor-pointer">
            <input type="checkbox" checked={form.secure} onChange={(e) => set("secure", e.target.checked)} className="rounded" />
            <span className="text-sm text-muted-foreground">Use SSL/TLS (port 465)</span>
          </label>

          <div className="flex gap-2 pt-1">
            <Button onClick={handleTest} disabled={loading} className="flex-1">
              {loading ? <RefreshCw className="h-4 w-4 animate-spin" /> : "Test Connection"}
            </Button>
          </div>
        </div>

        {/* Optional email */}
        <div className="space-y-4">
          <div className="glass-card rounded-xl p-5 space-y-4">
            <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground/60">Send Test Email <span className="text-muted-foreground/40 font-normal normal-case">(optional)</span></p>

            <div className="space-y-1">
              <Label>From</Label>
              <Input value={form.from} onChange={(e) => set("from", e.target.value)} placeholder="from@example.com" />
            </div>
            <div className="space-y-1">
              <Label>To</Label>
              <Input value={form.to} onChange={(e) => set("to", e.target.value)} placeholder="to@example.com" />
            </div>
            <div className="space-y-1">
              <Label>Subject</Label>
              <Input value={form.subject} onChange={(e) => set("subject", e.target.value)} placeholder="SMTP Test Email" />
            </div>
          </div>

          {/* Result */}
          {result && (
            <div className={`glass-card rounded-xl p-4 animate-fade-up ${result.success ? "border-green-500/20" : "border-red-500/20"}`}>
              <div className="flex items-start gap-3">
                {result.success
                  ? <CheckCircle2 className="h-5 w-5 text-green-400 shrink-0 mt-0.5" />
                  : <XCircle className="h-5 w-5 text-red-400 shrink-0 mt-0.5" />}
                <div>
                  <p className="text-sm font-medium">{result.success ? "Success" : "Failed"}</p>
                  <p className="text-xs text-muted-foreground mt-0.5">{result.message ?? result.error}</p>
                  {result.messageId && (
                    <p className="text-xs text-muted-foreground mt-1 font-mono">Message-ID: {result.messageId}</p>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </ToolLayout>
  );
}

export default function SmtpTestPage() {
  return <Suspense><SmtpTestContent /></Suspense>;
}
