"use client";

import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { AppShell } from "@/components/app/AppShell";
import { AdvancedSearchToggle } from "@/components/layout/AdvancedSearchToggle";
import { PageHeader } from "@/components/layout/PageHeader";
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, Input, Select } from "@/components/ui/Field";
import { ApiError, Paginated, apiDelete, apiGet, apiPut } from "@/lib/api";
import type { BuildingSummary } from "@/lib/buildings";
import { IRAN_PROVINCES } from "@/lib/iran-geo";
import { getActiveBranchId } from "@/lib/session-context";

const emptyFilters = {
  q: "",
  name: "",
  code: "",
  province: "",
  city: "",
  school: "",
  postal_code: "",
  is_active: "",
};

export default function BuildingsPage() {
  const router = useRouter();
  const [rows, setRows] = useState<BuildingSummary[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [lastPage, setLastPage] = useState(1);
  const [showSearch, setShowSearch] = useState(true);
  const [filters, setFilters] = useState(emptyFilters);
  const [applied, setApplied] = useState(emptyFilters);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [refresh, setRefresh] = useState(0);
  const [primaryBusy, setPrimaryBusy] = useState<number | null>(null);
  const branchId = getActiveBranchId();

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({ page: String(page) });
      if (applied.q) params.set("q", applied.q);
      if (applied.name) params.set("name", applied.name);
      if (applied.code) params.set("code", applied.code);
      if (applied.province) params.set("province", applied.province);
      if (applied.city) params.set("city", applied.city);
      if (applied.school) params.set("school", applied.school);
      if (applied.postal_code) params.set("postal_code", applied.postal_code);
      if (applied.is_active) params.set("is_active", applied.is_active);

      const result = await apiGet<Paginated<BuildingSummary>>(`/buildings?${params}`);
      setRows(result.data);
      setTotal(result.total);
      setLastPage(result.last_page);
      setError(null);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در بارگذاری ساختمان‌ها");
    } finally {
      setLoading(false);
    }
  }, [applied, page, refresh]);

  useEffect(() => {
    load();
  }, [load]);

  const patchFilter = (partial: Partial<typeof emptyFilters>) =>
    setFilters((prev) => ({ ...prev, ...partial }));

  const search = () => {
    setPage(1);
    setApplied(filters);
    setRefresh((n) => n + 1);
  };

  const clearFilters = () => {
    setFilters(emptyFilters);
    setApplied(emptyFilters);
    setPage(1);
  };

  const deactivate = async (id: number) => {
    if (!confirm("ساختمان غیرفعال شود؟")) return;
    try {
      await apiDelete(`/buildings/${id}`);
      setRefresh((n) => n + 1);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    }
  };

  const markPrimary = async (id: number) => {
    if (!branchId) return;
    setPrimaryBusy(id);
    try {
      await apiPut(`/branches/${branchId}/buildings/primary`, { building_id: id });
      setRefresh((n) => n + 1);
      setError(null);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "ثبت ساختمان مرکزی ناموفق بود.");
    } finally {
      setPrimaryBusy(null);
    }
  };

  const isPrimaryForBranch = (row: BuildingSummary) =>
    Boolean(branchId && row.branches?.some((b) => b.id === branchId && b.is_primary));

  return (
    <AppShell title="ساختمان‌ها" subtitle="مدیریت ساختمان‌ها، فضاها و ساختمان مرکزی شعبه">
      {error ? <Alert tone="error">{error}</Alert> : null}

      <div className="mb-4 rounded-2xl border border-[var(--border)] bg-white shadow-card">
        <AdvancedSearchToggle open={showSearch} onToggle={() => setShowSearch(!showSearch)} />
        {showSearch ? (
          <div className="grid gap-3 border-t border-[var(--border)] p-4 sm:grid-cols-2 lg:grid-cols-4">
            <Field label="جستجوی کلی">
              <Input
                value={filters.q}
                placeholder="نام، کد، شهر، آدرس یا مدرسه"
                onChange={(e) => patchFilter({ q: e.target.value })}
                onKeyDown={(e) => {
                  if (e.key === "Enter") search();
                }}
              />
            </Field>
            <Field label="نام ساختمان">
              <Input value={filters.name} onChange={(e) => patchFilter({ name: e.target.value })} />
            </Field>
            <Field label="کد">
              <Input value={filters.code} onChange={(e) => patchFilter({ code: e.target.value })} />
            </Field>
            <Field label="مدرسه / شعبه">
              <Input
                value={filters.school}
                placeholder="نام یا کد مدرسه"
                onChange={(e) => patchFilter({ school: e.target.value })}
              />
            </Field>
            <Field label="استان">
              <Select
                value={filters.province}
                onChange={(e) => patchFilter({ province: e.target.value, city: "" })}
              >
                <option value="">همه</option>
                {IRAN_PROVINCES.map((p) => (
                  <option key={p.id} value={p.name}>
                    {p.name}
                  </option>
                ))}
              </Select>
            </Field>
            <Field label="شهر">
              <Input value={filters.city} onChange={(e) => patchFilter({ city: e.target.value })} />
            </Field>
            <Field label="کد پستی">
              <Input value={filters.postal_code} onChange={(e) => patchFilter({ postal_code: e.target.value })} />
            </Field>
            <Field label="وضعیت">
              <Select value={filters.is_active} onChange={(e) => patchFilter({ is_active: e.target.value })}>
                <option value="">همه</option>
                <option value="1">فعال</option>
                <option value="0">غیرفعال</option>
              </Select>
            </Field>
            <div className="flex flex-wrap items-end gap-2 sm:col-span-2 lg:col-span-4">
              <Button onClick={search}>جستجو</Button>
              <Button variant="secondary" onClick={clearFilters}>
                پاک کردن فیلترها
              </Button>
            </div>
          </div>
        ) : null}
      </div>

      <PageHeader
        title="ساختمان‌ها"
        actions={
          <>
            <span className="rounded-full bg-blue-100 px-3 py-1 text-xs font-semibold text-blue-800">
              تعداد: {total}
            </span>
            <Button onClick={() => router.push("/buildings/new")}>+ ساختمان جدید</Button>
          </>
        }
      />
      <DataTable
        loading={loading}
        columns={[
          { key: "code", label: "کد" },
          { key: "name", label: "نام" },
          { key: "city", label: "شهر" },
          { key: "schools", label: "مدارس" },
          { key: "spaces", label: "بخش‌ها" },
          { key: "status", label: "وضعیت" },
          { key: "actions", label: "" },
        ]}
        emptyMessage="ساختمانی ثبت نشده است."
      >
        {rows.length === 0 ? (
          <DataTableEmpty colSpan={7} />
        ) : (
          rows.map((row) => (
            <tr key={row.id} className="hover:bg-slate-50">
              <td className="px-3 py-2 font-mono text-xs">{row.code}</td>
              <td className="px-3 py-2 font-medium">{row.name}</td>
              <td className="px-3 py-2">
                {[row.province, row.city].filter(Boolean).join("، ") || "—"}
              </td>
              <td className="px-3 py-2 text-xs">
                {row.branches && row.branches.length > 0
                  ? row.branches.map((b) => `${b.is_primary ? "★ " : ""}${b.name}`).join("، ")
                  : "—"}
              </td>
              <td className="px-3 py-2">{row.spaces_count ?? 0}</td>
              <td className="px-3 py-2">{row.is_active ? "فعال" : "غیرفعال"}</td>
              <td className="px-3 py-2">
                <div className="flex flex-wrap gap-2">
                  <Button variant="ghost" onClick={() => router.push(`/buildings/${row.id}`)}>
                    ویرایش
                  </Button>
                  {branchId && row.is_active ? (
                    isPrimaryForBranch(row) ? (
                      <span className="self-center text-xs font-semibold text-teal-700">مرکزی شعبه *</span>
                    ) : (
                      <Button
                        variant="ghost"
                        disabled={primaryBusy === row.id}
                        onClick={() => markPrimary(row.id)}
                      >
                        انتخاب به‌عنوان مرکزی *
                      </Button>
                    )
                  ) : null}
                  {row.is_active ? (
                    <Button variant="ghost" onClick={() => deactivate(row.id)}>
                      غیرفعال
                    </Button>
                  ) : null}
                </div>
              </td>
            </tr>
          ))
        )}
      </DataTable>
      <Pagination page={page} lastPage={lastPage} onPageChange={setPage} />
    </AppShell>
  );
}
