"use client";

import { useEffect, useRef, useState } from "react";
import { sendEmailAction, type ApiResponse, type EmailRequest } from "@/app/actions/sendEmail";
import { Button, Field, Input, Textarea } from "@/components/ui/form";

export default function SendEmailForm(): JSX.Element {
  const [result, setResult] = useState<
    ApiResponse<EmailRequest> | { error: string } | null
  >(null);
  const [submitting, setSubmitting] = useState(false);

  const [showSuccess, setShowSuccess] = useState(false);
  const successTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    return () => {
      if (successTimerRef.current) clearTimeout(successTimerRef.current);
    };
  }, []);

  async function onSubmit(e: React.FormEvent<HTMLFormElement>): Promise<void> {
    e.preventDefault();
    setResult(null);

    setShowSuccess(false);
    if (successTimerRef.current) clearTimeout(successTimerRef.current);

    const form = new FormData(e.currentTarget);

    const recipient = String(form.get("recipient") ?? "");
    const subject = String(form.get("subject") ?? "");
    const body = String(form.get("body") ?? "");

    try {
      setSubmitting(true);
      const data = await sendEmailAction({ recipient, subject, body });
      setResult(data);

      if (data?.success === true) {
        setShowSuccess(true);

        successTimerRef.current = setTimeout(() => {
          setShowSuccess(false);
          setResult(null); // clear the response panel too
        }, 2000);
      }
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setResult({ error: message });
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="mx-auto w-full max-w-xl px-4 py-10 text-zinc-50">
      <h1 className="text-2xl font-semibold tracking-tight">
        Send <span className="text-amber-300">Email</span>
      </h1>
      <p className="mt-2 text-sm text-zinc-400">
        Compose a message and send it from the admin panel.
      </p>

      <form onSubmit={onSubmit} className="mt-6 space-y-4">
        {result && "error" in result && (
          <div className="rounded-md border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-200">
            {result.error}
          </div>
        )}

        <Field label="Recipient" htmlFor="recipient">
          <Input
            id="recipient"
            name="recipient"
            type="email"
            placeholder="user@example.com"
            defaultValue="user@example.com"
            required
          />
        </Field>

        <Field label="Subject" htmlFor="subject">
          <Input
            id="subject"
            name="subject"
            placeholder="Test subject"
            defaultValue="Test subject"
            required
          />
        </Field>

        <Field label="Body" htmlFor="body">
          <Textarea
            id="body"
            name="body"
            placeholder="Write your message…"
            defaultValue="Test body"
            rows={6}
            required
          />
        </Field>

        <Button type="submit" disabled={submitting}>
          {submitting ? "Sending…" : showSuccess ? "Success" : "Send"}
        </Button>

        <div className="rounded-md border border-zinc-800 bg-zinc-950/60 p-3">
          <div className="text-xs font-medium text-zinc-400">Response</div>
          <pre className="mt-2 overflow-x-auto text-xs text-zinc-200">
            {result ? JSON.stringify(result, null, 2) : "No response yet."}
          </pre>
        </div>
      </form>
    </div>
  );
}