"use client";

import React, { useState, Suspense } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  Shield,
  Trash2,
  CheckCircle2,
  AlertTriangle,
  ArrowLeft,
  Mail,
  Lock,
  RefreshCw,
  Sparkles,
  Smartphone,
  UserCheck,
  Info,
} from "lucide-react";

function DeleteAccountContent() {
  const searchParams = useSearchParams();

  // Query params passed from mobile app
  const queryToken = searchParams.get("token") || "";
  const queryUserId = searchParams.get("userId") || "";
  const queryEmail = searchParams.get("email") || "";

  // Component state
  const [token, setToken] = useState(queryToken);
  const [agreed, setAgreed] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isDeleted, setIsDeleted] = useState(false);
  const [successMessage, setSuccessMessage] = useState("");

  const hasAuth = Boolean(queryToken || token);

  const handleDelete = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    const activeToken = token.trim();
    if (!activeToken) {
      setError("Authentication token is missing. Please initiate deletion from the IMZY app.");
      return;
    }

    if (!agreed) {
      setError("Please confirm your acknowledgement before proceeding.");
      return;
    }

    setLoading(true);

    try {
      const res = await fetch("/api/delete-account", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token: activeToken }),
      });

      const data = await res.json().catch(() => ({}));

      if (!res.ok || !data.success) {
        setError(data.error || "Failed to delete account. Token may be invalid or expired.");
      } else {
        setSuccessMessage(data.message || "User account deleted successfully");
        setIsDeleted(true);
      }
    } catch {
      setError("Network connection failed. Please check your internet and try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#07090E] text-slate-100 selection:bg-amber-500/30 selection:text-amber-200">
      {/* Ambient background glow */}
      <div className="fixed inset-0 pointer-events-none overflow-hidden">
        <div className="absolute -top-40 left-1/2 -translate-x-1/2 w-[800px] h-[500px] bg-gradient-to-b from-amber-500/10 via-amber-600/5 to-transparent blur-3xl opacity-60 rounded-full" />
        <div className="absolute top-1/2 -right-48 w-[400px] h-[400px] bg-rose-500/5 blur-3xl rounded-full" />
      </div>

      {/* Header */}
      <header className="relative z-50 border-b border-white/5 bg-[#07090E]/80 backdrop-blur-xl sticky top-0">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 h-18 flex items-center justify-between">
          <Link
            href="/"
            className="group flex items-center gap-3 transition-opacity hover:opacity-90"
          >
            <div className="w-10 h-10 rounded-xl bg-gradient-to-tr from-amber-500 via-amber-400 to-amber-600 flex items-center justify-center font-bold text-slate-950 text-xl shadow-lg shadow-amber-500/20 group-hover:scale-105 transition-transform">
              I
            </div>
            <div>
              <span className="text-lg font-bold tracking-wider text-white">
                IMZY
              </span>
              <span className="block text-[10px] tracking-widest uppercase text-amber-400 font-semibold">
                Account Security
              </span>
            </div>
          </Link>

          <div className="flex items-center gap-3">
            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium bg-amber-500/10 text-amber-300 border border-amber-500/20">
              <Shield className="w-3.5 h-3.5 text-amber-400" />
              Google Play Compliant
            </span>
            <Link
              href="/"
              className="inline-flex items-center gap-1.5 text-xs text-slate-400 hover:text-slate-200 transition-colors py-1 px-2.5 rounded-lg border border-white/5 hover:border-white/10 bg-white/[0.02]"
            >
              <ArrowLeft className="w-3.5 h-3.5" />
              Back
            </Link>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="relative z-10 max-w-3xl mx-auto px-4 sm:px-6 py-10 sm:py-16">
        {/* Title */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4 }}
          className="text-center mb-10"
        >
          <div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full text-xs font-semibold bg-amber-400/10 text-amber-300 border border-amber-400/20 mb-4 backdrop-blur-md">
            <Sparkles className="w-3.5 h-3.5 text-amber-400" />
            Official Account & Data Deletion
          </div>
          <h1 className="text-3xl sm:text-4xl font-extrabold tracking-tight text-white mb-3">
            Delete Your <span className="text-transparent bg-clip-text bg-gradient-to-r from-amber-200 via-amber-400 to-amber-100">IMZY Account</span>
          </h1>
          <p className="text-sm text-slate-400 max-w-lg mx-auto leading-relaxed">
            In compliance with Google Play Store Data Safety policies, you can permanently erase your account and all associated personal records.
          </p>
        </motion.div>

        {/* Dynamic State: Success or Form or Missing Token Guidance */}
        <AnimatePresence mode="wait">
          {isDeleted ? (
            /* Success View */
            <motion.div
              key="success-card"
              initial={{ opacity: 0, scale: 0.96 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.96 }}
              className="p-8 sm:p-10 rounded-3xl bg-gradient-to-b from-[#11141E] to-[#0A0D14] border border-amber-500/30 shadow-2xl shadow-black/80 backdrop-blur-xl text-center"
            >
              <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-amber-500/10 border border-amber-400/40 mb-6 shadow-xl shadow-amber-500/10">
                <CheckCircle2 className="w-10 h-10 text-amber-400" />
              </div>

              <h2 className="text-2xl sm:text-3xl font-bold text-white mb-3">
                Account Successfully Deleted
              </h2>
              <p className="text-sm text-slate-300 max-w-md mx-auto mb-6">
                {successMessage || "Your IMZY user account and associated personal data have been completely deleted."}
              </p>

              {queryEmail && (
                <div className="inline-block px-4 py-2 rounded-xl bg-slate-900 border border-white/10 text-xs font-mono text-slate-300 mb-8">
                  Deleted Account: <span className="text-amber-400 font-semibold">{queryEmail}</span>
                </div>
              )}

              <div className="p-4 rounded-xl bg-white/[0.02] border border-white/5 text-xs text-slate-400 max-w-md mx-auto mb-8 leading-relaxed">
                You have been signed out on all devices. If you wish to use IMZY in the future, you will need to create a new account.
              </div>

              <Link
                href="/"
                className="inline-flex items-center justify-center px-6 py-3 rounded-xl bg-gradient-to-r from-amber-400 to-amber-500 hover:from-amber-300 hover:to-amber-400 text-slate-950 font-semibold text-xs transition-all shadow-lg shadow-amber-500/20 hover:scale-105"
              >
                Return to Home
              </Link>
            </motion.div>
          ) : hasAuth ? (
            /* Authenticated Deletion Form */
            <motion.div
              key="auth-form"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="relative p-6 sm:p-10 rounded-3xl bg-gradient-to-b from-[#11141E] to-[#0A0D14] border border-white/10 shadow-2xl shadow-black/80 backdrop-blur-xl overflow-hidden"
            >
              <div className="absolute top-0 left-0 right-0 h-[2px] bg-gradient-to-r from-transparent via-amber-400 to-transparent opacity-80" />

              {/* User Identity Card */}
              <div className="p-5 rounded-2xl bg-slate-950/70 border border-white/5 mb-6">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2 text-xs font-semibold text-amber-300">
                    <UserCheck className="w-4 h-4 text-amber-400" />
                    Authenticated Account
                  </div>
                  <span className="text-[10px] px-2.5 py-0.5 rounded-full bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 font-medium">
                    Verified Session
                  </span>
                </div>

                <div className="space-y-2 text-xs">
                  {queryEmail && (
                    <div className="flex items-center justify-between">
                      <span className="text-slate-400">Account Email:</span>
                      <span className="font-semibold text-slate-100 font-mono">{queryEmail}</span>
                    </div>
                  )}
                  {queryUserId && (
                    <div className="flex items-center justify-between">
                      <span className="text-slate-400">User ID:</span>
                      <span className="font-mono text-slate-300 text-[11px]">{queryUserId}</span>
                    </div>
                  )}
                </div>
              </div>

              {/* Error Alert */}
              {error && (
                <div className="mb-6 p-4 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-300 text-xs sm:text-sm flex items-start gap-3">
                  <AlertTriangle className="w-5 h-5 text-rose-400 shrink-0 mt-0.5" />
                  <div className="flex-1">
                    <p className="font-semibold text-rose-200">Unable to Delete Account</p>
                    <p className="mt-0.5 text-rose-300/90">{error}</p>
                  </div>
                  <button
                    onClick={() => setError(null)}
                    className="text-rose-400 hover:text-rose-200 text-xs font-medium px-1.5 py-0.5"
                  >
                    Dismiss
                  </button>
                </div>
              )}

              {/* Data Safety Notice */}
              <div className="mb-6 p-4 rounded-xl bg-amber-500/5 border border-amber-500/20 text-xs text-slate-300 space-y-2">
                <div className="flex items-center gap-2 font-semibold text-amber-300">
                  <Lock className="w-4 h-4 text-amber-400" />
                  Permanent Data Deletion Notice
                </div>
                <p className="text-slate-400 leading-relaxed">
                  Executing this action will immediately remove your authentication profile, account credentials, uploaded media, personal messages, and activity data from IMZY servers.
                </p>
              </div>

              <form onSubmit={handleDelete} className="space-y-6">
                {/* Confirmation Checkbox */}
                <label className="flex items-start gap-3 cursor-pointer select-none">
                  <input
                    type="checkbox"
                    checked={agreed}
                    onChange={(e) => {
                      setAgreed(e.target.checked);
                      if (error) setError(null);
                    }}
                    className="mt-0.5 w-4 h-4 rounded border-white/20 bg-slate-900 text-amber-500 focus:ring-amber-400/30 accent-amber-500 shrink-0"
                  />
                  <span className="text-xs text-slate-300 leading-relaxed">
                    I understand that this action is irreversible and permanently erases my IMZY user account and all associated data.
                  </span>
                </label>

                {/* Submit Button */}
                <button
                  type="submit"
                  disabled={loading}
                  className="w-full py-3.5 px-6 rounded-xl font-semibold text-sm text-white bg-gradient-to-r from-rose-600 via-rose-500 to-amber-600 hover:from-rose-500 hover:to-amber-500 transition-all duration-300 shadow-lg shadow-rose-600/20 hover:shadow-rose-600/30 hover:scale-[1.01] active:scale-[0.99] disabled:opacity-60 disabled:pointer-events-none flex items-center justify-center gap-2"
                >
                  {loading ? (
                    <>
                      <RefreshCw className="w-4 h-4 animate-spin" />
                      Deleting Account...
                    </>
                  ) : (
                    <>
                      <Trash2 className="w-4 h-4" />
                      Permanently Delete My Account
                    </>
                  )}
                </button>
              </form>
            </motion.div>
          ) : (
            /* Missing Token Guidance Card */
            <motion.div
              key="no-token-card"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="p-6 sm:p-10 rounded-3xl bg-gradient-to-b from-[#11141E] to-[#0A0D14] border border-white/10 shadow-2xl backdrop-blur-xl"
            >
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-xl bg-amber-500/10 border border-amber-500/20 flex items-center justify-center text-amber-400">
                  <Smartphone className="w-5 h-5" />
                </div>
                <div>
                  <h2 className="text-lg font-bold text-white">
                    Initiate Deletion from IMZY App
                  </h2>
                  <p className="text-xs text-slate-400">
                    Secure authentication required
                  </p>
                </div>
              </div>

              <p className="text-xs sm:text-sm text-slate-300 mb-5 leading-relaxed">
                To protect user security and prevent unauthorized account deletion, this web portal requires a verified authorization token generated by the IMZY mobile application:
              </p>

              <div className="p-4 rounded-2xl bg-slate-950/60 border border-white/5 space-y-2 mb-6">
                <p className="text-xs font-semibold text-amber-300">How to Delete from App:</p>
                <ol className="list-decimal list-inside space-y-1.5 text-xs text-slate-300 pl-1">
                  <li>Open the <strong>IMZY</strong> mobile app on your phone.</li>
                  <li>Go to <strong>Preferences</strong> &gt; <strong>Account Security & Data management</strong>.</li>
                  <li>Tap <strong>Delete Account & Data</strong> to launch this portal with your authenticated credentials.</li>
                </ol>
              </div>

              {/* Advanced Manual Token Input for testing or direct paste */}
              <div className="pt-4 border-t border-white/5">
                <details className="group">
                  <summary className="text-xs text-slate-400 hover:text-slate-200 cursor-pointer select-none flex items-center gap-1.5">
                    <Info className="w-3.5 h-3.5 text-amber-400" />
                    Have an authorization token? Enter it manually
                  </summary>
                  <div className="mt-4 space-y-3">
                    <textarea
                      rows={3}
                      value={token}
                      onChange={(e) => setToken(e.target.value)}
                      placeholder="Paste your Bearer token here..."
                      className="w-full px-3.5 py-2.5 rounded-xl bg-slate-900 border border-white/10 text-xs font-mono text-slate-200 focus:outline-none focus:border-amber-400"
                    />
                    <button
                      onClick={() => {
                        if (token.trim()) setError(null);
                      }}
                      className="px-4 py-2 rounded-lg bg-amber-400 hover:bg-amber-300 text-slate-950 text-xs font-semibold transition-colors"
                    >
                      Verify Token
                    </button>
                  </div>
                </details>
              </div>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Footer info for Google Play auditors */}
        <footer className="mt-16 pt-8 border-t border-white/10 text-center text-xs text-slate-500">
          <div className="flex flex-wrap items-center justify-center gap-4 mb-2">
            <Link
              href="/privacy-policy"
              className="hover:text-amber-400 transition-colors"
            >
              Privacy Policy
            </Link>
            <span className="text-slate-700">&bull;</span>
            <a
              href="mailto:info@globe13.com"
              className="inline-flex items-center gap-1.5 hover:text-amber-400 transition-colors"
            >
              <Mail className="w-3.5 h-3.5" />
              info@globe13.com
            </a>
            <span className="text-slate-700">&bull;</span>
            <span>Google Play Data Safety</span>
          </div>
          <p className="text-[11px] text-slate-600">
            Account deletion requests are processed in strict compliance with Google Play Developer Policy and global privacy standards.
          </p>
        </footer>
      </main>
    </div>
  );
}

export default function DeleteAccountPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-[#07090E] flex items-center justify-center text-slate-400 text-sm">
          <RefreshCw className="w-5 h-5 animate-spin text-amber-400 mr-2" />
          Loading secure portal...
        </div>
      }
    >
      <DeleteAccountContent />
    </Suspense>
  );
}
