"use client";

import { useRef, useState } from "react";
import { ButtonLink } from "@/components/ui/Button";
import { Check } from "@/components/ui/Icons";
import { diagnosticQuestions } from "@/content/diagnostic";
import { cn } from "@/lib/cn";
import { auditHrefForResult, isDiagnosticComplete, scoreDiagnostic, type DiagnosticAnswers } from "@/lib/diagnostic";

export function GrowthDiagnostic() {
  const [answers, setAnswers] = useState<DiagnosticAnswers>({});
  const resultRef = useRef<HTMLDivElement>(null);

  const answeredCount = diagnosticQuestions.filter((question) => answers[question.id]).length;
  const complete = isDiagnosticComplete(answers);
  const result = complete ? scoreDiagnostic(answers) : null;

  const choose = (questionId: keyof DiagnosticAnswers, value: string) => {
    const next = { ...answers, [questionId]: value };
    const becameComplete = !complete && isDiagnosticComplete(next);
    setAnswers(next);
    if (becameComplete && window.matchMedia("(max-width: 63.99rem)").matches) {
      const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
      requestAnimationFrame(() => resultRef.current?.scrollIntoView({ behavior: reduce ? "auto" : "smooth", block: "start" }));
    }
  };

  return (
    <div className="mt-14 grid gap-6 lg:mt-20 lg:grid-cols-12">
      <form className="space-y-3 lg:col-span-7" onSubmit={(event) => event.preventDefault()} aria-label="Growth diagnostic">
        {diagnosticQuestions.map((question, questionIndex) => (
          <fieldset key={question.id} className="rounded-lg border border-line bg-surface p-5 sm:p-6">
            <legend className="sr-only">{question.label}</legend>
            <p aria-hidden="true" className="flex items-baseline gap-3">
              <span className="font-mono text-data text-muted">{String(questionIndex + 1).padStart(2, "0")}/05</span>
              <span className="font-medium tracking-[-0.01em]">{question.label}</span>
              {answers[question.id] ? <Check size={14} className="ml-auto text-signal" /> : null}
            </p>
            <div className="mt-4 flex flex-wrap gap-2">
              {question.options.map((option) => {
                const checked = answers[question.id] === option.value;
                return (
                  <label key={option.value} className="relative">
                    <input
                      type="radio"
                      name={question.id}
                      value={option.value}
                      checked={checked}
                      onChange={() => choose(question.id, option.value)}
                      className="peer absolute inset-0 cursor-pointer opacity-0"
                    />
                    <span
                      className={cn(
                        "pointer-events-none inline-flex min-h-11 items-center rounded-md border px-4 text-[0.9375rem] transition-colors duration-200",
                        "peer-focus-visible:outline peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-signal",
                        checked ? "border-ink bg-ink text-paper" : "border-line-strong bg-paper text-ink peer-hover:border-ink",
                      )}
                    >
                      {option.label}
                    </span>
                  </label>
                );
              })}
            </div>
          </fieldset>
        ))}
      </form>

      <div ref={resultRef} className="scroll-mt-24 lg:col-span-5">
        <div className="tone-night rounded-lg bg-night p-7 text-night-text sm:p-9 lg:sticky lg:top-24">
          <div aria-live="polite" aria-atomic="true">
            {result ? (
              <div key={result.title} className="fade-rise">
                <p className="text-label uppercase text-night-muted">Your biggest opportunity appears to be</p>
                <p className="mt-4 text-display-md text-night-text">{result.title}.</p>
                <p className="mt-5 text-night-muted">{result.summary}</p>
                <p className="mt-7 text-label uppercase text-night-muted">What we&rsquo;d check first</p>
                <ul className="mt-3 space-y-3">
                  {result.checks.map((check) => (
                    <li key={check} className="flex gap-3 text-[0.9375rem]">
                      <span aria-hidden="true" className="mt-2 size-1.5 shrink-0 bg-signal-bright" />
                      {check}
                    </li>
                  ))}
                </ul>
              </div>
            ) : (
              <div>
                <p className="text-label uppercase text-night-muted">
                  {answeredCount} of 5 answered
                </p>
                <div className="mt-4 grid grid-cols-5 gap-1.5" aria-hidden="true">
                  {diagnosticQuestions.map((question) => (
                    <span
                      key={question.id}
                      className={cn("h-1 rounded-full transition-colors duration-300", answers[question.id] ? "bg-signal-bright" : "bg-night-line")}
                    />
                  ))}
                </div>
                <p className="mt-8 text-title text-night-text">Your result appears here once all five questions are answered.</p>
                <p className="mt-4 text-night-muted">
                  You&rsquo;ll get a general category, why it matters, and what we would look at first. No revenue projections.
                </p>
              </div>
            )}
          </div>

          {result ? (
            <div className="mt-9 flex flex-col items-start gap-3 border-t border-night-line pt-7">
              <ButtonLink href={auditHrefForResult(result)} tone="dark" size="lg">
                Request the Full Growth Audit
              </ButtonLink>
              <button
                type="button"
                onClick={() => setAnswers({})}
                className="min-h-11 text-sm text-night-muted underline decoration-night-line underline-offset-4 hover:text-night-text"
              >
                Start over
              </button>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
}
