"use client";

import { signOut } from "next-auth/react";
import { useState } from "react";
import { SUPPORT_EMAIL } from "@/lib/plans";

type Props = {
  email: string;
};

export function AccountPrivacyActions({ email }: Props) {
  const [deleting, setDeleting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleDeleteAccount() {
    if (
      !confirm(
        "Delete your account permanently? This removes your jobs, uploads, and YouTube connection. This cannot be undone.",
      )
    ) {
      return;
    }

    setDeleting(true);
    setError(null);

    try {
      const res = await fetch("/api/account/delete", { method: "POST" });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to delete account");
      await signOut({ callbackUrl: "/" });
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to delete account");
      setDeleting(false);
    }
  }

  const dataRequestSubject = encodeURIComponent("Data export request");
  const dataRequestBody = encodeURIComponent(
    `Hello,\n\nI would like to request a copy of my personal data associated with my Songs2YT account (${email}).\n\nThank you.`,
  );

  return (
    <div className="space-y-4">
      {error && (
        <div className="rounded border border-red-500/50 bg-red-500/10 px-4 py-3 text-sm text-red-300">
          {error}
        </div>
      )}

      <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap">
        <a
          href={`mailto:${SUPPORT_EMAIL}?subject=${dataRequestSubject}&body=${dataRequestBody}`}
          className="inline-flex items-center justify-center rounded border border-gray-600 px-4 py-2 text-sm font-medium text-gray-200 transition-colors hover:bg-surface"
        >
          Request my data
        </a>

        <button
          type="button"
          onClick={handleDeleteAccount}
          disabled={deleting}
          className="inline-flex items-center justify-center rounded border border-red-600/50 px-4 py-2 text-sm font-medium text-red-300 transition-colors hover:bg-red-500/10 disabled:opacity-50"
        >
          {deleting ? "Deleting…" : "Delete account"}
        </button>
      </div>

      <p className="text-xs text-gray-500">
        Data requests are handled within the timelines described in our{" "}
        <a href="/privacy" className="text-gray-400 underline hover:text-white">
          Privacy Policy
        </a>
        .
      </p>
    </div>
  );
}
