import Link from "next/link";
import { GitBranch, Plus } from "lucide-react";
import { PageHeader } from "@/components/shared/PageHeader";
import { EmptyState } from "@/components/shared/EmptyState";
import { Card } from "@/components/ui/Card";
import { cn } from "@/lib/utils/cn";
import { DomesticCategoryManager } from "@/components/features/admin/domestic/DomesticCategoryManager";
import {
  getDomesticCategories,
  getDomesticQuestions,
} from "@/lib/queries/domestic-admin-queries";
import { DOMESTIC_TYPE_LABELS } from "@/lib/domestic/rules";
import type { DomesticQuestionStatus } from "@/types/participant";

export const dynamic = "force-dynamic";

const STATUS_FILTERS = ["all", "draft", "published", "paused", "retired"] as const;

const STATUS_STYLES: Record<DomesticQuestionStatus, string> = {
  draft: "bg-[#F1F5F9] text-muted",
  review: "bg-warning-bg text-warning",
  published: "bg-success-bg text-success",
  paused: "bg-warning-bg text-warning",
  retired: "bg-danger-bg text-danger",
};

interface Props {
  searchParams: Record<string, string | string[] | undefined>;
}

export default async function AdminDomesticPage({ searchParams }: Props) {
  const status = String(searchParams.status ?? "all");
  const search = String(searchParams.search ?? "").trim();
  const categoryId = String(searchParams.category ?? "");

  const [categories, questions] = await Promise.all([
    getDomesticCategories(),
    getDomesticQuestions({
      status: status === "all" ? undefined : status,
      search: search || undefined,
      categoryId: categoryId || undefined,
    }),
  ]);

  const qs = (next: Record<string, string>) => {
    const params = new URLSearchParams({
      ...(status !== "all" ? { status } : {}),
      ...(search ? { search } : {}),
      ...(categoryId ? { category: categoryId } : {}),
      ...next,
    });
    for (const [k, v] of Array.from(params.entries())) if (!v || v === "all") params.delete(k);
    const s = params.toString();
    return s ? `?${s}` : "";
  };

  return (
    <>
      <PageHeader
        title="Domestic Question Bank"
        subtitle="Platform-owned nonstop questions with versioning and branching"
        actions={
          <Link
            href="/admin/domestic/questions/new"
            className="inline-flex items-center gap-1.5 rounded-sm bg-accent px-[18px] py-2.5 text-sm font-semibold text-navy hover:bg-[#22b3ec]"
          >
            <Plus className="h-4 w-4" />
            New question
          </Link>
        }
      />
      <div className="flex-1 overflow-y-auto p-4 sm:p-[26px]">
        <div className="grid grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1fr)_300px]">
          <div>
            <div className="mb-3 flex flex-wrap items-center gap-2">
              {STATUS_FILTERS.map((s) => (
                <Link
                  key={s}
                  href={`/admin/domestic${qs({ status: s })}`}
                  className={cn(
                    "rounded-full border px-3 py-1.5 text-[12.5px] font-semibold capitalize",
                    status === s
                      ? "border-primary bg-[#EFF6FF] text-primary"
                      : "border-border bg-white text-muted hover:border-primary/40"
                  )}
                >
                  {s}
                </Link>
              ))}
              <form className="ml-auto" action="/admin/domestic">
                {status !== "all" && <input type="hidden" name="status" value={status} />}
                {categoryId && <input type="hidden" name="category" value={categoryId} />}
                <input
                  name="search"
                  defaultValue={search}
                  placeholder="Search code or text…"
                  className="w-[220px] rounded-sm border border-border px-3 py-1.5 text-[13px] focus:border-primary focus:outline-none"
                />
              </form>
            </div>

            <Card className="overflow-hidden">
              {questions.length === 0 ? (
                <EmptyState
                  title="No questions found"
                  description="Create your first domestic question to start the nonstop feed."
                />
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-[13px]">
                    <thead className="border-b border-border bg-[#F8FAFC] text-[11.5px] uppercase tracking-wide text-muted">
                      <tr>
                        <th className="px-4 py-3 font-bold">Code</th>
                        <th className="px-4 py-3 font-bold">Question</th>
                        <th className="px-4 py-3 font-bold">Category</th>
                        <th className="px-4 py-3 font-bold">Status</th>
                        <th className="px-4 py-3 text-right font-bold">Answers</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border">
                      {questions.map((q) => (
                        <tr key={q.id} className="hover:bg-[#F8FAFC]">
                          <td className="whitespace-nowrap px-4 py-3 font-mono text-[12px] font-bold">
                            <Link
                              href={`/admin/domestic/questions/${q.id}`}
                              className="text-primary hover:underline"
                            >
                              {q.code}
                            </Link>
                          </td>
                          <td className="px-4 py-3">
                            <Link
                              href={`/admin/domestic/questions/${q.id}`}
                              className="line-clamp-2 font-medium text-text hover:text-primary"
                            >
                              {q.prompt || "—"}
                            </Link>
                            <div className="mt-0.5 flex flex-wrap items-center gap-2 text-[11.5px] text-muted">
                              {q.type && <span>{DOMESTIC_TYPE_LABELS[q.type]}</span>}
                              {q.versionNumber && <span>v{q.versionNumber}</span>}
                              <span>{q.isEntry ? "Entry" : "Follow-up only"}</span>
                              {q.ruleCount > 0 && (
                                <span className="inline-flex items-center gap-1">
                                  <GitBranch className="h-3 w-3" />
                                  {q.ruleCount}
                                </span>
                              )}
                            </div>
                          </td>
                          <td className="whitespace-nowrap px-4 py-3 text-muted">
                            {q.categoryName}
                          </td>
                          <td className="px-4 py-3">
                            <span
                              className={cn(
                                "rounded-full px-2.5 py-1 text-[11.5px] font-bold capitalize",
                                STATUS_STYLES[q.status]
                              )}
                            >
                              {q.status}
                            </span>
                          </td>
                          <td className="px-4 py-3 text-right font-mono">
                            {q.answerCount > 0 ? (
                              <Link
                                href={`/admin/domestic/questions/${q.id}#responses`}
                                className="font-semibold text-primary hover:underline"
                              >
                                {q.answerCount}
                              </Link>
                            ) : (
                              "0"
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </Card>
          </div>

          <DomesticCategoryManager categories={categories} />
        </div>
      </div>
    </>
  );
}
