"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { ArrowRight, ChevronRight, FileText, Info, Lock, Sparkles, Star } from "lucide-react";

import { ArchetypeBanner } from "@/components/result/archetype-banner";
import { ArchetypeTraits } from "@/components/result/archetype-traits";
import { BmiIndicator } from "@/components/result/bmi-indicator";
import { Glp1StatusCard } from "@/components/result/glp1-status-card";
import { ReportLockOverlay } from "@/components/result/report-lock-overlay";
import { Button } from "@/components/ui/button";
import { getArchetypeById } from "@/data/archetypes";
import { PACKAGES } from "@/data/packages";
import type { ArchetypeResult } from "@/types/novalife";
import { STORAGE_KEYS } from "@/types/novalife";
import { cn } from "@/lib/utils";

const LOCKED_SECTION_PREVIEWS = [
  {
    title: "Full Metabolic Root-Cause Analysis",
    description: "Understand exactly why your previous efforts haven't worked",
    tier: "advanced" as const,
  },
  {
    title: "Personalised Nutrition & Lifestyle Protocol",
    description: "A complete, archetype-specific action plan built for your biology",
    tier: "advanced" as const,
  },
  {
    title: "GLP-1 Eligibility Full Assessment",
    description: "Detailed clinical review and next steps for your GP consultation",
    tier: "advanced" as const,
  },
];

