"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import {
  autodiagnosticSections,
  buildAutodiagnosticPromptContext,
  calculateAutodiagnosticResult,
  createEmptyAutodiagnosticAnswers,
  isAutodiagnosticComplete,
  type AutodiagnosticAnswers,
  type AutodiagnosticAnswerValue,
} from "@/lib/autodiagnostic-shared";
import { MandatoryOnboardingGuard } from "@/components/mandatory-onboarding-guard";
import {
  getDemoOnboardingState,
  updateDemoOnboardingState,
} from "@/lib/demo-session-store";
import type { OnboardingState } from "@/lib/onboarding-shared";

function fetchOnboardingState() {
  return getDemoOnboardingState();
}

function saveAutodiagnosticDraft(answers: AutodiagnosticAnswers) {
  return updateDemoOnboardingState({
    autodiagnosticAnswers: answers,
  });
}

export function AutodiagnosticShell() {
  const router = useRouter();
  const [answers, setAnswers] = useState<AutodiagnosticAnswers>(
    createEmptyAutodiagnosticAnswers(),
  );
  const [status, setStatus] = useState<OnboardingState | null>(null);
  const [loadingStatus, setLoadingStatus] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let active = true;

    function loadStatus() {
      try {
        const nextState = fetchOnboardingState();

        if (active) {
          setStatus(nextState);
          setAnswers(nextState.autodiagnosticAnswers);
        }
      } catch (caughtError) {
        if (active) {
          setError(
            caughtError instanceof Error
              ? caughtError.message
              : "Impossible de charger cette etape.",
          );
        }
      } finally {
        if (active) {
          setLoadingStatus(false);
        }
      }
    }

    loadStatus();

    return () => {
      active = false;
    };
  }, []);

  const questions = useMemo(
    () => autodiagnosticSections.flatMap((section) => section.questions),
    [],
  );

  const answeredCount = useMemo(
    () => Object.values(answers).filter((value) => value !== "").length,
    [answers],
  );

  const completionPercentage = Math.round(
    (answeredCount / questions.length) * 100,
  );
  const canSubmit = isAutodiagnosticComplete(answers);

  const sectionProgress = useMemo(
    () =>
      autodiagnosticSections.map((section) => ({
        id: section.id,
        title: section.title,
        answered: section.questions.filter(
          (question) => answers[question.id] !== "",
        ).length,
        total: section.questions.length,
      })),
    [answers],
  );

  function handleAnswerToggle(questionId: string, value: AutodiagnosticAnswerValue) {
    const nextAnswers: AutodiagnosticAnswers = {
      ...answers,
      [questionId]: answers[questionId] === value ? "" : value,
    };

    setAnswers(nextAnswers);
    setError(null);

    try {
      const nextState = saveAutodiagnosticDraft(nextAnswers);
      setStatus(nextState);
    } catch (caughtError) {
      setError(
        caughtError instanceof Error
          ? caughtError.message
          : "Impossible d'enregistrer cette reponse.",
      );
    }
  }

  function handleReset() {
    const nextAnswers = createEmptyAutodiagnosticAnswers();

    setAnswers(nextAnswers);
    setError(null);

    try {
      const nextState = updateDemoOnboardingState({
        autodiagnosticAnswers: nextAnswers,
        autodiagnosticResult: null,
        autodiagnosticPromptContext: "",
        completeAutodiagnostic: false,
        acknowledgeAutodiagnosticResult: false,
      });
      setStatus(nextState);
    } catch (caughtError) {
      setError(
        caughtError instanceof Error
          ? caughtError.message
          : "Impossible de reinitialiser cette etape.",
      );
    }
  }

  function handleSubmit() {
    if (!canSubmit || saving || !status?.answers.managerialLevel) {
      return;
    }

    setSaving(true);
    setError(null);

    try {
      const result = calculateAutodiagnosticResult(
        status.answers.managerialLevel,
        answers,
      );
      const nextState = updateDemoOnboardingState({
        autodiagnosticAnswers: answers,
        autodiagnosticResult: result,
        autodiagnosticPromptContext: buildAutodiagnosticPromptContext(result),
        completeAutodiagnostic: true,
        acknowledgeAutodiagnosticResult: false,
      });

      setStatus(nextState);
      router.push("/onboarding/autodiagnostique/resultat");
    } catch (caughtError) {
      setError(
        caughtError instanceof Error
          ? caughtError.message
          : "Impossible de calculer le resultat de l'autodiagnostique.",
      );
    } finally {
      setSaving(false);
    }
  }

  return (
    <MandatoryOnboardingGuard scope="onboarding">
      <main className="app-shell min-h-screen px-5 py-8 sm:px-8 lg:px-10">
        <div className="relative z-10 mx-auto grid max-w-7xl gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
          <section className="glass-card fade-in-up rounded-[32px] px-6 py-6 lg:px-8 lg:py-8">
            <p className="text-sm font-semibold uppercase tracking-[0.22em] text-[var(--accent-red)]">
              Autodiagnostique
            </p>
            <h1 className="mt-4 text-4xl font-extrabold tracking-[-0.04em] text-[var(--ink)]">
              Questionnaire managerial en 18 situations
            </h1>
            <div className="mt-5 flex flex-wrap gap-2">
              <span className="inline-flex items-center rounded-full bg-[rgba(23,117,186,0.12)] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-[var(--primary)]">
                18 situations
              </span>
              <span className="inline-flex items-center rounded-full bg-[rgba(216,142,4,0.14)] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-[var(--accent-gold)]">
                72 choix
              </span>
              {status?.answers.managerialLevel ? (
                <span className="inline-flex items-center rounded-full bg-[rgba(47,138,99,0.12)] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-[var(--success)]">
                  Niveau {status.answers.managerialLevel}
                </span>
              ) : null}
            </div>

            <section className="mt-8 rounded-[28px] border border-[var(--line)] bg-[var(--surface-soft)] p-5 sm:p-6">
              <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.18em] text-[var(--primary)]">
                    Progression
                  </p>
                  <h2 className="mt-2 text-3xl font-extrabold tracking-[-0.03em] text-[var(--ink)]">
                    {answeredCount}/{questions.length} reponses selectionnees
                  </h2>
                  <p className="mt-2 text-sm leading-7 text-[var(--foreground)]">
                    Repondez aux 18 situations pour calculer votre resultat.
                  </p>
                </div>

                <div className="rounded-[24px] border border-[var(--line)] bg-white px-4 py-3 text-sm font-semibold text-[var(--foreground)]">
                  {completionPercentage}% complete
                </div>
              </div>

              <div className="mt-5 h-3 overflow-hidden rounded-full bg-white">
                <div
                  className="h-full rounded-full bg-[linear-gradient(90deg,var(--primary)_0%,var(--accent-gold)_100%)] transition-[width] duration-300"
                  style={{ width: `${completionPercentage}%` }}
                />
              </div>
            </section>

            {loadingStatus ? (
              <div className="mt-6 rounded-[24px] border border-[rgba(23,117,186,0.16)] bg-[rgba(23,117,186,0.07)] px-4 py-3 text-sm leading-7 text-[var(--primary)]">
                Chargement de votre progression onboarding...
              </div>
            ) : null}

            {error ? (
              <div className="mt-6 rounded-[24px] border border-[rgba(159,25,24,0.16)] bg-[rgba(159,25,24,0.06)] px-4 py-3 text-sm leading-7 text-[var(--accent-red)]">
                {error}
              </div>
            ) : null}

            <div className="mt-8 space-y-8">
              {autodiagnosticSections.map((section, index) => (
                <section
                  key={section.id}
                  id={section.id}
                  className="rounded-[30px] border border-[var(--line)] bg-[rgba(255,255,255,0.78)] p-5 sm:p-6"
                >
                  <div className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
                    <div>
                      <p className="text-xs font-semibold uppercase tracking-[0.18em] text-[var(--accent-gold)]">
                        {section.kicker}
                      </p>
                      <h2 className="mt-2 text-3xl font-extrabold tracking-[-0.03em] text-[var(--ink)]">
                        {section.title}
                      </h2>
                      <p className="mt-3 max-w-3xl text-sm leading-7 text-[var(--foreground)]">
                        {section.description}
                      </p>
                    </div>

                    <div className="rounded-[20px] border border-[var(--line)] bg-white px-4 py-3 text-sm font-semibold text-[var(--foreground)]">
                      Bloc {index + 1} sur {autodiagnosticSections.length}
                    </div>
                  </div>

                  <div className="mt-5 space-y-4">
                    {section.questions.map((question) => {
                      const selectedAnswer = answers[question.id];

                      return (
                        <article
                          key={question.id}
                          className="rounded-[26px] border border-[var(--line)] bg-white p-5 shadow-[0_12px_30px_rgba(15,23,42,0.05)]"
                        >
                          <div className="flex flex-wrap items-center gap-3">
                            <p className="text-xs font-semibold uppercase tracking-[0.18em] text-[var(--primary)]">
                              Situation {question.number}
                            </p>
                            <span
                              className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold ${
                                selectedAnswer
                                  ? "bg-[rgba(47,138,99,0.12)] text-[var(--success)]"
                                  : "bg-[rgba(159,25,24,0.08)] text-[var(--accent-red)]"
                              }`}
                            >
                              {selectedAnswer
                                ? `Reponse ${selectedAnswer}`
                                : "Reponse a definir"}
                            </span>
                          </div>

                          <div className="mt-3 space-y-3 text-sm leading-7 text-[var(--foreground)]">
                            {question.context.map((paragraph) => (
                              <p key={`${question.id}-${paragraph}`}>{paragraph}</p>
                            ))}
                          </div>

                          <fieldset className="mt-5">
                            <legend className="text-xs font-semibold uppercase tracking-[0.18em] text-[var(--primary)]">
                              Choisissez la reponse la plus proche de votre reflexe actuel
                            </legend>

                            <div className="mt-3 grid gap-3 xl:grid-cols-2">
                              {question.options.map((option) => {
                                const selected = selectedAnswer === option.value;

                                return (
                                  <button
                                    key={option.value}
                                    type="button"
                                    aria-pressed={selected}
                                    onClick={() =>
                                      handleAnswerToggle(question.id, option.value)
                                    }
                                    className={`flex w-full gap-3 rounded-[22px] border px-4 py-4 text-left transition-all ${
                                      selected
                                        ? "border-[var(--primary)] bg-[rgba(23,117,186,0.08)] shadow-[0_12px_24px_rgba(23,117,186,0.12)]"
                                        : "border-[var(--line)] bg-[var(--surface-soft)] hover:border-[var(--accent-gold)] hover:bg-[rgba(216,142,4,0.08)]"
                                    }`}
                                  >
                                    <span
                                      className={`inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-sm font-extrabold ${
                                        selected
                                          ? "bg-[var(--primary)] text-white"
                                          : "bg-white text-[var(--ink)]"
                                      }`}
                                    >
                                      {option.value}
                                    </span>
                                    <span className="min-w-0 text-sm font-semibold leading-7 text-[var(--ink)]">
                                      {option.text}
                                    </span>
                                  </button>
                                );
                              })}
                            </div>
                          </fieldset>
                        </article>
                      );
                    })}
                  </div>
                </section>
              ))}
            </div>

            <div className="mt-8 flex flex-col gap-3 xl:flex-row xl:items-center">
              <button
                type="button"
                onClick={handleSubmit}
                disabled={!canSubmit || saving}
                className="inline-flex items-center justify-center rounded-full bg-[var(--primary)] px-6 py-3 text-sm font-semibold text-white transition-colors hover:bg-[var(--primary-strong)] disabled:cursor-not-allowed disabled:opacity-60"
              >
                {saving ? "Calcul en cours..." : "Voir mon resultat"}
              </button>
              <button
                type="button"
                onClick={handleReset}
                className="inline-flex items-center justify-center rounded-full border border-[var(--line)] bg-white px-6 py-3 text-sm font-semibold text-[var(--foreground)] transition-colors hover:border-[var(--accent-red)] hover:text-[var(--accent-red)]"
              >
                Reinitialiser le questionnaire
              </button>
              <Link
                href="/onboarding"
                className="inline-flex items-center justify-center rounded-full border border-[var(--line)] px-6 py-3 text-sm font-semibold text-[var(--foreground)] transition-colors hover:border-[var(--accent-gold)] hover:text-[var(--accent-gold)]"
              >
                Retour a mon contexte
              </Link>
            </div>
          </section>

          <aside className="hidden glass-card fade-in-up rounded-[32px] p-6 md:block lg:sticky lg:top-6 lg:h-fit">
            <p className="text-sm font-semibold uppercase tracking-[0.2em] text-[var(--accent-gold)]">
              Resume
            </p>
            <h2 className="mt-3 text-3xl font-extrabold tracking-[-0.04em] text-[var(--ink)]">
              Parcours du Manager
            </h2>

            <nav className="mt-4 space-y-2">
              {sectionProgress.map((section) => (
                <a
                  key={section.id}
                  href={`#${section.id}`}
                  className="flex items-center justify-between rounded-[20px] border border-[var(--line)] bg-white px-4 py-3 text-sm font-semibold text-[var(--foreground)] transition-colors hover:border-[var(--primary)] hover:text-[var(--primary)]"
                >
                  <span className="min-w-0">{section.title}</span>
                  <span className="shrink-0 rounded-full bg-[var(--surface-soft)] px-3 py-1 text-xs text-[var(--ink)]">
                    {section.answered}/{section.total}
                  </span>
                </a>
              ))}
            </nav>
          </aside>
        </div>
      </main>
    </MandatoryOnboardingGuard>
  );
}
