import Link from "next/link";
import { Plus, Pencil } from "lucide-react";
import { staffApi } from "@/lib/api/staff";
import { getServerUser, requireServerToken } from "@/lib/auth/server";
import type { ApiStaff, PaginationMeta } from "@/lib/api/types";
import { deleteStaff } from "./actions";
import DeleteStaffButton from "./DeleteStaffButton";

type PageProps = {
  searchParams: Promise<{ page?: string; search?: string }>;
};

async function loadStaff(token: string, page: number, search?: string) {
  try {
    return await staffApi.list(token, { page, search });
  } catch {
    return { data: [] as ApiStaff[], meta: undefined as PaginationMeta | undefined };
  }
}

/**
 * Server-rendered. The owner-only gate now reads the cached user cookie instead
 * of `useAuth`, which means the "owner-only" card is in the first HTML response
 * rather than appearing after a hydration flash of `<Loader />`. It is still a
 * hint — the API is what actually refuses a staff account's request.
 *
 * Search and page moved from `useState` into the URL: that is what lets the
 * fetch happen here at all, and it makes a filtered list shareable.
 */
export default async function StaffListPage({ searchParams }: PageProps) {
  const user = await getServerUser();
  if (!user) return null;

  if (user.is_staff) {
    return (
      <div className="rounded-xl bg-white p-10 text-center shadow-sm ring-1 ring-gray-100">
        <h1 className="text-lg font-semibold text-gray-900">Staff management is owner-only</h1>
        <p className="mt-2 text-sm text-gray-500">Please ask your account owner to manage staff.</p>
      </div>
    );
  }

  const token = await requireServerToken("/staff");
  const sp = await searchParams;

  const page = Math.max(1, Number(sp.page) || 1);
  const search = sp.search?.trim() || "";

  const { data: list, meta } = await loadStaff(token, page, search || undefined);

  const query = (p: number) =>
    search ? `/staff?search=${encodeURIComponent(search)}&page=${p}` : `/staff?page=${p}`;

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="text-2xl font-bold text-gray-900">Staff</h1>
        <Link
          href="/staff/new"
          className="inline-flex items-center gap-2 rounded-lg bg-[#CC1414] px-4 py-2 text-sm font-medium text-white hover:bg-[#a30f0f]"
        >
          <Plus className="h-4 w-4" /> New staff
        </Link>
      </div>

      {/* A plain GET form: submitting puts `search` in the URL, which both
          resets paging and re-runs the fetch above — no client JS involved. */}
      <form action="/staff" method="get" className="flex gap-2">
        <input
          name="search"
          defaultValue={search}
          placeholder="Search by name, email, phone, role"
          className="w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm focus:border-[#CC1414] focus:outline-none"
        />
        <button
          type="submit"
          className="rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
        >
          Search
        </button>
      </form>

      {list.length === 0 ? (
        <div className="rounded-xl bg-white p-10 text-center text-gray-500 shadow-sm ring-1 ring-gray-100">
          No staff members yet. Click <span className="font-medium">New staff</span> to add one.
        </div>
      ) : (
        <div className="overflow-x-auto rounded-xl bg-white shadow-sm ring-1 ring-gray-100">
          <table className="w-full min-w-[640px] divide-y divide-gray-100 text-sm">
            <thead className="bg-gray-50 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
              <tr>
                <th className="px-4 py-3">Name</th>
                <th className="px-4 py-3">Email</th>
                <th className="px-4 py-3">Phone</th>
                <th className="px-4 py-3">Role</th>
                <th className="px-4 py-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {list.map((s) => (
                <tr key={s.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3 font-medium text-gray-900">{s.name}</td>
                  <td className="px-4 py-3 text-gray-700">{s.email ?? "—"}</td>
                  <td className="px-4 py-3 text-gray-700">{s.phone ?? "—"}</td>
                  <td className="px-4 py-3 text-gray-700">{s.role ?? "—"}</td>
                  <td className="px-4 py-3 text-right">
                    <div className="inline-flex gap-2">
                      <Link
                        href={`/staff/${s.id}`}
                        className="inline-flex items-center gap-1 rounded-md border border-gray-200 px-3 py-2 text-xs font-medium text-gray-700 hover:bg-gray-50"
                      >
                        <Pencil className="h-3.5 w-3.5" /> Edit
                      </Link>
                      <form action={deleteStaff}>
                        <input type="hidden" name="id" value={s.id} />
                        <DeleteStaffButton name={s.name} />
                      </form>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {meta && meta.last_page > 1 && (
        <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl bg-white px-4 py-3 shadow-sm ring-1 ring-gray-100">
          <span className="min-w-0 truncate text-sm text-gray-500">Page {meta.current_page} of {meta.last_page} · {meta.total} total</span>
          {/* Plain links: no client JS needed for paging. */}
          <div className="flex gap-2">
            {page > 1 ? (
              <Link href={query(page - 1)} className="rounded-md border px-4 py-2 text-sm hover:bg-gray-50">
                Prev
              </Link>
            ) : (
              <span className="rounded-md border px-4 py-2 text-sm opacity-50">Prev</span>
            )}
            {page < meta.last_page ? (
              <Link href={query(page + 1)} className="rounded-md border px-4 py-2 text-sm hover:bg-gray-50">
                Next
              </Link>
            ) : (
              <span className="rounded-md border px-4 py-2 text-sm opacity-50">Next</span>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
