"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { Plus, Trash2, Pencil, X } from "lucide-react";
import { RoleGuard } from "@/components/RoleGuard";
import { ROLES } from "@/lib/roles";
import { dimensionLabels, type Dimension } from "@/lib/data";
import { dsasCategoryLabels, type DsasCategory } from "@/lib/dsas";
import {
  subscribeAssessmentTypes,
  saveAssessmentType,
  deleteAssessmentType,
  type AssessmentType,
  type NewAssessmentType,
  type AssessmentQuestion,
} from "@/lib/firestore/assessments";

const DIMENSIONS = Object.keys(dimensionLabels) as Dimension[];

// Shown as a starting template whenever admin clicks "Assessment Baru" —
// point 7 of the revision doc ("assesment nya di kasih contoh soalnya
// juga"). Admin edits/replaces this rather than starting from a blank form.
const EXAMPLE_QUESTIONS: AssessmentQuestion[] = [
  {
    text: "Contoh: Seberapa sering kamu merasa cukup istirahat setelah bangun tidur?",
    options: [
      { text: "Hampir selalu", score: 25 },
      { text: "Sering", score: 18 },
      { text: "Kadang-kadang", score: 10 },
      { text: "Jarang sekali", score: 0 },
    ],
  },
  {
    text: "Contoh: Seberapa mampu kamu menyelesaikan pekerjaan tanpa merasa kewalahan?",
    options: [
      { text: "Sangat mampu", score: 25 },
      { text: "Cukup mampu", score: 18 },
      { text: "Kurang mampu", score: 10 },
      { text: "Tidak mampu sama sekali", score: 0 },
    ],
  },
];

const emptyForm: NewAssessmentType = {
  slug: "",
  dimension: "stress",
  title: "",
  description: "",
  duration: "5 menit",
  questions: EXAMPLE_QUESTIONS,
  healthThreshold: 60,
  basicQuestionCount: 1,
  isDsasAssessment: false,
};

function slugify(s: string) {
  return s
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/(^-|-$)/g, "");
}

function maxPossibleScore(questions: AssessmentQuestion[]): number {
  return questions.reduce((sum, q) => {
    const best = q.options.reduce((m, o) => Math.max(m, o.score), 0);
    return sum + best;
  }, 0);
}

