"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Download, Printer, MessageCircle, Crown } from "lucide-react";
import type { Level } from "@/lib/data";
import type { AssessmentType } from "@/lib/firestore/assessments";
import { saveAssessmentResult } from "@/lib/firestore/assessments";
import { flagLowScoreAlert } from "@/lib/firestore/lowScoreAlerts";
import { subscribeMembershipSettings, type MembershipSettings } from "@/lib/firestore/membership";
import { useAuthContext } from "@/components/FirebaseProvider";
import { isMember } from "@/lib/roles";
import { WaveGauge } from "@/components/WaveGauge";
import { downloadAssessmentResultPdf } from "@/lib/pdf/assessmentReport";
import { scoreDsasFromAssessment } from "@/lib/dsasAssessmentBridge";
import { saveDsasResult } from "@/lib/firestore/dsasResults";

// NOTE ON POLARITY: the questions themselves now score "wellness" — a
// higher raw score (sum of the chosen PG option scores) means the person is
// doing BETTER, matching the revision doc ("kalau skor udah cukup maka
// aman"). But every existing HR-facing/PDF/aggregate consumer of
// AssessmentResult.score+level (levelColor, recommendationFor, /api/stats'
// department-risk ranking) was built around the OPPOSITE convention: higher
// = more concern (High = red = prioritized). Rather than touch all of
// that, we convert once here: store a `concernScore` (100 - wellness%) as
// AssessmentResult.score, so HR/PDF keep working completely unchanged. The
// employee-facing UI below never shows concernScore/Level at all — it only
// ever shows the raw wellness score against the assessment's own
// healthThreshold, with soft wording.
function scoreToLevel(concernScore: number): Level {
  if (concernScore >= 66) return "High";
  if (concernScore >= 40) return "Medium";
  return "Low";
}

