"use client";

import { useEffect, useMemo, useState } from "react";
import { TutorPanel } from "./TutorPanel";
import type { Course, Level } from "@/lib/courses/types";

type Props = {
  course: Course;
  level: Level;
  index: number;
  prevId: string | null;
  nextId: string | null;
};

export function LessonView({ course, level, index, prevId, nextId }: Props) {
  const [done, setDone] = useState<Set<string>>(new Set());
  const [quizChoice, setQuizChoice] = useState<number[]>([]);
  const [quizResult, setQuizResult] = useState<{
    passed: boolean;
    score: number;
    total: number;
    results: { correct: boolean; explain: string }[];
  } | null>(null);
  const [sheets, setSheets] = useState<Record<string, Record<string, string>>>({});

  useEffect(() => {
    fetch(`/api/progress?course=${course.slug}`)
      .then((r) => r.json())
      .then((j) => {
        const set = new Set<string>();
        for (const row of j.steps || []) {
          if (row.level_id === level.id) set.add(row.step_id);
        }
        setDone(set);
        const q = (j.quizzes || []).find((x: { level_id: string; passed: number }) => x.level_id === level.id);
        if (q?.passed) {
          setQuizResult({ passed: true, score: q.score, total: level.quiz.length, results: [] });
        }
      });
    fetch(`/api/worksheets?course=${course.slug}&level=${level.id}`)
      .then((r) => r.json())
      .then((j) => setSheets(j.worksheets || {}));
  }, [course.slug, level.id, level.quiz.length]);

  async function toggle(stepId: string) {
    const next = new Set(done);
    const will = !next.has(stepId);
    if (will) next.add(stepId);
    else next.delete(stepId);
    setDone(next);
    await fetch("/api/progress", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ course: course.slug, level: level.id, step: stepId, done: will }),
    });
  }

  async function saveSheet(stepId: string, data: Record<string, string>) {
    setSheets((s) => ({ ...s, [stepId]: data }));
    await fetch("/api/worksheets", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ course: course.slug, level: level.id, step: stepId, data }),
    });
  }

  async function submitQuiz() {
    const res = await fetch("/api/quiz", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ course: course.slug, level: level.id, answers: quizChoice }),
    });
    const json = await res.json();
    setQuizResult(json);
  }

  const stepPct = useMemo(
    () => Math.round((done.size / Math.max(level.steps.length, 1)) * 100),
    [done, level.steps.length]
  );

  return (
    <div className="mx-auto max-w-6xl px-4 py-8">
      <p className="text-xs uppercase tracking-[0.25em] text-terra">
        {course.short} · Level {index + 1}
      </p>
      <h1 className="font-display mt-2 text-3xl text-forest md:text-4xl">{level.title}</h1>
      <p className="mt-2 text-forest/75">{level.goal}</p>
      <div className="mt-4 h-1.5 overflow-hidden rounded-full bg-paper-2">
        <div className="h-full bg-gold" style={{ width: `${stepPct}%` }} />
      </div>

      <div className="mt-8 grid gap-8 lg:grid-cols-[minmax(0,1fr)_340px]">
        <div className="space-y-8">
          {level.steps.map((step, si) => (
            <article key={step.id} className="rounded-3xl border border-forest/10 bg-cream p-6">
              <div className="flex items-start justify-between gap-4">
                <h2 className="font-display text-2xl text-forest">
                  {si + 1}. {step.title}
                </h2>
                <button
                  type="button"
                  onClick={() => toggle(step.id)}
                  className={`shrink-0 rounded-full px-3 py-1 text-xs ${
                    done.has(step.id) ? "bg-forest text-gold-2" : "border border-forest/20 text-forest"
                  }`}
                >
                  {done.has(step.id) ? "Done" : "Mark done"}
                </button>
              </div>
              <div className="prose-step mt-4 text-sm leading-relaxed text-forest/85">
                {step.body.map((p) => (
                  <p key={p}>{p}</p>
                ))}
              </div>
              {step.bullets ? (
                <ul className="mt-4 list-disc space-y-1 pl-5 text-sm text-forest/85">
                  {step.bullets.map((b) => (
                    <li key={b}>{b}</li>
                  ))}
                </ul>
              ) : null}
              {step.platforms ? (
                <div className="mt-4 grid gap-2 sm:grid-cols-2">
                  {step.platforms.map((p) => (
                    <div key={p.name} className="rounded-2xl bg-paper p-3 text-sm">
                      <p className="font-medium text-forest">{p.name}</p>
                      <p className="text-forest/70">{p.use}</p>
                    </div>
                  ))}
                </div>
              ) : null}
              {step.checklist ? (
                <ul className="mt-4 space-y-2 text-sm">
                  {step.checklist.map((c) => (
                    <li key={c} className="flex gap-2 text-forest/85">
                      <span className="mt-0.5 text-gold">▣</span>
                      {c}
                    </li>
                  ))}
                </ul>
              ) : null}
              {step.worksheet ? (
                <div className="mt-5 rounded-2xl bg-paper p-4">
                  <p className="text-sm font-medium text-forest">{step.worksheet.title}</p>
                  <div className="mt-3 grid gap-3">
                    {step.worksheet.fields.map((f) => (
                      <label key={f.id} className="block text-xs text-forest/80">
                        {f.label}
                        <input
                          value={sheets[step.id]?.[f.id] || ""}
                          placeholder={f.placeholder}
                          onChange={(e) =>
                            saveSheet(step.id, { ...(sheets[step.id] || {}), [f.id]: e.target.value })
                          }
                          className="mt-1 w-full rounded-xl border border-forest/10 bg-white px-3 py-2 text-sm"
                        />
                      </label>
                    ))}
                  </div>
                </div>
              ) : null}
            </article>
          ))}

          <section className="rounded-3xl border border-gold/40 bg-cream p-6">
            <h2 className="font-display text-2xl text-forest">Level quiz · unlock the next floor</h2>
            <p className="mt-1 text-sm text-forest/70">Get two-thirds right to pass.</p>
            <div className="mt-6 space-y-6">
              {level.quiz.map((q, qi) => (
                <fieldset key={q.q}>
                  <legend className="text-sm font-medium text-forest">
                    {qi + 1}. {q.q}
                  </legend>
                  <div className="mt-2 space-y-2">
                    {q.options.map((opt, oi) => (
                      <label key={opt} className="flex cursor-pointer gap-2 text-sm text-forest/85">
                        <input
                          type="radio"
                          name={`q${qi}`}
                          checked={quizChoice[qi] === oi}
                          onChange={() => {
                            const next = [...quizChoice];
                            next[qi] = oi;
                            setQuizChoice(next);
                          }}
                        />
                        {opt}
                      </label>
                    ))}
                  </div>
                  {quizResult?.results?.[qi] ? (
                    <p className={`mt-2 text-xs ${quizResult.results[qi].correct ? "text-forest" : "text-terra"}`}>
                      {quizResult.results[qi].explain}
                    </p>
                  ) : null}
                </fieldset>
              ))}
            </div>
            <button
              type="button"
              onClick={submitQuiz}
              className="mt-6 rounded-full bg-forest px-5 py-2.5 text-sm font-semibold text-gold-2"
            >
              Submit quiz
            </button>
            {quizResult ? (
              <p className="mt-3 text-sm text-forest">
                {quizResult.passed
                  ? `Passed · ${quizResult.score}/${quizResult.total}. Next level is unlocked.`
                  : `Not yet · ${quizResult.score}/${quizResult.total}. Try again or ask the tutor to drill you.`}
              </p>
            ) : null}
          </section>

          <div className="flex justify-between text-sm">
            {prevId ? (
              <a className="text-terra" href={`/courses/${course.slug}/${prevId}`}>
                ← Previous level
              </a>
            ) : (
              <a className="text-forest/60" href={`/courses/${course.slug}`}>
                ← Course home
              </a>
            )}
            {nextId && quizResult?.passed ? (
              <a className="font-medium text-terra" href={`/courses/${course.slug}/${nextId}`}>
                Next level →
              </a>
            ) : (
              <span className="text-forest/40">Pass the quiz to continue</span>
            )}
          </div>
        </div>
        <div className="lg:sticky lg:top-24 lg:h-[calc(100vh-8rem)]">
          <TutorPanel course={course.slug} level={level.id} prompts={level.tutorPrompts} />
        </div>
      </div>
    </div>
  );
}
