"use client";

import { useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { useAlertConfirm } from "@/components/ui/alert-dialog";

/**
 * MA1: "Approve + send" outbound Gmail button.
 *
 * Surfaces a confirm-then-send action next to draft / suggested-reply rows.
 * Talks to /api/google/send. Stays inert until the user confirms via
 * AlertDialog — this is production-facing and real mail goes out.
 */

interface SendEmailButtonProps {
  /** Which connected Gmail account to send FROM. Required by the server route. */
  accountId: string;
  to: string;
  subject: string;
  bodyText: string;
  /** Optional rich HTML body. If absent the server wraps bodyText in a <pre>. */
  bodyHtml?: string;
  threadId?: string;
  cc?: string;
  bcc?: string;
  replyTo?: string;
  /** Fires after a successful send. Inbox can refresh / mark thread sent. */
  onSent?: (result: { id: string | null; threadId: string | null }) => void;
  /** Optional size + class overrides — defaults to size="sm" + brand variant. */
  size?: "sm" | "default";
  className?: string;
}

interface SendResponse {
  ok: boolean;
  id?: string | null;
  threadId?: string | null;
  error?: string;
  code?: string;
  reconnectUrl?: string;
}

export function SendEmailButton(props: SendEmailButtonProps) {
  const {
    accountId,
    to,
    subject,
    bodyText,
    bodyHtml,
    threadId,
    cc,
    bcc,
    replyTo,
    onSent,
    size = "sm",
    className,
  } = props;

  const [state, setState] = useState<"idle" | "sending" | "sent" | "error">("idle");
  const [errorMsg, setErrorMsg] = useState<string>("");
  const [missingScope, setMissingScope] = useState(false);
  const { confirm: confirmAlert, AlertConfirmPortal } = useAlertConfirm();

  const buttonLabel = (() => {
    if (state === "sending") return "Sending...";
    if (state === "sent") return "Sent";
    return "Approve + send";
  })();

  async function handleClick() {
    if (state === "sending" || state === "sent") return;

    // AlertDialog escape — production safety net.
    const truncatedSubject = subject.length > 80 ? subject.slice(0, 77) + "..." : subject;
    const proceed = await confirmAlert({
      title: `Send this email to ${to}?`,
      description: `Subject: "${truncatedSubject}"`,
      actionLabel: "Send",
    });
    if (!proceed) return;

    setState("sending");
    setErrorMsg("");
    setMissingScope(false);

    try {
      const resp = await fetch("/api/google/send", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          accountId,
          to,
          subject,
          bodyText,
          bodyHtml,
          cc,
          bcc,
          replyTo,
          threadId,
        }),
      });

      let data: SendResponse = { ok: false };
      try {
        data = (await resp.json()) as SendResponse;
      } catch {
        // Non-JSON response; fall through to generic error below.
      }

      if (!resp.ok || !data.ok) {
        if (data.code === "MISSING_SCOPE") {
          setMissingScope(true);
          setErrorMsg(
            data.error ||
              "Gmail send permission not granted. Re-link Gmail to enable sending."
          );
        } else {
          setErrorMsg(data.error || `Send failed (HTTP ${resp.status})`);
        }
        setState("error");
        return;
      }

      setState("sent");
      onSent?.({ id: data.id ?? null, threadId: data.threadId ?? null });
    } catch (e) {
      setErrorMsg(e instanceof Error ? e.message : "Send failed");
      setState("error");
    }
  }

  return (
    <>
    <div className={`inline-flex items-center gap-2 flex-wrap ${className ?? ""}`}>
      <Button
        type="button"
        variant={state === "sent" ? "outline" : "brand"}
        size={size}
        disabled={state === "sending" || state === "sent"}
        onClick={handleClick}
        title={state === "sent" ? "This message has been sent" : "Confirm and send via Gmail"}
      >
        {state === "sending" && (
          <span
            className="inline-block w-3 h-3 rounded-full border-2 border-white/30 border-t-white animate-spin"
            aria-hidden
          />
        )}
        {buttonLabel}
        {state === "sent" && (
          <span aria-hidden className="ml-0.5">
            ✓
          </span>
        )}
      </Button>

      {state === "sent" && (
        <span
          className="inline-flex items-center rounded-full border border-green-300 bg-green-50 text-green-900 px-2 py-0.5 text-[10px] font-medium dark:bg-green-900/30 dark:text-green-100 dark:border-green-900/40"
          aria-live="polite"
        >
          Sent ✓
        </span>
      )}

      {state === "error" && (
        <div className="text-[11px] text-destructive max-w-xs" role="alert">
          {errorMsg}
          {missingScope && (
            <>
              {" "}
              <Link
                href="/app/settings/connections"
                className="underline font-medium text-destructive hover:text-destructive/80"
              >
                Re-link Gmail to enable sending →
              </Link>
            </>
          )}
        </div>
      )}
    </div>
    <AlertConfirmPortal />
    </>
  );
}
