"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { AppShell } from "@/components/app/AppShell";
import { ListExportActions } from "@/components/export/ListExportActions";
import { DataTable, DataTableEmpty } from "@/components/layout/DataTable";
import { Pagination } from "@/components/layout/Pagination";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Field, Select } from "@/components/ui/Field";
import {
  ApiError,
  DeskApplication,
  Paginated,
  apiGet,
} from "@/lib/api";
import { getActiveBranchId } from "@/lib/session-context";
import { STATUS_LABELS } from "@/lib/labels";
import {
  PRE_REGISTRATION_BUCKETS,
  PRE_REGISTRATION_GROUP_STATUSES,
  isPreRegistrationGroup,
  type PreRegistrationGroup,
} from "@/lib/pre-registration-dashboard";

function genderLabel(gender?: string | null) {
  if (gender === "male") return "پسر";
  if (gender === "female") return "دختر";
  return "—";
}

function formatDate(value?: string | null) {
  if (!value) return "—";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return value;
  return d.toLocaleDateString("fa-IR");
}

function paymentLabel(item: DeskApplication) {
  const pay = item.payment_summary;
  if (!pay) return "—";
  const amount =
    pay.amount != null ? `${Number(pay.amount).toLocaleString("fa-IR")} ریال` : "";
  return [pay.status, amount, pay.method].filter(Boolean).join(" · ") || "—";
}

function parentsLabel(item: DeskApplication) {
  const p = item.parents_summary;
  if (!p) return "—";
  const parts = [
    p.father_name ? `پدر: ${p.father_name}${p.father_mobile ? ` (${p.father_mobile})` : ""}` : null,
    p.mother_name ? `مادر: ${p.mother_name}${p.mother_mobile ? ` (${p.mother_mobile})` : ""}` : null,
  ].filter(Boolean);
  return parts.length ? parts.join(" · ") : "—";
}

const GROUP_CHIPS: Array<{ id: "" | PreRegistrationGroup; label: string }> = [
  { id: "", label: "همه" },
  ...(Object.entries(PRE_REGISTRATION_BUCKETS) as Array<[PreRegistrationGroup, string]>).map(
    ([id, label]) => ({ id, label }),
  ),
];

export default function PreRegistrationAdmissionsPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const applicationIdParam = searchParams.get("application_id");
  const bucketParam = searchParams.get("bucket");
  const groupParam = searchParams.get("group");
  const statusParam = searchParams.get("status") ?? "";

  const branchId = getActiveBranchId();

  const [items, setItems] = useState<DeskApplication[]>([]);
  const [page, setPage] = useState(1);
  const [lastPage, setLastPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const activeGroup: "" | PreRegistrationGroup = isPreRegistrationGroup(groupParam)
    ? groupParam
    : "";

  const statusOptions = useMemo(() => {
    if (activeGroup) {
      return PRE_REGISTRATION_GROUP_STATUSES[activeGroup];
    }
    return Object.keys(STATUS_LABELS);
  }, [activeGroup]);

  const replaceFilters = useCallback(
    (next: { group?: string; status?: string }) => {
      const qs = new URLSearchParams();
      const group = next.group ?? activeGroup;
      const status = next.status ?? statusParam;
      if (group) qs.set("group", group);
      if (status) qs.set("status", status);
      const suffix = qs.toString() ? `?${qs.toString()}` : "";
      setPage(1);
      router.replace(`/pre-registration/admissions${suffix}`);
    },
    [activeGroup, router, statusParam],
  );

  // سازگاری عقب‌رو: ?bucket= → ?group=
  useEffect(() => {
    if (!bucketParam) return;
    if (groupParam) {
      const qs = new URLSearchParams(searchParams.toString());
      qs.delete("bucket");
      const suffix = qs.toString() ? `?${qs.toString()}` : "";
      router.replace(`/pre-registration/admissions${suffix}`);
      return;
    }
    if (isPreRegistrationGroup(bucketParam)) {
      const qs = new URLSearchParams();
      qs.set("group", bucketParam);
      if (statusParam) qs.set("status", statusParam);
      router.replace(`/pre-registration/admissions?${qs.toString()}`);
      return;
    }
    const qs = new URLSearchParams(searchParams.toString());
    qs.delete("bucket");
    const suffix = qs.toString() ? `?${qs.toString()}` : "";
    router.replace(`/pre-registration/admissions${suffix}`);
  }, [bucketParam, groupParam, router, searchParams, statusParam]);

  useEffect(() => {
    if (!applicationIdParam) return;
    const id = Number(applicationIdParam);
    if (!id) return;
    const qs = new URLSearchParams();
    if (activeGroup) qs.set("group", activeGroup);
    if (statusParam) qs.set("status", statusParam);
    const suffix = qs.toString() ? `?${qs.toString()}` : "";
    router.replace(`/pre-registration/admissions/${id}${suffix}`);
  }, [activeGroup, applicationIdParam, router, statusParam]);

  // اگر status انتخابی خارج از گروه فعلی است، پاکش کن
  useEffect(() => {
    if (!statusParam) return;
    if (!statusOptions.includes(statusParam)) {
      replaceFilters({ status: "" });
    }
  }, [replaceFilters, statusOptions, statusParam]);

  const loadDesk = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams();
      params.set("page", String(page));
      params.set("per_page", "20");
      if (statusParam) params.set("status", statusParam);
      if (activeGroup) params.set("group", activeGroup);
      if (branchId) {
        params.set("branch_id", String(branchId));
      }
      const query = params.toString();
      const result = await apiGet<Paginated<DeskApplication>>(
        `/admissions/desk${query ? `?${query}` : ""}`,
      );
      setItems(result.data);
      setLastPage(result.last_page);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در بارگذاری");
    } finally {
      setLoading(false);
    }
  }, [activeGroup, branchId, page, statusParam]);

  useEffect(() => {
    if (applicationIdParam || bucketParam) return;
    void loadDesk();
  }, [applicationIdParam, bucketParam, loadDesk]);

  const exportFilters = {
    status: statusParam || undefined,
    group: activeGroup || undefined,
    branch_id: branchId ?? undefined,
  };

  const detailHref = (id: number, mode?: "edit") => {
    const qs = new URLSearchParams();
    if (activeGroup) qs.set("group", activeGroup);
    if (statusParam) qs.set("status", statusParam);
    if (mode) qs.set("mode", mode);
    const suffix = qs.toString() ? `?${qs.toString()}` : "";
    return `/pre-registration/admissions/${id}${suffix}`;
  };

  if (applicationIdParam || bucketParam) {
    return (
      <AppShell title="میز پذیرش" subtitle="در حال هم‌تراز کردن آدرس…">
        <p className="text-sm text-[var(--muted)]">لطفاً صبر کنید…</p>
      </AppShell>
    );
  }

  return (
    <AppShell title="میز پذیرش" subtitle="بررسی درخواست‌های پیش‌ثبت‌نام">
      <div className="space-y-4">
        <div className="flex flex-wrap gap-2">
          <Link
            href="/pre-registration"
            className="rounded-xl bg-slate-100 px-3 py-2 text-xs font-semibold text-slate-700"
          >
            ← داشبورد پیش‌ثبت‌نام
          </Link>
        </div>

        <div className="flex flex-wrap gap-2">
          {GROUP_CHIPS.map((chip) => {
            const selected = activeGroup === chip.id;
            return (
              <button
                key={chip.id || "all"}
                type="button"
                onClick={() => replaceFilters({ group: chip.id, status: "" })}
                className={`rounded-full px-3 py-1.5 text-xs font-semibold transition ${
                  selected
                    ? "bg-primary text-white"
                    : "bg-white text-slate-700 ring-1 ring-[var(--border)] hover:bg-slate-50"
                }`}
              >
                {chip.label}
              </button>
            );
          })}
        </div>

        <div className="flex flex-wrap items-end justify-between gap-3">
          <div className="min-w-[220px]">
            <Field label="وضعیت دقیق">
              <Select
                value={statusParam}
                onChange={(e) => replaceFilters({ status: e.target.value })}
              >
                <option value="">همه وضعیت‌های این گروه</option>
                {statusOptions.map((value) => (
                  <option key={value} value={value}>
                    {STATUS_LABELS[value] ?? value}
                  </option>
                ))}
              </Select>
            </Field>
          </div>
          <ListExportActions
            exportPath="/admissions/desk/export"
            filters={exportFilters}
            contextKeys={["branch_id"]}
            filenameBase="admissions-desk-export"
            onError={setError}
          />
        </div>

        {error ? <Alert tone="error">{error}</Alert> : null}

        <DataTable
          loading={loading}
          columns={[
            { key: "student", label: "دانش‌آموز" },
            { key: "school", label: "مدرسه / پایه" },
            { key: "status", label: "وضعیت" },
            { key: "parents", label: "اولیا" },
            { key: "residence", label: "محل سکونت" },
            { key: "docs", label: "مدارک" },
            { key: "payment", label: "پرداخت" },
            { key: "eval", label: "ارزیابی" },
            { key: "submitted", label: "ارسال" },
            { key: "ops", label: "عملیات" },
          ]}
        >
          {items.length === 0 ? (
            <DataTableEmpty colSpan={10} message="درخواستی یافت نشد." />
          ) : (
            items.map((item) => (
              <tr key={item.id} className="hover:bg-slate-50">
                <td className="px-3 py-3">
                  <p className="font-medium">
                    {item.student_name
                      || `${String(item.form_data?.first_name ?? "")} ${String(item.form_data?.last_name ?? "")}`.trim()
                      || "—"}
                  </p>
                  <p className="mt-0.5 text-xs text-[var(--muted)]">
                    {item.applicant_national_code}
                    {" · "}
                    {genderLabel(item.gender)}
                    {item.birth_date ? ` · ${formatDate(item.birth_date)}` : ""}
                  </p>
                </td>
                <td className="px-3 py-3 text-xs">
                  <p>{item.branch?.name ?? "—"}</p>
                  <p className="mt-0.5 text-[var(--muted)]">{item.grade_level?.name ?? "—"}</p>
                </td>
                <td className="px-3 py-3 text-xs">
                  {STATUS_LABELS[item.status] ?? item.status}
                </td>
                <td className="max-w-[220px] px-3 py-3 text-xs leading-5 text-[var(--muted)]">
                  {parentsLabel(item)}
                </td>
                <td className="max-w-[180px] px-3 py-3 text-xs text-[var(--muted)]">
                  {item.residence_summary || "—"}
                </td>
                <td className="px-3 py-3 text-xs">
                  {item.documents_count != null ? `${item.documents_count} مدرک` : "—"}
                </td>
                <td className="px-3 py-3 text-xs text-[var(--muted)]">{paymentLabel(item)}</td>
                <td className="px-3 py-3 text-xs">
                  {item.document_review_status ?? "—"}
                </td>
                <td className="px-3 py-3 text-xs text-[var(--muted)]">
                  {formatDate(item.submitted_at)}
                </td>
                <td className="px-3 py-3">
                  <div className="flex flex-wrap gap-2">
                    <Link href={detailHref(item.id)}>
                      <Button variant="secondary" className="!px-3 !py-1.5 text-xs">
                        مشاهده
                      </Button>
                    </Link>
                    <Link href={detailHref(item.id, "edit")}>
                      <Button className="!px-3 !py-1.5 text-xs">ویرایش</Button>
                    </Link>
                  </div>
                </td>
              </tr>
            ))
          )}
        </DataTable>
        <Pagination page={page} lastPage={lastPage} onPageChange={setPage} />
      </div>
    </AppShell>
  );
}
