"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "motion/react";
import {
  ShieldCheck,
  Database,
  Share2,
  Cookie,
  UserCog,
  Archive,
  Globe,
  Lock,
  Download,
  Loader2,
  ChevronRight,
  Clock,
  FileText,
  Info,
} from "lucide-react";
import { cn } from "@/lib/utils";

const privacyData = [
  {
    id: "collection",
    title: "1. Information We Collect",
    icon: <Database className="w-5 h-5" />,
    content: "We collect information to provide effective and secure hosting services. Data is categorized as Personal and Non-Personal information.",
    points: [
      "Personal: Name, Email, Phone Number, Payment Information.",
      "Non-Personal: IP Address, Browser Type, Operating System, Activity Logs.",
      "Purpose: Customer identification, service communication, and security verification.",
    ],
  },
  {
    id: "usage",
    title: "2. How We Use Data",
    icon: <FileText className="w-5 h-5" />,
    content: "Your data is a vital asset for our operations. We do not use your data for any purpose beyond providing Sonata services.",
    points: [
      "Provide, maintain, and improve hosting services.",
      "Communication regarding account updates, system changes, and promotions.",
      "Early detection of fraud and system security threats.",
      "Compliance with applicable legal obligations.",
    ],
  },
  {
    id: "protection",
    title: "3. Data Protection",
    icon: <ShieldCheck className="w-5 h-5" />,
    content: "We implement the highest industry security standards to protect your data from unauthorized access, alteration, or leakage.",
    points: [
      "SSL/TLS encryption for all sensitive data transmissions.",
      "Secure storage for personal and payment information.",
      "Regular security audits and routine system updates.",
      "Data access restricted to authorized staff only (Strict Access Control).",
    ],
  },
  {
    id: "sharing",
    title: "4. Sharing & Disclosure",
    icon: <Share2 className="w-5 h-5" />,
    content: "Sonata's principle is to NOT sell, rent, or trade your personal data to any party.",
    points: [
      "Trusted Third Parties: Payment Gateways (Stripe/PayPal) & Email Services.",
      "Legal Obligations: If requested by law enforcement authorities.",
      "Business Transfers: In the event of a merger, acquisition, or asset sale.",
    ],
  },
  {
    id: "cookies",
    title: "5. Cookies & Tracking",
    icon: <Cookie className="w-5 h-5" />,
    content: "We use cookies to enhance your experience on our website and panel. You can manage these preferences through your browser settings.",
    points: [
      "Essential Cookies: Required for the website to function normally.",
      "Analytical Cookies: Understanding usage patterns to improve services.",
      "Marketing Cookies: Displaying relevant offers (Optional).",
    ],
  },
  {
    id: "rights",
    title: "6. Your Data Rights",
    icon: <UserCog className="w-5 h-5" />,
    content: "As a customer, you have full control over your data in accordance with applicable data protection regulations.",
    points: [
      "Right to Access & Correct: Request a copy or correction of your data.",
      "Right to Erasure (Right to be Forgotten): Request deletion of your data if no contractual obligation exists.",
      "Data Portability: Receive your data in a structured, machine-readable format.",
      "Right to Restrict Processing: Request limitations on how certain data is used.",
    ],
  },
  {
    id: "retention",
    title: "7. Data Retention",
    icon: <Archive className="w-5 h-5" />,
    content: "We only retain your data for as long as necessary to provide services and comply with legal requirements. Data will be securely deleted after the retention period ends.",
    points: [
      "Active account data is retained for the duration of the subscription.",
      "Server logs are kept for a maximum of 30–90 days for security auditing.",
      "Payment data is retained in accordance with applicable tax and legal requirements.",
    ],
  },
  {
    id: "international",
    title: "8. International Users",
    icon: <Globe className="w-5 h-5" />,
    content: "If you access our services from outside your region, your information will be transferred and processed at our data centers in compliance with local privacy laws.",
    points: [
      "Data is processed at data centers meeting high security standards.",
      "Subject to the jurisdiction of applicable laws.",
      "We guarantee protection standards equivalent to international best practices.",
    ],
  },
];

