"use client";

import { useState } from "react";
import Link from "next/link";
import { ArrowRight, ArrowLeft, ShieldCheck } from "lucide-react";
import {
  QUICK_TEST_QUESTIONS,
  scoreQuickTest,
  quickTestConditionCopy,
  type QuickTestAnswer,
} from "@/lib/quickTest";
import { saveQuickTestLead } from "@/lib/firestore/quickTestLeads";

type Step = "intro" | "lead" | "questions" | "result";

export default function QuickTestPage() {
  const [step, setStep] = useState<Step>("intro");
  const [lead, setLead] = useState({
    name: "",
    contact: "",
    ageRange: "",
    occupation: "",
    consent: false,
  });
  const [answers, setAnswers] = useState<Record<string, number>>({});
  const [qIndex, setQIndex] = useState(0);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<ReturnType<typeof scoreQuickTest> | null>(null);

  const currentQuestion = QUICK_TEST_QUESTIONS[qIndex];
  const progress = Math.round(((qIndex + 1) / QUICK_TEST_QUESTIONS.length) * 100);

  async function handleAnswer(value: number) {
    const next = { ...answers, [currentQuestion.id]: value };
    setAnswers(next);

    if (qIndex < QUICK_TEST_QUESTIONS.length - 1) {
      setQIndex(qIndex + 1);
      return;
    }

    const answerList: QuickTestAnswer[] = QUICK_TEST_QUESTIONS.map((q) => ({
      questionId: q.id,
      value: next[q.id],
    }));
    const scored = scoreQuickTest(answerList);
    setResult(scored);
    setSaving(true);
    setError(null);
    try {
      await saveQuickTestLead({
        lead,
        answers: answerList,
        averageScore: scored.averageScore,
        condition: scored.condition,
      });
    } catch {
      setError("Hasil kamu tetap valid, tapi ada sedikit gangguan saat menyimpan data.");
    } finally {
      setSaving(false);
      setStep("result");
    }
  }

  return (
    <div className="min-h-screen bg-background text-ink">
      <header className="border-b border-border px-4 py-4 sm:px-6">
        <div className="mx-auto flex max-w-2xl items-center justify-between">
          <Link href="/" className="text-sm font-semibold text-ink">
            Mindfulness Indonesia
          </Link>
          <Link href="/" className="text-sm text-ink-soft hover:text-ink">
            Kembali
          </Link>
        </div>
      </header>

      <main className="mx-auto max-w-2xl px-4 py-10 sm:px-6">
        {step === "intro" && (
          <div className="rounded-2xl border border-border bg-surface p-6 sm:p-8">
            <h1 className="text-2xl font-bold text-ink">Quick Test — 3-Minute Peace Check</h1>
            <p className="mt-2 text-ink-soft">
              Tes cepat untuk mengenali kondisi umummu hari ini. Sekitar 2-3 menit, 7 pertanyaan
              singkat mencakup Calm, Clarity, dan Balance. Hasilnya berupa kondisi umum dan
              rekomendasi awal — tanpa skor detail.
            </p>
            <button
              onClick={() => setStep("lead")}
              className="mt-6 inline-flex items-center gap-2 rounded-full bg-primary px-6 py-3 text-sm font-medium text-primary-foreground hover:bg-primary-soft"
            >
              Mulai Tes <ArrowRight className="h-4 w-4" />
            </button>
          </div>
        )}

        {step === "lead" && (
          <form
            className="rounded-2xl border border-border bg-surface p-6 sm:p-8"
            onSubmit={(e) => {
              e.preventDefault();
              if (!lead.name || !lead.contact || !lead.consent) {
                setError("Nama, kontak, dan persetujuan wajib diisi.");
                return;
              }
              setError(null);
              setStep("questions");
            }}
          >
            <h2 className="text-xl font-bold text-ink">Sebelum mulai, kenalan dulu yuk</h2>
            <p className="mt-1 text-sm text-ink-soft">
              Data ini digunakan untuk follow-up dan rekomendasi program yang sesuai.
            </p>

            <div className="mt-5 space-y-4">
              <div>
                <label className="text-sm font-medium text-ink">Nama Lengkap</label>
                <input
                  type="text"
                  value={lead.name}
                  onChange={(e) => setLead({ ...lead, name: e.target.value })}
                  className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
                  required
                />
              </div>
              <div>
                <label className="text-sm font-medium text-ink">Email / No. WhatsApp</label>
                <input
                  type="text"
                  value={lead.contact}
                  onChange={(e) => setLead({ ...lead, contact: e.target.value })}
                  className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
                  required
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium text-ink">Usia (Range)</label>
                  <input
                    type="text"
                    placeholder="cth. 25-34"
                    value={lead.ageRange}
                    onChange={(e) => setLead({ ...lead, ageRange: e.target.value })}
                    className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
                  />
                </div>
                <div>
                  <label className="text-sm font-medium text-ink">Pekerjaan</label>
                  <input
                    type="text"
                    value={lead.occupation}
                    onChange={(e) => setLead({ ...lead, occupation: e.target.value })}
                    className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
                  />
                </div>
              </div>
              <label className="flex items-start gap-2 text-sm text-ink-soft">
                <input
                  type="checkbox"
                  checked={lead.consent}
                  onChange={(e) => setLead({ ...lead, consent: e.target.checked })}
                  className="mt-1"
                />
                Saya setuju data saya digunakan untuk follow-up dan personalisasi rekomendasi,
                sesuai kebijakan privasi Mindfulness Indonesia.
              </label>
            </div>

            {error && <p className="mt-3 text-sm text-danger">{error}</p>}

            <button
              type="submit"
              className="mt-6 inline-flex items-center gap-2 rounded-full bg-primary px-6 py-3 text-sm font-medium text-primary-foreground hover:bg-primary-soft"
            >
              Lanjut ke Tes <ArrowRight className="h-4 w-4" />
            </button>
          </form>
        )}

        {step === "questions" && currentQuestion && (
          <div className="rounded-2xl border border-border bg-surface p-6 sm:p-8">
            <div className="mb-6 h-1.5 w-full overflow-hidden rounded-full bg-surface-sunk">
              <div
                className="h-full rounded-full bg-primary transition-all"
                style={{ width: `${progress}%` }}
              />
            </div>
            <p className="text-xs font-medium uppercase tracking-wider text-ink-soft">
              Pertanyaan {qIndex + 1} dari {QUICK_TEST_QUESTIONS.length}
            </p>
            <h2 className="mt-2 text-lg font-semibold text-ink">{currentQuestion.text}</h2>

            <div className="mt-6 grid grid-cols-5 gap-2">
              {[1, 2, 3, 4, 5].map((v) => (
                <button
                  key={v}
                  onClick={() => handleAnswer(v)}
                  className="flex flex-col items-center gap-1 rounded-xl border border-border bg-background py-4 text-sm font-medium text-ink hover:border-primary hover:bg-primary-soft/20"
                >
                  {v}
                </button>
              ))}
            </div>
            <div className="mt-3 flex justify-between text-xs text-ink-soft">
              <span>Tidak pernah</span>
              <span>Sangat sering</span>
            </div>

            {qIndex > 0 && (
              <button
                onClick={() => setQIndex(qIndex - 1)}
                className="mt-6 inline-flex items-center gap-1 text-sm text-ink-soft hover:text-ink"
              >
                <ArrowLeft className="h-4 w-4" /> Kembali
              </button>
            )}
          </div>
        )}

        {step === "result" && result && (
          <div className="rounded-2xl border border-border bg-surface p-6 sm:p-8">
            <div className="mb-3 inline-flex items-center gap-2 rounded-full bg-success-soft px-3 py-1 text-xs font-medium text-success">
              <ShieldCheck className="h-3.5 w-3.5" /> Selesai — tanpa skor detail
            </div>
            <h2 className="text-xl font-bold text-ink">Hasil Peace Check Kamu</h2>
            <p className="mt-3 text-ink-soft">{quickTestConditionCopy[result.condition].summary}</p>
            <div className="mt-4 rounded-xl bg-surface-sunk p-4">
              <p className="text-sm font-medium text-ink">Rekomendasi</p>
              <p className="mt-1 text-sm text-ink-soft">
                {quickTestConditionCopy[result.condition].recommendation}
              </p>
            </div>

            {saving && <p className="mt-3 text-xs text-ink-soft">Menyimpan hasil...</p>}
            {error && <p className="mt-3 text-sm text-warning">{error}</p>}

            <div className="mt-6 flex flex-col gap-3 sm:flex-row">
              <Link
                href="/mulai/member"
                className="inline-flex items-center justify-center gap-2 rounded-full bg-primary px-6 py-3 text-sm font-medium text-primary-foreground hover:bg-primary-soft"
              >
                Jadi Member Penuh <ArrowRight className="h-4 w-4" />
              </Link>
              <Link
                href="/dashboard/programs"
                className="inline-flex items-center justify-center gap-2 rounded-full border border-border px-6 py-3 text-sm font-medium text-ink hover:bg-surface-sunk"
              >
                Lihat Program Lain
              </Link>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
