"use client";

import { useState, useEffect, useCallback } from "react";
import type { ProposalDetail } from "@/lib/proposal/queries";
import { CoverSection } from "./sections/CoverSection";
import { VisionSection } from "./sections/VisionSection";
import { IndexSection } from "./sections/IndexSection";
import { ChapterDivider } from "./sections/ChapterDivider";
import { StrategistSection } from "./sections/StrategistSection";
import { FactsSection } from "./sections/FactsSection";
import { TestimonialsSection } from "./sections/TestimonialsSection";
import { ProblemNodeSection } from "./sections/ProblemNodeSection";
import { SynthesisDiagramSection } from "./sections/SynthesisDiagramSection";
import { SolutionNodeSection } from "./sections/SolutionNodeSection";
import { SolutionSynthesisSection } from "./sections/SolutionSynthesisSection";
import { ScopeSection } from "./sections/ScopeSection";
import { DeliverablesSection } from "./sections/DeliverablesSection";
import { TimelineSection } from "./sections/TimelineSection";
import { PricingSection } from "./sections/PricingSection";
import { StagesRecapSection } from "./sections/StagesRecapSection";
import { ComparisonMatrixSection } from "./sections/ComparisonMatrixSection";
import { NextStepsSection } from "./sections/NextStepsSection";
import { ClosingSection } from "./sections/ClosingSection";
import { AcceptSection } from "./sections/AcceptSection";

type Props = {
  proposal: ProposalDetail;
  onAccept: (slug: string, tier: string, email?: string, notes?: string) => Promise<void>;
  onReject: (slug: string, notes?: string) => Promise<void>;
};

