"use client";

import { useState } from "react";

export default function PrivacySettingsPage() {
  const [exporting, setExporting] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [confirmText, setConfirmText] = useState("");
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  async function handleExport() {
    setExporting(true);
    setMessage(null);
    try {
      const res = await fetch("/api/user/data-export");
      if (!res.ok) throw new Error("Export failed");
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `my-data-export-${new Date().toISOString().slice(0, 10)}.json`;
      a.click();
      URL.revokeObjectURL(url);
      setMessage({ type: "success", text: "Your data has been downloaded." });
    } catch {
      setMessage({ type: "error", text: "Failed to export data. Please try again." });
    } finally {
      setExporting(false);
    }
  }

  async function handleDelete() {
    if (confirmText !== "DELETE") return;
    setDeleting(true);
    setMessage(null);
    try {
      const res = await fetch("/api/user/data-delete", { method: "POST" });
      if (!res.ok) throw new Error("Deletion failed");
      window.location.href = "/login?deleted=1";
    } catch {
      setMessage({ type: "error", text: "Failed to delete account. Please try again." });
      setDeleting(false);
    }
  }

  return (
    <div className="max-w-3xl mx-auto">
      <h1 className="text-3xl font-bold text-text mb-6">Privacy Settings</h1>

      <div className="space-y-6">
        {/* Privacy Info */}
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold text-text mb-3">Your Privacy</h2>
          <div className="text-text-muted text-sm space-y-2">
            <p>
              We take your privacy seriously. Under the General Data Protection Regulation (GDPR) and
              other applicable privacy laws, you have the right to access, export, and delete your personal data.
            </p>
            <p>
              <strong className="text-text">Data we store:</strong> Your profile information (name, email, bio),
              photos and galleries you have uploaded, messages, transaction history, favorites, and usage logs.
            </p>
            <p>
              <strong className="text-text">How we use your data:</strong> To provide our services, process
              payments, prevent fraud, and improve your experience. We do not sell your personal data to third parties.
            </p>
            <p>
              For more details, see our{" "}
              <a href="/privacy-policy" className="text-primary underline">Privacy Policy</a>.
            </p>
          </div>
        </div>

        {/* Export Data */}
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold text-text mb-3">Download My Data</h2>
          <p className="text-text-muted text-sm mb-4">
            Export a copy of all personal data we hold about you, including your profile,
            photos, galleries, messages, transactions, and favorites. The file will be
            downloaded in JSON format.
          </p>
          <button
            onClick={handleExport}
            disabled={exporting}
            className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50"
          >
            {exporting ? "Exporting..." : "Download My Data"}
          </button>
        </div>

        {/* Delete Account */}
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold text-red-400 mb-3">Delete My Account</h2>
          <div className="bg-red-900/20 border border-red-800 rounded-lg p-4 mb-4">
            <p className="text-text-muted text-sm">
              This will permanently anonymize your account and delete all associated data including
              photos, galleries, messages, favorites, and notifications. This action cannot be undone.
              You will be signed out immediately after deletion.
            </p>
          </div>

          {!showDeleteConfirm ? (
            <button
              onClick={() => setShowDeleteConfirm(true)}
              className="bg-red-600 hover:bg-red-700 text-white px-6 py-2.5 rounded-lg font-semibold transition-colors"
            >
              Delete My Account
            </button>
          ) : (
            <div className="space-y-3">
              <label className="block text-sm font-medium text-text">
                Type <span className="text-red-400 font-mono">DELETE</span> to confirm
              </label>
              <input
                type="text"
                value={confirmText}
                onChange={(e) => setConfirmText(e.target.value)}
                className="w-full max-w-xs bg-background border border-red-800 rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-red-500"
                placeholder="DELETE"
              />
              {/* R16 D.3: live validation hint so users see immediately why
                  the button is disabled — the case-sensitive match was
                  silently rejecting "delete" / "Delete" without feedback. */}
              {confirmText.length > 0 && (
                <p className={`text-xs ${confirmText === "DELETE" ? "text-green-400" : "text-red-400"}`}>
                  {confirmText === "DELETE"
                    ? "✓ Confirmation matches"
                    : "✗ Must match \"DELETE\" exactly (uppercase)"}
                </p>
              )}
              <div className="flex gap-3">
                <button
                  onClick={handleDelete}
                  disabled={confirmText !== "DELETE" || deleting}
                  className="bg-red-600 hover:bg-red-700 text-white px-6 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50"
                >
                  {deleting ? "Deleting..." : "Confirm Deletion"}
                </button>
                <button
                  onClick={() => { setShowDeleteConfirm(false); setConfirmText(""); }}
                  className="px-6 py-2.5 rounded-lg border border-surface-light text-text-muted hover:text-text transition-colors"
                >
                  Cancel
                </button>
              </div>
            </div>
          )}
        </div>

        {message && (
          <div
            className={`rounded-lg p-4 text-sm ${
              message.type === "success"
                ? "bg-green-900/20 border border-green-800 text-green-400"
                : "bg-red-900/20 border border-red-800 text-red-400"
            }`}
          >
            {message.text}
          </div>
        )}
      </div>
    </div>
  );
}
