import { useEffect, useState } from "react";
import { MailCheck, MailX, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";

// Unsubscribe is handled on Lovable Cloud (where the email queue + suppression tables live),
// not the external Supabase backend the rest of the app uses.
const LC_URL = "https://xckpovwdmnlravxzurcr.supabase.co";
const LC_ANON = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inhja3BvdndkbW5scmF2eHp1cmNyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzg2OTA1NDUsImV4cCI6MjA5NDI2NjU0NX0.RgmO7WSvVq_XrmGkAF5gi38p2VkGMSK_qL9ceorpcoM";

export default function UnsubscribePage() {
  const token = new URLSearchParams(window.location.search).get("token") || "";
  const [state, setState] = useState<"loading" | "valid" | "success" | "invalid">("loading");

  useEffect(() => {
    if (!token) { setState("invalid"); return; }
    fetch(`${LC_URL}/functions/v1/handle-email-unsubscribe?token=${encodeURIComponent(token)}`, {
      headers: { apikey: LC_ANON, Authorization: `Bearer ${LC_ANON}` },
    }).then(async (res) => {
      const data = await res.json().catch(() => ({}));
      setState(res.ok && data.valid ? "valid" : "invalid");
    }).catch(() => setState("invalid"));
  }, [token]);

  const confirm = async () => {
    try {
      const res = await fetch(`${LC_URL}/functions/v1/handle-email-unsubscribe`, {
        method: "POST",
        headers: { apikey: LC_ANON, Authorization: `Bearer ${LC_ANON}`, "Content-Type": "application/json" },
        body: JSON.stringify({ token }),
      });
      setState(res.ok ? "success" : "invalid");
    } catch {
      setState("invalid");
    }
  };

  return (
    <main className="flex min-h-screen items-center justify-center bg-background p-6">
      <Card className="w-full max-w-md">
        <CardContent className="p-8 text-center">
          {state === "loading" && <Loader2 className="mx-auto mb-4 h-8 w-8 animate-spin text-primary" />}
          {state === "valid" && <MailCheck className="mx-auto mb-4 h-10 w-10 text-primary" />}
          {(state === "invalid" || state === "success") && <MailX className="mx-auto mb-4 h-10 w-10 text-muted-foreground" />}
          <h1 className="text-xl font-semibold text-foreground">
            {state === "success" ? "You’re unsubscribed" : state === "invalid" ? "Link unavailable" : "Email preferences"}
          </h1>
          <p className="mt-2 text-sm text-muted-foreground">
            {state === "valid" ? "Confirm that you no longer want to receive these app email notifications." : state === "success" ? "You will no longer receive these app email notifications." : state === "invalid" ? "This unsubscribe link is invalid or has already been used." : "Checking your link…"}
          </p>
          {state === "valid" && <Button className="mt-6" onClick={confirm}>Confirm unsubscribe</Button>}
        </CardContent>
      </Card>
    </main>
  );
}
