"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { ArrowLeft, Copy, Printer, Check } from "lucide-react";

import { ReportSection } from "@/components/report/report-section";
import { ReportNavSidebar } from "@/components/report/report-nav-sidebar";
import { Button } from "@/components/ui/button";
import { getArchetypeById } from "@/data/archetypes";
import { getPackageById } from "@/data/packages";
import { DEMO_REPORTS, getReportById as getDemoReport } from "@/data/reports";
import { useAuthStore } from "@/stores/auth-store";
import { useReportStore } from "@/stores/report-store";
import type { Report, PackageTier } from "@/types/novalife";

const SECTION_ORDER = [
  { key: "archetypeProfile", label: "Archetype Profile" },
  { key: "metabolicSnapshot", label: "Metabolic Snapshot" },
  { key: "whyYouStruggle", label: "Why You Struggle" },
  { key: "nutritionStrategy", label: "Nutrition Strategy" },
  { key: "lifestyleProtocol", label: "Lifestyle Protocol" },
  { key: "glp1Assessment", label: "GLP-1 Assessment" },
  { key: "actionPlan", label: "Action Plan" },
  { key: "nextSteps", label: "Next Steps" },
] as const;

const TIER_SECTIONS: Record<PackageTier, string[]> = {
  starter: ["archetypeProfile", "metabolicSnapshot", "nutritionStrategy", "nextSteps"],
  advanced: [
    "archetypeProfile",
    "metabolicSnapshot",
    "whyYouStruggle",
    "nutritionStrategy",
    "lifestyleProtocol",
    "glp1Assessment",
    "nextSteps",
  ],
  professional: [
    "archetypeProfile",
    "metabolicSnapshot",
    "whyYouStruggle",
    "nutritionStrategy",
    "lifestyleProtocol",
    "glp1Assessment",
    "actionPlan",
    "nextSteps",
  ],
};