export default function ResultPage() {
  const router = useRouter();
  const [archetypeResult, setArchetypeResult] = useState<ArchetypeResult | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const raw = localStorage.getItem(STORAGE_KEYS.ARCHETYPE_RESULT);
    if (!raw) {
      router.replace("/quiz");
      return;
    }

    const isUnlocked = localStorage.getItem(STORAGE_KEYS.REPORT_UNLOCKED) === "true";
    if (isUnlocked) {
      router.replace("/dashboard/reports");
      return;
    }

    try {
      const result: ArchetypeResult = JSON.parse(raw);
      setArchetypeResult(result);
    } catch {
      router.replace("/quiz");
      return;
    }
    setIsLoading(false);
  }, [router]);

  const archetype = archetypeResult
    ? getArchetypeById(archetypeResult.primaryArchetype)
    : null;

  if (isLoading || !archetypeResult || !archetype) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="flex flex-col items-center gap-3">
          <div className="w-10 h-10 rounded-full border-4 border-teal-600 border-t-transparent animate-spin" />
          <p className="text-gray-500 text-sm">Loading your results…</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Archetype Banner */}
      <div className="relative">
        <p className="absolute top-4 left-1/2 -translate-x-1/2 z-20 text-white/60 text-xs font-semibold uppercase tracking-widest bg-black/20 px-3 py-1 rounded-full backdrop-blur-sm">
          Your Metabolic Type
        </p>
        <ArchetypeBanner archetypeId={archetypeResult.primaryArchetype} />
      </div>

      {/* Main content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Left column — details */}
          <div className="lg:col-span-2 space-y-6">
            {/* Long description */}
            <div className="bg-white rounded-2xl border border-gray-100 p-6 shadow-sm">
              <h2 className="text-lg font-bold text-gray-900 mb-3">
                About Your Archetype
              </h2>
              <p className="text-gray-600 leading-relaxed text-sm sm:text-base">
                {archetype.longDescription}
              </p>
            </div>

            {/* Traits */}
            <div className="bg-white rounded-2xl border border-gray-100 p-6 shadow-sm">
              <ArchetypeTraits traits={archetype.traits} color={archetype.color} />
            </div>

            {/* BMI */}
            <BmiIndicator
              bmi={archetypeResult.bmi}
              category={archetypeResult.bmiCategory}
            />

            {/* GLP-1 */}
            <Glp1StatusCard
              glp1Eligible={archetypeResult.glp1Eligible}
              glp1Score={archetypeResult.glp1Score}
            />

            {/* Key insight */}
            <div
              className="rounded-2xl p-6 border"
              style={{
                backgroundColor: `${archetype.color}10`,
                borderColor: `${archetype.color}30`,
              }}
            >
              <div className="flex items-start gap-3">
                <div
                  className="flex h-9 w-9 items-center justify-center rounded-lg flex-shrink-0"
                  style={{ backgroundColor: `${archetype.color}20` }}
                >
                  <Sparkles className="h-5 w-5" style={{ color: archetype.color }} />
                </div>
                <div>
                  <p className="text-xs font-bold uppercase tracking-wider mb-1.5" style={{ color: archetype.color }}>
                    Your Key Insight
                  </p>
                  <p className="text-gray-800 font-medium text-sm sm:text-base leading-relaxed">
                    {archetype.struggles[0]}
                  </p>
                  <p className="text-gray-600 text-sm mt-2 leading-relaxed">
                    Your personalised report breaks down the exact science behind this and provides
                    targeted interventions designed specifically for the{" "}
                    <strong>{archetype.name}</strong> archetype.
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* Right column — sticky unlock card */}
          <div className="lg:col-span-1">
            <div className="sticky top-20 space-y-4">
              {/* Unlock card */}
              <div className="bg-white rounded-2xl border-2 border-teal-600 p-6 shadow-lg shadow-teal-600/10">
                <div className="flex items-center gap-2 mb-1">
                  <FileText className="h-5 w-5 text-teal-600" />
                  <h3 className="text-lg font-bold text-gray-900">Your full report is ready</h3>
                </div>
                <p className="text-sm text-gray-500 mb-5">
                  Choose a package to unlock your personalised{" "}
                  <strong>{archetype.name}</strong> health report.
                </p>

                {/* Package teasers */}
                <div className="space-y-2.5 mb-5">
                  {PACKAGES.map((pkg) => (
                    <div
                      key={pkg.id}
                      className={cn(
                        "rounded-xl border p-3 flex items-center justify-between transition-colors",
                        pkg.isPopular
                          ? "border-teal-200 bg-teal-50"
                          : "border-gray-100 bg-gray-50",
                      )}
                    >
                      <div>
                        <div className="flex items-center gap-1.5">
                          <span className="text-sm font-semibold text-gray-800">{pkg.name}</span>
                          {pkg.isPopular && (
                            <span className="px-1.5 py-0.5 bg-teal-600 text-white text-xs font-bold rounded">
                              POPULAR
                            </span>
                          )}
                        </div>
                        <p className="text-xs text-gray-400 mt-0.5">{pkg.tagline}</p>
                      </div>
                      <span className="text-sm font-bold text-gray-700 whitespace-nowrap">
                        CHF {pkg.priceChf}
                      </span>
                    </div>
                  ))}
                </div>

                <Link href="/result/unlock">
                  <Button className="w-full bg-teal-600 hover:bg-teal-700 text-white font-semibold py-2.5 rounded-xl shadow-sm hover:shadow-md transition-all group">
                    Unlock Your Report — From CHF 29
                    <ArrowRight className="ml-2 h-4 w-4 group-hover:translate-x-0.5 transition-transform" />
                  </Button>
                </Link>

                <div className="mt-3 text-center">
                  <Link
                    href="/pricing"
                    className="text-xs text-teal-600 hover:text-teal-700 font-medium inline-flex items-center gap-1"
                  >
                    Learn more about packages
                    <ChevronRight className="h-3 w-3" />
                  </Link>
                </div>
              </div>

              {/* Social proof */}
              <div className="bg-amber-50 rounded-xl border border-amber-200 p-4">
                <div className="flex items-center gap-1 mb-1.5">
                  {[1, 2, 3, 4, 5].map((i) => (
                    <Star key={i} className="h-3.5 w-3.5 fill-amber-400 text-amber-400" />
                  ))}
                </div>
                <p className="text-xs text-amber-800 leading-relaxed">
                  "The report was eye-opening. I finally understood why every diet had failed me."
                </p>
                <p className="text-xs text-amber-600 font-semibold mt-1.5">— Sarah M., Zürich</p>
              </div>

              {/* Trust note */}
              <div className="flex items-start gap-2 bg-gray-50 rounded-xl border border-gray-100 p-3">
                <Info className="h-4 w-4 text-gray-400 flex-shrink-0 mt-0.5" />
                <p className="text-xs text-gray-400 leading-relaxed">
                  One-time payment. No subscription required for Starter or Advanced. Instant
                  access after checkout.
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Locked section previews */}
        <div className="mt-12">
          <div className="text-center mb-6">
            <div className="inline-flex items-center gap-2 bg-gray-100 rounded-full px-4 py-2 mb-3">
              <Lock className="h-4 w-4 text-gray-500" />
              <span className="text-sm font-semibold text-gray-600">What's inside your full report</span>
            </div>
            <h2 className="text-2xl font-bold text-gray-900">
              3 more sections locked in your report
            </h2>
            <p className="text-gray-500 mt-1 text-sm">
              Unlock your personalised report to access the full depth of your analysis
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {LOCKED_SECTION_PREVIEWS.map((section, index) => (
              <div key={index} className="relative">
                {/* Preview header visible above overlay */}
                <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
                  <div className="px-5 pt-5 pb-2">
                    <h3 className="font-bold text-gray-900 text-sm mb-1">{section.title}</h3>
                    <p className="text-xs text-gray-400">{section.description}</p>
                  </div>
                  <ReportLockOverlay
                    tier={section.tier}
                    onUnlock={() => router.push("/result/unlock")}
                    className="rounded-none border-x-0 border-b-0 rounded-b-xl"
                  />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