export default function PrivacySection() {
  const [activeTab, setActiveTab] = useState(privacyData[0].id);
  const [isDownloading, setIsDownloading] = useState(false);

  const handleDownloadPDF = async () => {
    if (isDownloading) return;
    setIsDownloading(true);
    try {
      await new Promise((resolve) => setTimeout(resolve, 1500));
      const link = document.createElement("a");
      link.href = "/documents/Sonata_Privacy_Policy.pdf";
      link.download = `Sonata_Privacy_Policy_${new Date().getFullYear()}.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error("Download failed:", error);
    } finally {
      setIsDownloading(false);
    }
  };

  return (
    <section className="relative w-full overflow-hidden font-sans">
      <div className="max-w-6xl mx-auto relative z-10">

        <div className="flex flex-col md:flex-row items-start md:items-end justify-between gap-6 mb-16">
          <div className="space-y-3">
            <div className="flex items-center gap-3">
              <Lock className="w-4 h-4 text-accent-text" />
              <p className="text-xs font-bold text-accent-text uppercase tracking-widest">Data Protection</p>
            </div>
            <h2 className="text-3xl md:text-4xl font-semibold text-white tracking-tight">
              Privacy <span className="text-accent-text">Policy</span>
            </h2>
            <div className="flex items-center gap-2 text-sm text-content-muted font-mono">
              <Clock className="w-4 h-4" />
              Last updated: Feb 15, 2024
            </div>
          </div>

          <button
            onClick={handleDownloadPDF}
            disabled={isDownloading}
            className="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-zinc-900 border border-border text-zinc-300 text-sm font-semibold hover:text-white hover:border-border-hover hover:bg-zinc-800 transition-all group disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isDownloading ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Download className="w-4 h-4 group-hover:-translate-y-0.5 transition-transform" />
            )}
            {isDownloading ? "Generating PDF…" : "Download Policy PDF"}
          </button>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12">

          <aside className="lg:col-span-4">
            <div className="sticky top-28 space-y-1">
              <p className="text-xs font-bold text-content-subtle uppercase tracking-widest mb-4 px-2">Table of Contents</p>
              {privacyData.map((item) => (
                <button
                  key={item.id}
                  onClick={() => setActiveTab(item.id)}
                  className={cn(
                    "w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 text-left border group",
                    activeTab === item.id
                      ? "bg-accent-hover/10 border-accent-hover/20 text-accent-text"
                      : "bg-transparent border-transparent text-content-muted hover:text-zinc-200 hover:bg-zinc-800/50"
                  )}
                >
                  <span className={cn(
                    "shrink-0 transition-colors duration-200",
                    activeTab === item.id ? "text-accent-text" : "text-content-subtle group-hover:text-content-dim"
                  )}>
                    {item.icon}
                  </span>
                  <span className="font-semibold text-sm flex-1">{item.title}</span>
                  {activeTab === item.id && (
                    <ChevronRight className="w-4 h-4 text-accent-hover shrink-0" />
                  )}
                </button>
              ))}
            </div>
          </aside>

          <main className="lg:col-span-8">
            <div className="bg-surface border border-border/80 rounded-2xl p-8 md:p-10 min-h-[600px]">
              <AnimatePresence mode="wait">
                {(() => { const item = privacyData.find(i => i.id === activeTab); return item ? (
                  <motion.div
                    key={item.id}
                    initial={{ opacity: 0, x: 15 }}
                    animate={{ opacity: 1, x: 0 }}
                    exit={{ opacity: 0, x: -15 }}
                    transition={{ duration: 0.25, ease: "easeOut" }}
                    className="space-y-8"
                  >
                    <div className="space-y-4 border-b border-border/80 pb-8">
                      <div className="inline-flex items-center gap-2 text-accent-text font-bold text-xs tracking-widest uppercase">
                        <div className="w-1.5 h-1.5 rounded-full bg-accent-hover" />
                        Section: {item.id}
                      </div>
                      <h3 className="text-2xl md:text-3xl font-semibold text-white">
                        {item.title}
                      </h3>
                      <p className="text-[1rem] md:text-lg leading-relaxed text-content-dim">
                        {item.content}
                      </p>
                    </div>

                    <div className="space-y-4">
                      <h4 className="text-xs font-bold text-content-subtle uppercase tracking-wider flex items-center gap-2">
                        <Info className="w-4 h-4 text-accent-hover" /> Key Details
                      </h4>
                      <div className="grid gap-3">
                        {item.points.map((point, idx) => (
                          <motion.div
                            key={idx}
                            initial={{ opacity: 0, y: 10 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: idx * 0.05 }}
                            className="flex items-start gap-4 p-4 rounded-xl bg-surface border border-border/80 hover:border-border-hover transition-colors group"
                          >
                            <div className="w-1.5 h-1.5 rounded-full bg-zinc-600 group-hover:bg-accent-hover transition-colors mt-2 shrink-0" />
                            <span className="text-sm text-zinc-300 leading-relaxed font-medium">{point}</span>
                          </motion.div>
                        ))}
                      </div>
                    </div>

                    {item.id === "protection" && (
                      <div className="p-5 rounded-xl bg-accent-hover/10 border border-accent-hover/20 flex gap-4">
                        <Lock className="w-5 h-5 text-accent-text shrink-0 mt-0.5" />
                        <div className="space-y-1">
                          <h5 className="text-sm font-semibold text-accent-text/80">Security Commitment</h5>
                          <p className="text-xs text-accent-text/80/70 leading-relaxed">
                            We regularly conduct penetration testing and security audits to ensure your data is protected against the latest cyber threats.
                          </p>
                        </div>
                      </div>
                    )}
                  </motion.div>
                ) : null; })()
              }
              </AnimatePresence>
            </div>
          </main>

        </div>

        <div className="mt-10 flex flex-col md:flex-row items-center justify-between gap-6 p-6 rounded-2xl bg-surface border border-border/80">
          <p className="text-sm text-content-muted text-center md:text-left">
            This policy applies to all users of Sonata services. For further questions, please reach out to our privacy team.
          </p>
          <div className="shrink-0">
            <button className="px-6 py-2.5 rounded-xl bg-accent hover:bg-accent-hover text-white text-sm font-semibold transition-colors active:scale-95 duration-150">
              Contact Privacy Officer
            </button>
          </div>
        </div>

      </div>
    </section>
  );
}