export default function ReportViewerPage() {
  const params = useParams<{ id: string }>();
  const router = useRouter();
  const { user } = useAuthStore();
  const { getReportById, loadReports } = useReportStore();
  const [report, setReport] = useState<Report | null>(null);
  const [activeSection, setActiveSection] = useState("archetypeProfile");
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    if (user) {
      loadReports(user.id);
    }
  }, [user, loadReports]);

  useEffect(() => {
    if (!params?.id) return;
    const found = getReportById(params.id) ?? getDemoReport(params.id);
    if (found) {
      setReport(found);
    } else {
      const allDemo = DEMO_REPORTS.find((r) => r.id === params.id);
      setReport(allDemo ?? null);
    }
  }, [params?.id, getReportById]);

  useEffect(() => {
    const handleScroll = () => {
      if (!report) return;
      const unlockedSections = TIER_SECTIONS[report.tier] ?? [];
      for (const section of [...unlockedSections].reverse()) {
        const el = document.getElementById(section);
        if (el) {
          const rect = el.getBoundingClientRect();
          if (rect.top <= 120) {
            setActiveSection(section);
            break;
          }
        }
      }
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, [report]);

  const handleShare = () => {
    navigator.clipboard.writeText(globalThis.location.href);
    setCopied(true);
    setTimeout(() => setCopied(false), 2500);
  };

  const handlePrint = () => {
    globalThis.print();
  };

  if (!report) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-gray-500 mb-4">Report not found.</p>
          <Button
            onClick={() => router.push("/dashboard/reports")}
            variant="outline"
            className="rounded-xl"
          >
            Back to Reports
          </Button>
        </div>
      </div>
    );
  }

  const archetype = getArchetypeById(report.archetypeId);
  const pkg = getPackageById(report.tier);
  const unlockedSections = TIER_SECTIONS[report.tier] ?? [];

  const navSections = SECTION_ORDER.filter(
    (s) => report.sections[s.key as keyof typeof report.sections],
  ).map((s) => ({ key: s.key, title: s.label }));

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Print styles */}
      <style>{`
        @media print {
          .no-print { display: none !important; }
          .print-break { page-break-after: always; }
          body { background: white; }
        }
      `}</style>

      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6 no-print">
          <div className="flex items-center gap-3">
            <Button
              variant="ghost"
              size="icon"
              onClick={() => router.push("/dashboard/reports")}
              className="rounded-xl border border-gray-200 h-9 w-9"
            >
              <ArrowLeft className="h-4 w-4" />
            </Button>
            <div>
              <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">
                {pkg?.name} Report
              </p>
              <h1 className="text-lg font-bold text-gray-900">
                {archetype?.name ?? report.archetypeId}
              </h1>
            </div>
          </div>

          <div className="flex items-center gap-2 no-print">
            <Button
              variant="outline"
              size="sm"
              onClick={handleShare}
              className="rounded-xl border-gray-200 text-gray-600 hover:bg-gray-50"
            >
              {copied ? (
                <>
                  <Check className="h-3.5 w-3.5 mr-1.5 text-green-600" />
                  Copied!
                </>
              ) : (
                <>
                  <Copy className="h-3.5 w-3.5 mr-1.5" />
                  Share
                </>
              )}
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={handlePrint}
              className="rounded-xl border-gray-200 text-gray-600 hover:bg-gray-50"
            >
              <Printer className="h-3.5 w-3.5 mr-1.5" />
              Print / Save PDF
            </Button>
          </div>
        </div>

        {/* Report header banner */}
        <div
          className="rounded-2xl p-6 mb-6 text-white print-break"
          style={{
            background: archetype
              ? `linear-gradient(135deg, ${archetype.color}, ${archetype.color}88)`
              : "linear-gradient(135deg, #0F766E, #0d9488)",
          }}
        >
          <p className="text-white/70 text-xs font-bold uppercase tracking-widest mb-1">
            Personalised Health Report
          </p>
          <h2 className="text-2xl font-extrabold mb-1">{archetype?.name}</h2>
          <p className="text-white/80 text-sm">{archetype?.tagline}</p>
          <div className="mt-3 flex items-center gap-3 flex-wrap">
            <span className="bg-white/20 backdrop-blur-sm text-white text-xs font-semibold px-3 py-1 rounded-full">
              {pkg?.name ?? report.tier} Plan
            </span>
            <span className="text-white/60 text-xs">
              Generated{" "}
              {new Date(report.generatedAt).toLocaleDateString("en-GB", {
                day: "numeric",
                month: "long",
                year: "numeric",
              })}
            </span>
          </div>
        </div>

        {/* Content with nav sidebar */}
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          {/* Nav sidebar */}
          <div className="lg:col-span-1 no-print">
            <div className="sticky top-20 bg-white rounded-2xl border border-gray-100 p-4 shadow-sm">
              <ReportNavSidebar
                sections={navSections}
                activeSection={activeSection}
                onSectionClick={setActiveSection}
              />
            </div>
          </div>

          {/* Report sections */}
          <div className="lg:col-span-3 space-y-4">
            {SECTION_ORDER.map(({ key, label }) => {
              const sectionData = report.sections[key as keyof typeof report.sections];
              if (!sectionData) return null;

              const isLocked = !unlockedSections.includes(key);

              return (
                <ReportSection
                  key={key}
                  section={sectionData}
                  sectionKey={key}
                  isLocked={isLocked}
                />
              );
            })}

            {/* Upgrade CTA at bottom */}
            {report.tier !== "professional" && (
              <div className="rounded-2xl border-2 border-teal-200 bg-teal-50 p-6 text-center no-print">
                <p className="text-sm font-bold text-teal-700 uppercase tracking-wider mb-2">
                  Unlock More Insights
                </p>
                <h3 className="text-xl font-extrabold text-gray-900 mb-2">
                  Upgrade to{" "}
                  {report.tier === "starter" ? "Advanced or Professional" : "Professional"}
                </h3>
                <p className="text-sm text-gray-500 mb-4">
                  Get the full depth of your personalised metabolic analysis and action plan.
                </p>
                <Button
                  onClick={() => router.push("/result/unlock")}
                  className="bg-teal-600 hover:bg-teal-700 text-white font-bold rounded-xl px-6"
                >
                  View Upgrade Options
                </Button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