function AssessmentsPageInner() {
  const [types, setTypes] = useState<AssessmentType[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingSlug, setEditingSlug] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState<NewAssessmentType>(emptyForm);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    const unsub = subscribeAssessmentTypes((t) => {
      setTypes(t);
      setLoading(false);
    });
    return unsub;
  }, []);

  function openCreate() {
    setEditingSlug(null);
    setForm(emptyForm);
    setShowForm(true);
    setError("");
  }

  function openEdit(a: AssessmentType) {
    setEditingSlug(a.slug);
    setForm({
      slug: a.slug,
      dimension: a.dimension,
      title: a.title,
      description: a.description,
      duration: a.duration,
      questions: a.questions.map((q) => ({ text: q.text, options: q.options.map((o) => ({ ...o })) })),
      healthThreshold: a.healthThreshold ?? 60,
      basicQuestionCount: a.basicQuestionCount ?? a.questions.length,
    });
    setShowForm(true);
    setError("");
  }

  function updateQuestionText(qi: number, value: string) {
    const next = [...form.questions];
    next[qi] = { ...next[qi], text: value };
    setForm({ ...form, questions: next });
  }

  function updateQuestionCategory(qi: number, category: DsasCategory) {
    const next = [...form.questions];
    next[qi] = { ...next[qi], dsasCategory: category };
    setForm({ ...form, questions: next });
  }

  function updateOption(qi: number, oi: number, field: "text" | "score", value: string) {
    const next = [...form.questions];
    const opts = [...next[qi].options];
    opts[oi] = { ...opts[oi], [field]: field === "score" ? Number(value) || 0 : value };
    next[qi] = { ...next[qi], options: opts };
    setForm({ ...form, questions: next });
  }

  function addQuestion() {
    setForm({
      ...form,
      questions: [
        ...form.questions,
        { text: "", options: [{ text: "", score: 0 }, { text: "", score: 0 }] },
      ],
    });
  }

  function removeQuestion(qi: number) {
    setForm({ ...form, questions: form.questions.filter((_, i) => i !== qi) });
  }

  function addOption(qi: number) {
    const next = [...form.questions];
    next[qi] = { ...next[qi], options: [...next[qi].options, { text: "", score: 0 }] };
    setForm({ ...form, questions: next });
  }

  function removeOption(qi: number, oi: number) {
    const next = [...form.questions];
    next[qi] = { ...next[qi], options: next[qi].options.filter((_, i) => i !== oi) };
    setForm({ ...form, questions: next });
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const cleanQuestions = form.questions
      .map((q) => ({ text: q.text.trim(), options: q.options.filter((o) => o.text.trim()) }))
      .filter((q) => q.text && q.options.length >= 2);

    if (!form.title.trim() || !form.description.trim() || cleanQuestions.length === 0) {
      setError("Judul, deskripsi, dan minimal 1 pertanyaan (dengan minimal 2 opsi jawaban) wajib diisi");
      return;
    }

    const slug = editingSlug || slugify(form.title);
    setSaving(true);
    setError("");
    try {
      await saveAssessmentType({
        ...form,
        slug,
        questions: cleanQuestions,
        basicQuestionCount: Math.min(form.basicQuestionCount, cleanQuestions.length) || cleanQuestions.length,
      });
      setShowForm(false);
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Gagal menyimpan assessment");
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete(slug: string) {
    if (!confirm("Hapus assessment ini? Hasil assessment karyawan yang sudah ada tidak ikut terhapus.")) return;
    try {
      await deleteAssessmentType(slug);
    } catch {
      alert("Gagal menghapus assessment");
    }
  }

  const currentMax = maxPossibleScore(form.questions);

  return (
    <div className="min-h-screen bg-background">
      <header className="border-b border-border bg-surface px-4 py-5 sm:px-8">
        <div className="mx-auto flex max-w-6xl items-center justify-between gap-3">
          <div className="flex min-w-0 items-center gap-3 sm:gap-4">
            <Image src="/mindfulness-logo.png" alt="Mindfulness Indonesia" width={120} height={30} className="hidden shrink-0 sm:block" />
            <div className="min-w-0">
              <p className="truncate text-xs font-medium uppercase tracking-wide text-ink-soft">Super Admin</p>
              <h1 className="truncate font-display text-xl font-semibold text-ink">Kelola Assessment</h1>
            </div>
          </div>
          <Link href="/super-admin" className="shrink-0 text-sm font-medium text-ink-soft hover:text-ink">
            &larr; Kembali
          </Link>
        </div>
      </header>

      <main className="mx-auto max-w-6xl space-y-6 px-4 py-10 sm:px-8">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <p className="text-sm text-ink-soft">
            Tiap pertanyaan pilihan ganda punya skor sendiri per opsi jawaban. Karyawan Non-Member
            cuma lihat sejumlah pertanyaan pertama (atur di &quot;Jumlah soal versi Non-Member&quot;);
            Member lihat semua.
          </p>
          <button
            onClick={openCreate}
            className="flex shrink-0 items-center gap-1.5 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary-soft"
          >
            <Plus size={16} /> Assessment Baru
          </button>
        </div>

        {showForm && (
          <div className="rounded-2xl border border-border bg-surface p-6">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="font-display text-base font-semibold text-ink">
                {editingSlug ? "Edit Assessment" : "Assessment Baru"}
              </h2>
              <button onClick={() => setShowForm(false)} className="text-ink-soft hover:text-ink">
                <X size={18} />
              </button>
            </div>
            <form onSubmit={handleSubmit} className="space-y-5">
              <input
                placeholder="Judul assessment"
                value={form.title}
                onChange={(e) => setForm({ ...form, title: e.target.value })}
                className="w-full rounded-lg border border-border bg-background px-3.5 py-2.5 text-sm text-ink outline-none focus:border-primary"
              />
              <textarea
                placeholder="Deskripsi singkat"
                value={form.description}
                onChange={(e) => setForm({ ...form, description: e.target.value })}
                rows={2}
                className="w-full rounded-lg border border-border bg-background px-3.5 py-2.5 text-sm text-ink outline-none focus:border-primary"
              />

              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <select
                  value={form.dimension}
                  onChange={(e) => setForm({ ...form, dimension: e.target.value as Dimension })}
                  className="w-full rounded-lg border border-border bg-background px-3.5 py-2.5 text-sm text-ink outline-none focus:border-primary"
                >
                  {DIMENSIONS.map((d) => (
                    <option key={d} value={d}>{dimensionLabels[d]}</option>
                  ))}
                </select>
                <input
                  placeholder="Durasi (mis. 5 menit)"
                  value={form.duration}
                  onChange={(e) => setForm({ ...form, duration: e.target.value })}
                  className="w-full rounded-lg border border-border bg-background px-3.5 py-2.5 text-sm text-ink outline-none focus:border-primary"
                />
              </div>

              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-ink">
                    Batas Skor Aman (dari max {currentMax || "?"})
                  </label>
                  <input
                    type="number"
                    min={0}
                    value={form.healthThreshold}
                    onChange={(e) => setForm({ ...form, healthThreshold: Number(e.target.value) || 0 })}
                    className="w-full rounded-lg border border-border bg-background px-3.5 py-2.5 text-sm text-ink outline-none focus:border-primary"
                  />
                  <p className="mt-1 text-xs text-ink-soft">Skor di bawah ini akan disarankan konsultasi psikolog.</p>
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-ink">
                    Jumlah Soal Versi Non-Member (dari {form.questions.length} total)
                  </label>
                  <input
                    type="number"
                    min={1}
                    max={form.questions.length}
                    value={form.basicQuestionCount}
                    onChange={(e) => setForm({ ...form, basicQuestionCount: Number(e.target.value) || 1 })}
                    className="w-full rounded-lg border border-border bg-background px-3.5 py-2.5 text-sm text-ink outline-none focus:border-primary"
                  />
                  <p className="mt-1 text-xs text-ink-soft">Member selalu lihat semua {form.questions.length} soal.</p>
                </div>
              </div>

              <label className="flex items-center gap-2 rounded-lg border border-border bg-background px-3.5 py-2.5 text-sm text-ink">
                <input
                  type="checkbox"
                  checked={!!form.isDsasAssessment}
                  onChange={(e) => setForm({ ...form, isDsasAssessment: e.target.checked })}
                />
                Ini assessment DSAS (feed ke funnel prioritas 1000&rarr;300 peserta)
              </label>
              {form.isDsasAssessment && (
                <p className="text-xs text-ink-soft">
                  Set kategori DSAS (Depresi/Anxiety/Stress) di tiap pertanyaan di bawah.
                </p>
              )}

              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="font-display text-sm font-semibold text-ink">Pertanyaan (Pilihan Ganda)</h3>
                  <span className="text-xs text-ink-soft">Skor maksimal total: {currentMax}</span>
                </div>
                {form.questions.map((q, qi) => (
                  <div key={qi} className="rounded-xl border border-border bg-background p-4 space-y-3">
                    <div className="flex items-start gap-2">
                      <textarea
                        placeholder={`Pertanyaan ${qi + 1}`}
                        value={q.text}
                        onChange={(e) => updateQuestionText(qi, e.target.value)}
                        rows={2}
                        className="w-full rounded-lg border border-border bg-surface px-3 py-2 text-sm text-ink outline-none focus:border-primary"
                      />
                      <button type="button" onClick={() => removeQuestion(qi)} className="mt-1 shrink-0 text-danger hover:opacity-70">
                        <Trash2 size={16} />
                      </button>
                    </div>
                    {form.isDsasAssessment && (
                      <select
                        value={q.dsasCategory ?? ""}
                        onChange={(e) => updateQuestionCategory(qi, e.target.value as DsasCategory)}
                        className="w-full rounded-lg border border-border bg-surface px-3 py-1.5 text-sm text-ink outline-none focus:border-primary"
                      >
                        <option value="" disabled>Pilih kategori DSAS...</option>
                        {(Object.keys(dsasCategoryLabels) as DsasCategory[]).map((c) => (
                          <option key={c} value={c}>{dsasCategoryLabels[c]}</option>
                        ))}
                      </select>
                    )}
                    <div className="space-y-2 pl-3">
                      {q.options.map((o, oi) => (
                        <div key={oi} className="flex items-center gap-2">
                          <input
                            placeholder={`Opsi ${oi + 1}`}
                            value={o.text}
                            onChange={(e) => updateOption(qi, oi, "text", e.target.value)}
                            className="w-full rounded-lg border border-border bg-surface px-3 py-1.5 text-sm text-ink outline-none focus:border-primary"
                          />
                          <input
                            type="number"
                            placeholder="Skor"
                            value={o.score}
                            onChange={(e) => updateOption(qi, oi, "score", e.target.value)}
                            className="w-20 shrink-0 rounded-lg border border-border bg-surface px-2 py-1.5 text-sm text-ink outline-none focus:border-primary"
                          />
                          <button type="button" onClick={() => removeOption(qi, oi)} className="shrink-0 text-ink-soft hover:text-danger">
                            <X size={14} />
                          </button>
                        </div>
                      ))}
                      <button type="button" onClick={() => addOption(qi)} className="text-xs font-medium text-primary hover:underline">
                        + Tambah opsi
                      </button>
                    </div>
                  </div>
                ))}
                <button type="button" onClick={addQuestion} className="flex items-center gap-1.5 text-sm font-medium text-primary hover:underline">
                  <Plus size={14} /> Tambah pertanyaan
                </button>
              </div>

              {error && <p className="text-sm text-danger">{error}</p>}
              <button
                type="submit"
                disabled={saving}
                className="w-full rounded-lg bg-primary py-2.5 text-sm font-semibold text-primary-foreground hover:bg-primary-soft disabled:opacity-50"
              >
                {saving ? "Menyimpan..." : editingSlug ? "Simpan Perubahan" : "Tambah Assessment"}
              </button>
            </form>
          </div>
        )}

        {loading ? (
          <p className="text-sm text-ink-soft">Memuat...</p>
        ) : types.length === 0 ? (
          <p className="text-sm text-ink-soft">Belum ada assessment. Klik &quot;Assessment Baru&quot; untuk menambahkan.</p>
        ) : (
          <div className="space-y-3">
            {types.map((a) => (
              <div key={a.slug} className="flex flex-col justify-between gap-3 rounded-2xl border border-border bg-surface p-5 sm:flex-row sm:items-center">
                <div className="min-w-0">
                  <p className="truncate font-medium text-ink">{a.title}</p>
                  <p className="truncate text-sm text-ink-soft">
                    {a.questions.length} soal &middot; batas aman {a.healthThreshold ?? "-"}/{maxPossibleScore(a.questions)}
                    &middot; Non-Member lihat {a.basicQuestionCount ?? a.questions.length} soal
                  </p>
                </div>
                <div className="flex shrink-0 gap-2">
                  <button onClick={() => openEdit(a)} className="flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-sm font-medium text-ink hover:bg-surface-sunk">
                    <Pencil size={14} /> Edit
                  </button>
                  <button onClick={() => handleDelete(a.slug)} className="flex items-center gap-1.5 rounded-lg border border-danger/30 px-3 py-1.5 text-sm font-medium text-danger hover:bg-danger/10">
                    <Trash2 size={14} /> Hapus
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </main>
    </div>
  );
}

export default function AssessmentsAdminPage() {
  return (
    <RoleGuard allowedRoles={[ROLES.SUPER_ADMIN]}>
      <AssessmentsPageInner />
    </RoleGuard>
  );
}
