"use client";

import { useState } from "react";
import { useSearchParams } from "next/navigation";

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000";

export default function DeleteConfirmForm() {
  const searchParams = useSearchParams();
  const token = searchParams.get("token");
  const [status, setStatus] = useState<
    "idle" | "submitting" | "done" | "error"
  >("idle");
  const [message, setMessage] = useState("");

  async function handleConfirm() {
    if (!token) return;
    setStatus("submitting");
    try {
      const res = await fetch(
        `${API_BASE_URL}/api/v1/custom/leads/deletion-requests/confirm/`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ token }),
        },
      );
      const json = await res.json();
      if (!res.ok) {
        setMessage(json?.error?.message ?? "确认失败，请重新申请删除。");
        setStatus("error");
        return;
      }
      setMessage(json?.message ?? "已成功删除您的个人信息。");
      setStatus("done");
    } catch {
      setMessage("网络错误，请稍后重试。");
      setStatus("error");
    }
  }

  if (!token) {
    return (
      <p className="text-slate-700">
        链接无效，请从确认邮件中重新打开该链接，或前往{" "}
        <a
          href="/privacy-policy/delete-request"
          className="text-primary underline"
        >
          申请删除个人信息
        </a>{" "}
        重新发起申请。
      </p>
    );
  }

  if (status === "done") {
    return <p className="text-slate-700">{message}</p>;
  }

  if (status === "error") {
    return <p className="text-red-600">{message}</p>;
  }

  return (
    <div className="space-y-4">
      <h1 className="text-2xl font-bold text-slate-900">确认删除个人信息</h1>
      <p className="text-slate-700">
        点击下方按钮将永久删除您通过表单提交给我们的个人信息，此操作不可撤销。
      </p>
      <button
        onClick={handleConfirm}
        disabled={status === "submitting"}
        className="rounded-full bg-red-600 px-6 py-2 font-medium text-white disabled:opacity-50"
      >
        {status === "submitting" ? "处理中..." : "确认删除"}
      </button>
    </div>
  );
}
