"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { AppShell } from "@/components/app/AppShell";
import {
  SupportFeaturedGuide,
  SupportGuideCard,
  SupportQuickActions,
} from "@/components/support/SupportGuideCard";
import { TeacherSearchBar } from "@/components/teacher/ui/TeacherSearchBar";
import { getStoredUser } from "@/lib/api";
import { roleLabels } from "@/lib/role-labels";
import {
  featuredGuideForRole,
  guidesForRole,
  normalizeSupportQuery,
  searchGuides,
} from "@/lib/support-center";
import {
  getActiveBranchId,
  getActiveRole,
  getActiveRoleLabel,
} from "@/lib/session-context";

export default function SupportCenterPage() {
  const router = useRouter();
  const [query, setQuery] = useState("");
  const storedUser = getStoredUser<{ roles?: string[] }>();
  const role = getActiveRole() ?? storedUser?.roles?.[0] ?? null;
  const roleLabel = getActiveRoleLabel() ?? (role ? roleLabels[role] : null) ?? "کاربر";
  const branchId = getActiveBranchId();
  const searching = normalizeSupportQuery(query).length > 0;

  const roleGuides = useMemo(() => guidesForRole(role), [role]);
  const guides = useMemo(() => searchGuides(roleGuides, query), [roleGuides, query]);
  const featured = useMemo(
    () => (searching ? undefined : featuredGuideForRole(role)),
    [role, searching],
  );
  const otherGuides = useMemo(
    () => guides.filter((guide) => guide.id !== featured?.id),
    [guides, featured],
  );

  const hasResults = Boolean(featured) || otherGuides.length > 0;

  return (
    <AppShell title="مرکز راهنما" subtitle="راهنمای گام‌به‌گام بر اساس نقش شما">
      <div className="space-y-5">
        <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card sm:p-5">
          <p className="text-sm leading-7 text-foreground/85">
            فقط راهنماهایی که با نقش فعال شما مرتبط است نمایش داده می‌شود. برای مثال معلم بخش
            پیش‌ثبت‌نام را نمی‌بیند.
          </p>
          <div className="mt-3 flex flex-wrap gap-2 text-xs">
            <span className="rounded-full bg-primary/10 px-3 py-1 font-semibold text-primary">
              نقش: {roleLabel}
            </span>
            {branchId ? (
              <span className="rounded-full bg-slate-100 px-3 py-1 font-semibold text-slate-700">
                شعبه فعال: #{branchId}
              </span>
            ) : null}
          </div>
          <div className="mt-4">
            <TeacherSearchBar
              value={query}
              onChange={setQuery}
              placeholder="جستجو در راهنماها…"
            />
          </div>
          <div className="mt-4">
            <SupportQuickActions onSelectContext={() => router.push("/select-context")} />
          </div>
        </div>

        {!role ? (
          <div className="rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm leading-7 text-amber-900">
            برای مشاهده راهنمای مناسب، ابتدا نقش خود را از صفحه «انتخاب زمینه» مشخص کنید.
          </div>
        ) : null}

        {featured ? <SupportFeaturedGuide guide={featured} /> : null}

        {otherGuides.length ? (
          <section className="space-y-3">
            <h2 className="px-1 text-sm font-bold text-slate-900">
              {searching ? "راهنماهای مطابق جستجو" : "سایر راهنماها"}
            </h2>
            {otherGuides.map((guide) => (
              <SupportGuideCard key={`${guide.id}-${query}`} guide={guide} defaultOpen={searching} />
            ))}
          </section>
        ) : null}

        {role && !hasResults ? (
          <div className="rounded-2xl border border-[var(--border)] bg-white p-4 text-sm text-[var(--muted)]">
            {searching
              ? "نتیجه‌ای برای این جستجو در راهنماهای نقش شما پیدا نشد."
              : "هنوز راهنمای اختصاصی برای این نقش تعریف نشده است."}
          </div>
        ) : null}
      </div>
    </AppShell>
  );
}