export function AssessmentRunner({ assessment }: { assessment: AssessmentType }) {
  const { user, profile } = useAuthContext();
  const [step, setStep] = useState(0);
  const [chosenScores, setChosenScores] = useState<number[]>([]);
  const [submitted, setSubmitted] = useState(false);
  const [saveError, setSaveError] = useState("");
  const [settings, setSettings] = useState<MembershipSettings | null>(null);
  const [alerted, setAlerted] = useState(false);

  useEffect(() => {
    const unsub = subscribeMembershipSettings(setSettings);
    return unsub;
  }, []);

  const member = isMember(profile);
  const totalQuestions = assessment.questions.length;
  const visibleCount = member
    ? totalQuestions
    : Math.min(assessment.basicQuestionCount || totalQuestions, totalQuestions);
  const questions = assessment.questions.slice(0, visibleCount);

  const maxPossible = questions.reduce(
    (sum, q) => sum + q.options.reduce((m, o) => Math.max(m, o.score), 0),
    0
  );
  // Scale the threshold down proportionally when a non-member only answers
  // a subset of the questions — comparing a partial score against the
  // full-assessment threshold wouldn't be fair otherwise.
  const effectiveThreshold = Math.round(
    (assessment.healthThreshold || 0) * (visibleCount / (totalQuestions || 1))
  );

  const current = questions[step];
  const rawScore = chosenScores.reduce((a, b) => a + b, 0);
  const isSafe = rawScore >= effectiveThreshold;
  const wellnessPct = maxPossible > 0 ? rawScore / maxPossible : 0;
  const concernScore = Math.round((1 - wellnessPct) * 100);
  const level = scoreToLevel(concernScore);

  function choose(score: number) {
    const next = [...chosenScores, score];
    setChosenScores(next);
    if (step + 1 < questions.length) {
      setStep(step + 1);
    } else {
      finish(next);
    }
  }

  function goBack() {
    if (step === 0) return;
    setChosenScores(chosenScores.slice(0, -1));
    setStep(step - 1);
  }

  async function finish(finalScores: number[]) {
    setSubmitted(true);
    const total = finalScores.reduce((a, b) => a + b, 0);
    const pct = maxPossible > 0 ? total / maxPossible : 0;
    const concern = Math.round((1 - pct) * 100);
    const lvl = scoreToLevel(concern);

    if (user) {
      try {
        await saveAssessmentResult({
          uid: user.uid,
          slug: assessment.slug,
          dimension: assessment.dimension,
          title: assessment.title,
          answers: finalScores,
          score: concern,
          level: lvl,
        });
      } catch (e: unknown) {
        setSaveError(e instanceof Error ? e.message : "Gagal menyimpan hasil");
      }

      // Additionally feed the DSAS priority funnel when this assessment is
      // tagged as such — kept as a best-effort side write (never blocks the
      // employee's normal result from saving/displaying) since the DSAS
      // pipeline is a separate concern (urgency alerts, 300-participant
      // selection) from the per-employee result shown above.
      if (assessment.isDsasAssessment && profile?.company) {
        try {
          const categories = scoreDsasFromAssessment(assessment, finalScores);
          if (categories.length > 0) {
            await saveDsasResult({
              uid: user.uid,
              companyId: profile.company,
              categories,
              isMember: member,
            });
          }
        } catch {
          // Non-critical — the employee's own result above already saved.
        }
      }
    }

    if (total < Math.round((assessment.healthThreshold || 0) * (finalScores.length / (totalQuestions || 1))) && !alerted) {
      setAlerted(true);
      flagLowScoreAlert({ company: profile?.company, dimension: assessment.dimension });
    }
  }

  if (submitted) {
    return (
      <div className="mx-auto max-w-xl space-y-6 print:max-w-full">
        <WaveGauge label={assessment.title} level={level} score={rawScore} />

        <div className="rounded-2xl border border-border bg-surface p-6 text-center">
          <p className="text-3xl font-bold text-ink">
            {rawScore} <span className="text-base font-normal text-ink-soft">/ {maxPossible}</span>
          </p>
          {isSafe ? (
            <p className="mt-2 font-semibold text-success">Kondisi Baik &mdash; Sehat &amp; Terjaga</p>
          ) : (
            <p className="mt-2 font-semibold text-accent">Perlu Perhatian Lebih</p>
          )}
          {!member && visibleCount < totalQuestions && (
            <p className="mt-2 text-xs text-ink-soft">
              Ini hasil dari {visibleCount} dari {totalQuestions} soal (versi Non-Member). Upgrade ke
              Member untuk assessment lengkap.
            </p>
          )}
        </div>

        {!isSafe && (
          <div className="rounded-2xl border border-accent/40 bg-accent/10 p-6 space-y-3">
            <p className="text-sm text-ink">
              Skor kamu ada di bawah batas aman untuk assessment ini. Ini bukan diagnosis, tapi
              tanda baik untuk mengobrol dengan psikolog kami — gak apa-apa kok, banyak yang
              ngerasa begini.
            </p>
            {member ? (
              <div className="flex flex-wrap gap-2">
                {settings?.psychologistWhatsapp && (
                  <a
                    href={`https://wa.me/${settings.psychologistWhatsapp.replace(/[^0-9]/g, "")}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-1.5 rounded-lg bg-success px-4 py-2 text-sm font-semibold text-white hover:opacity-90"
                  >
                    <MessageCircle size={15} /> Chat Psikolog via WhatsApp
                  </a>
                )}
                <Link
                  href="/dashboard/counseling"
                  className="flex items-center gap-1.5 rounded-lg border border-border px-4 py-2 text-sm font-medium text-ink hover:bg-surface-sunk"
                >
                  Booking Sesi Konseling
                </Link>
              </div>
            ) : (
              <Link
                href="/dashboard/membership"
                className="inline-flex items-center gap-1.5 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:bg-primary-soft"
              >
                <Crown size={15} /> Upgrade ke Member untuk Akses Psikolog Langsung
              </Link>
            )}
          </div>
        )}

        {saveError && <p className="text-center text-sm text-danger">{saveError}</p>}

        <div className="flex flex-wrap justify-center gap-3 print:hidden">
          <button
            onClick={() => window.print()}
            className="flex items-center gap-1.5 rounded-lg border border-border px-4 py-2 text-sm font-medium text-ink hover:bg-surface-sunk"
          >
            <Printer size={15} /> Cetak / Simpan sebagai PDF
          </button>
          <button
            onClick={() =>
              downloadAssessmentResultPdf(
                {
                  id: "local",
                  uid: user?.uid || "",
                  slug: assessment.slug,
                  dimension: assessment.dimension,
                  title: assessment.title,
                  answers: chosenScores,
                  score: concernScore,
                  level,
                },
                profile?.name || "Karyawan"
              )
            }
            className="flex items-center gap-1.5 rounded-lg border border-border px-4 py-2 text-sm font-medium text-ink hover:bg-surface-sunk"
          >
            <Download size={15} /> Download PDF
          </button>
          <Link href="/dashboard/assessment" className="flex items-center gap-1.5 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary-soft">
            Kembali ke Daftar Assessment
          </Link>
        </div>
      </div>
    );
  }

  if (!current) {
    return <p className="text-center text-sm text-ink-soft">Assessment ini belum punya pertanyaan.</p>;
  }

  return (
    <div className="mx-auto max-w-xl space-y-6">
      <div>
        <div className="mb-2 flex items-center justify-between text-xs text-ink-soft">
          <span>Pertanyaan {step + 1} dari {questions.length}</span>
          <span>{Math.round(((step) / questions.length) * 100)}%</span>
        </div>
        <div className="h-1.5 w-full overflow-hidden rounded-full bg-surface-sunk">
          <div
            className="h-full rounded-full bg-primary transition-all"
            style={{ width: `${(step / questions.length) * 100}%` }}
          />
        </div>
      </div>

      <h2 className="font-display text-xl font-semibold text-ink">{current.text}</h2>

      <div className="space-y-2.5">
        {current.options.map((opt, i) => (
          <button
            key={i}
            onClick={() => choose(opt.score)}
            className="w-full rounded-xl border border-border bg-surface px-4 py-3 text-left text-sm font-medium text-ink transition-colors hover:border-primary hover:bg-primary/5"
          >
            {opt.text}
          </button>
        ))}
      </div>

      {step > 0 && (
        <button onClick={goBack} className="text-sm font-medium text-ink-soft hover:text-ink">
          &larr; Kembali
        </button>
      )}
    </div>
  );
}