export function ProposalDeck({ proposal, onAccept, onReject }: Props) {
  const { content, state, selectedTier, acceptedAt } = proposal;
  const { ai, consultant, offer, header } = content;
  const problems = ai.problems;
  const solutions = ai.solutions;

  // Costruisce la lista di slide dinamicamente
  const testimonialPages = Math.ceil(consultant.testimonials.length / 9);

  type Slide = { id: string; component: React.ReactNode };

  const slides: Slide[] = [
    // 01 — Cover
    { id: "cover", component: <CoverSection header={header} /> },
    // 02 — Vision
    { id: "vision", component: <VisionSection vision={ai.vision} header={header} /> },
    // 03 — Sommario
    { id: "index", component: <IndexSection /> },
    // Cap.01 — Lo strategist
    { id: "ch01", component: <ChapterDivider number="01" title="Lo strategist." subtitle="Chi vi affianca in questo lavoro, con quali credenziali, con quale metodo e con quali precedenti dimostrabili." /> },
    { id: "strategist", component: <StrategistSection consultant={consultant} /> },
    { id: "facts", component: <FactsSection consultant={consultant} /> },
    // Testimonianze (1–N pagine da 9)
    ...Array.from({ length: testimonialPages }, (_, i) => ({
      id: `testimonials-${i + 1}`,
      component: (
        <TestimonialsSection
          testimonials={consultant.testimonials}
          page={i + 1}
          totalPages={testimonialPages}
        />
      ),
    })),
    // Cap.02 — Il problema
    { id: "ch02", component: <ChapterDivider number="02" title="Il problema." subtitle={`${problems.length} nodi rilevati nella discovery. Li chiamiamo per nome, uno per uno.`} /> },
    // Nodi problema
    ...problems.map((p) => ({
      id: `problem-${p.id}`,
      component: <ProblemNodeSection problem={p} />,
    })),
    // Sintesi problema
    { id: "problem-synthesis", component: <SynthesisDiagramSection synthesis={ai.problemSynthesis} type="problem" /> },
    // Cap.03 — La soluzione
    { id: "ch03", component: <ChapterDivider number="03" title="La soluzione." subtitle="Per ogni nodo, un'elevazione speculare. La struttura riprende l'ordine dei problemi e mostra dove la trasformazione vi porta." /> },
    // Nodi soluzione
    ...solutions.map((s) => ({
      id: `solution-${s.id}`,
      component: <SolutionNodeSection solution={s} />,
    })),
    // Sintesi soluzione
    { id: "solution-synthesis", component: <SolutionSynthesisSection synthesis={ai.solutionSynthesis} /> },
    // Cap.04 — L'esecuzione
    { id: "ch04", component: <ChapterDivider number="04" title="L'esecuzione." subtitle="Lo scope del lavoro, gli obiettivi, i deliverable, ciò che è incluso e ciò che non lo è. La timeline." /> },
    { id: "scope", component: <ScopeSection scope={ai.scope} /> },
    { id: "deliverables", component: <DeliverablesSection deliverables={ai.deliverables} /> },
    { id: "timeline", component: <TimelineSection timeline={ai.timeline} /> },
    // Cap.05 — Le opzioni
    { id: "ch05", component: <ChapterDivider number="05" title="Le opzioni." subtitle="Il valore di mercato delle attività, le tre opzioni progressive con il loro pricing, e il processo per partire." /> },
    { id: "pricing", component: <PricingSection tiers={offer.tiers} offerType={offer.offerType} /> },
    // Stages recap + comparison
    { id: "stages", component: <StagesRecapSection stages={ai.stagesRecap.stages} /> },
    { id: "comparison", component: <ComparisonMatrixSection matrix={ai.comparisonMatrix} tiers={offer.tiers} /> },
    // Come procedere / Next steps
    { id: "nextsteps", component: <NextStepsSection consultant={consultant} header={header} offer={offer} /> },
    // Accept/Reject (solo se published)
    ...(state === "published"
      ? [{
          id: "accept",
          component: (
            <AcceptSection
              slug={proposal.slug}
              tiers={offer.tiers}
              header={header}
              onAccept={onAccept}
              onReject={onReject}
            />
          ),
        }]
      : []),
    // Closing
    { id: "closing", component: <ClosingSection consultant={consultant} header={header} state={state} selectedTier={selectedTier} acceptedAt={acceptedAt} /> },
  ];

  const total = slides.length;
  const [current, setCurrent] = useState(0);

  const goTo = useCallback((i: number) => setCurrent(Math.max(0, Math.min(total - 1, i))), [total]);
  const prev = useCallback(() => goTo(current - 1), [current, goTo]);
  const next = useCallback(() => goTo(current + 1), [current, goTo]);

  // Navigazione da tastiera
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === "ArrowRight" || e.key === "ArrowDown") next();
      if (e.key === "ArrowLeft" || e.key === "ArrowUp") prev();
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [next, prev]);

  // Blocca lo scroll del body mentre la deck è visibile
  useEffect(() => {
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = ""; };
  }, []);

  return (
    <div className="relative h-screen overflow-hidden bg-white font-sans select-none">
      {/* Topbar */}
      <div className="fixed top-0 left-0 right-0 z-20 flex items-center justify-between px-8 py-4 bg-white/90 backdrop-blur-sm border-b border-border">
        <span className="text-xs font-mono text-muted-foreground tracking-widest uppercase">
          Documento di Soluzione · {header.clientName} · {header.date}
        </span>
        <span className="text-xs font-mono text-muted-foreground">
          {String(current + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}
        </span>
      </div>

      {/* Contenuto slide — riempie esattamente lo spazio tra le due barre fisse */}
      <div className="h-full pt-16 pb-20 overflow-hidden">
        {slides[current].component}
      </div>

      {/* Bottom nav */}
      <div className="fixed bottom-0 left-0 right-0 z-20 flex items-center justify-between px-8 py-4 bg-white/90 backdrop-blur-sm border-t border-border">
          {/* Frecce */}
          <div className="flex items-center gap-3 text-xs text-muted-foreground">
            <button
              onClick={prev}
              disabled={current === 0}
              className="disabled:opacity-30 hover:text-foreground transition-colors"
              aria-label="Precedente"
            >
              ←
            </button>
            <button
              onClick={next}
              disabled={current === total - 1}
              className="disabled:opacity-30 hover:text-foreground transition-colors"
              aria-label="Prossimo"
            >
              →
            </button>
            <span className="ml-2 hidden sm:inline">CLICK DOTS</span>
          </div>

          {/* Dot navigator */}
          <div className="flex items-center gap-1 overflow-x-auto max-w-[60vw] py-1">
            {slides.map((s, i) => (
              <button
                key={s.id}
                onClick={() => goTo(i)}
                aria-label={`Vai alla slide ${i + 1}`}
                className={`shrink-0 rounded-full transition-all ${
                  i === current
                    ? "w-6 h-2 bg-primary"
                    : "w-2 h-2 bg-border hover:bg-muted-foreground"
                }`}
              />
            ))}
          </div>
        </div>
    </div>
  );
}
