"use client";

import { useState } from "react";

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

export default function DeleteRequestPage() {
  const [contact, setContact] = useState("");
  const [status, setStatus] = useState<
    "idle" | "submitting" | "done" | "error"
  >("idle");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setStatus("submitting");
    try {
      const res = await fetch(
        `${API_BASE_URL}/api/v1/custom/leads/deletion-requests/`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ contact }),
        },
      );
      if (!res.ok) throw new Error("request failed");
      setStatus("done");
    } catch {
      setStatus("error");
    }
  }

  if (status === "done") {
    return (
      <div className="mx-auto max-w-xl px-6 py-24 text-center text-slate-700">
        如果我们持有与该邮箱关联的信息，确认邮件将发送至该邮箱，请查收并点击链接完成删除确认。
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-xl px-6 py-24">
      <h1 className="mb-4 text-2xl font-bold text-slate-900">
        申请删除个人信息
      </h1>
      <p className="mb-6 text-slate-700">
        依据《中华人民共和国个人信息保护法》（PIPL），您可以申请删除我们通过表单收集的您的个人信息。
        请输入您提交表单时使用的邮箱，我们将向该邮箱发送确认邮件，点击邮件中的链接即可完成删除。
      </p>
      <form onSubmit={handleSubmit} className="flex gap-2">
        <input
          type="email"
          required
          value={contact}
          onChange={(e) => setContact(e.target.value)}
          placeholder="请输入邮箱"
          className="flex-1 rounded-lg border border-slate-200 px-4 py-2"
        />
        <button
          type="submit"
          disabled={status === "submitting"}
          className="rounded-full bg-primary px-6 py-2 font-medium text-white disabled:opacity-50"
        >
          {status === "submitting" ? "提交中..." : "提交申请"}
        </button>
      </form>
      {status === "error" && (
        <p className="mt-4 text-red-600">提交失败，请稍后重试。</p>
      )}
    </div>
  );
}
