"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "motion/react";
import {
  Percent,
  Clock,
  ServerCrash,
  Coins,
  FileCheck,
  AlertOctagon,
  Download,
  Loader2,
  ChevronRight,
  Activity,
} from "lucide-react";
import { cn } from "@/lib/utils";

const slaData = [
  {
    id: "definitions",
    title: "1. Definitions",
    icon: <FileCheck className="w-5 h-5" />,
    content: "For the clarity of this document, the following terms are defined as:",
    points: [
      "Service: The hosting, VPS, or Dedicated Server product being rented.",
      "Downtime: A period during which the service is inaccessible via the public network due to Sonata infrastructure failure.",
      "Monthly Uptime: The percentage of time a service is available within a calendar month.",
      "Scheduled Maintenance: Maintenance announced at least 24 hours in advance.",
    ],
  },
  {
    id: "guarantee",
    title: "2. Uptime Guarantee",
    icon: <Activity className="w-5 h-5" />,
    content: "Sonata guarantees a network and infrastructure availability (Uptime) rate of 99.9% per calendar month.",
    points: [
      "Target Uptime: 99.9% per month.",
      "Maximum tolerated downtime: ~43 minutes per month.",
      "Monitoring is conducted by internal systems and third-party services (Status Page).",
    ],
  },
  {
    id: "credits",
    title: "3. SLA Credits",
    icon: <Coins className="w-5 h-5" />,
    content: "If we fail to meet the uptime guarantee above, you are entitled to request a Service Credit as compensation under the following scheme:",
    points: [
      "99.5% – 99.9%: 5% credit of monthly fee.",
      "99.0% – 99.5%: 10% credit of monthly fee.",
      "98.0% – 99.0%: 25% credit of monthly fee.",
      "Below 98.0%: 50% credit of monthly fee (Maximum).",
    ],
  },
  {
    id: "claims",
    title: "4. Claim Procedure",
    icon: <FileCheck className="w-5 h-5" />,
    content: "To file an SLA claim, customers must meet the following requirements:",
    points: [
      "Open a support ticket in the Client Area within 7 days of the incident.",
      "Provide evidence of downtime (Traceroute, Error Logs, or Screenshot).",
      "Account must not have any outstanding balance (Unpaid) or be Suspended.",
      "Credits will be added to your account balance for the next billing cycle.",
    ],
  },
  {
    id: "exclusions",
    title: "5. Exclusions",
    icon: <AlertOctagon className="w-5 h-5" />,
    content: "The SLA guarantee does not apply to downtime caused by:",
    points: [
      "Scheduled Maintenance.",
      "User configuration errors (Script errors, Plugin crashes, Full disk).",
      "Force Majeure (Natural disasters, War, Tier-1 global ISP outages).",
      "DDoS attacks exceeding the standard mitigation capacity of your plan (except plans with Dedicated Protection).",
      "Service suspension due to ToS/AUP violations.",
    ],
  },
  {
    id: "hardware",
    title: "6. Hardware SLA",
    icon: <ServerCrash className="w-5 h-5" />,
    content: "For Dedicated Node/VPS services specifically, we guarantee replacement of failed hardware.",
    points: [
      "Initial Response: Maximum 1 hour after hardware failure is diagnosed.",
      "Replacement Time: Maximum 4 hours for component replacement (RAM/Disk/PSU).",
      "Compensation: 5% credit for each hour of replacement delay.",
    ],
  },
];

export default function SlaSection() {
  const [activeTab, setActiveTab] = useState(slaData[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_SLA.pdf";
      link.download = `Sonata_SLA_${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">
              <Percent className="w-4 h-4 text-accent-text" />
              <p className="text-xs font-bold text-accent-text uppercase tracking-widest">Performance Guarantee</p>
            </div>
            <h2 className="text-3xl md:text-4xl font-semibold text-white tracking-tight">
              Service Level <span className="text-accent-text">Agreement</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
            </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 SLA…" : "Download SLA 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">Agreement Clauses</p>
              {slaData.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-[500px]">
              <AnimatePresence mode="wait">
                {(() => { const item = slaData.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" />
                        Clause: {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">
                        <FileCheck className="w-4 h-4 text-accent-hover" /> Details & Conditions
                      </h4>

                      {item.id === "credits" ? (
                        <div className="grid gap-3">
                          {item.points.map((point, idx) => {
                            const colonIdx = point.indexOf(":");
                            const range  = point.slice(0, colonIdx).trim();
                            const credit = point.slice(colonIdx + 1).trim();
                            return (
                              <div
                                key={idx}
                                className="flex justify-between items-center p-4 rounded-xl bg-surface border border-border/80 hover:border-border-hover transition-colors"
                              >
                                <span className="font-mono text-accent-text/80 font-bold text-sm">{range}</span>
                                <span className="text-sm text-zinc-300 bg-accent-hover/10 px-3 py-1 rounded-full border border-accent-hover/20">{credit}</span>
                              </div>
                            );
                          })}
                        </div>
                      ) : (
                        <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>
                      )}

                      {item.id === "exclusions" && (
                        <div className="p-5 rounded-xl bg-accent-hover/10 border border-accent-hover/20 flex gap-4 mt-2">
                          <AlertOctagon 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">Note</h5>
                            <p className="text-xs text-accent-text/80/70 leading-relaxed">
                              SLA claims rejected due to Force Majeure are non-disputable. We recommend users maintain off-site backups as part of their disaster mitigation strategy.
                            </p>
                          </div>
                        </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">
            Sonata is committed to maintaining the highest service quality standards. This SLA is our written guarantee to you.
          </p>
          <div className="shrink-0">
            <a
              href="/status"
              className="inline-block 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"
            >
              View Server Status
            </a>
          </div>
        </div>

      </div>
    </section>
  );
}
