import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { staffApi } from "@/lib/api/staff";
import { getServerUser, requireServerToken } from "@/lib/auth/server";
import type { ApiStaff, StaffPermissionTemplate } from "@/lib/api/types";
import { deleteStaffMember } from "./actions";
import DeleteStaffButton from "./DeleteStaffButton";
import StaffEditForm from "./StaffEditForm";

type PageProps = {
  params: Promise<{ id: string }>;
};

function normalizePermission(raw: ApiStaff["permission"]): StaffPermissionTemplate {
  // Legacy V1 stored as `[{...}]`; V2 stores as object directly. Accept either.
  if (Array.isArray(raw)) {
    return (raw[0] as StaffPermissionTemplate) ?? {};
  }
  return (raw as StaffPermissionTemplate) ?? {};
}

/**
 * The two requests are independent, so they go out together — the effect this
 * replaces already used `Promise.all`, and there is no reason to lose that by
 * awaiting them in sequence.
 */
async function loadStaffEdit(token: string, id: number) {
  try {
    const [tpl, staff] = await Promise.all([
      staffApi.permissionTemplate(token),
      staffApi.show(token, id),
    ]);
    return { tpl, staff };
  } catch {
    return { tpl: null, staff: null };
  }
}

/**
 * Server-rendered. Both fetches happen during SSR, so the form arrives populated
 * instead of showing a `<Loader />` until the bundle hydrates and the effect
 * fires. The owner-only gate reads the cached user cookie rather than `useAuth`,
 * which removes the loading flash it used to render first.
 */
export default async function StaffEditPage({ params }: PageProps) {
  const { id } = await params;
  const staffId = Number(id);

  const user = await getServerUser();
  if (!user || user.is_staff) {
    return (
      <div className="rounded-xl bg-white p-10 text-center shadow-sm ring-1 ring-gray-100">
        <p className="text-sm text-gray-500">Staff management is owner-only.</p>
      </div>
    );
  }

  const token = await requireServerToken(`/staff/${id}`);
  const { tpl, staff } = await loadStaffEdit(token, staffId);

  // The client version sat on a spinner forever when either request failed;
  // on the server a missing record is simply a 404.
  if (!tpl || !staff) notFound();

  return (
    <div className="space-y-4">
      <Link href="/staff" className="inline-flex items-center gap-1 text-sm text-gray-600 hover:text-[#CC1414]">
        <ArrowLeft className="h-4 w-4" /> Back to staff
      </Link>

      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="text-2xl font-bold text-gray-900">Edit Staff</h1>
        <form action={deleteStaffMember}>
          <input type="hidden" name="id" value={staff.id} />
          <DeleteStaffButton name={staff.name} />
        </form>
      </div>

      <StaffEditForm
        id={staff.id}
        template={tpl.template}
        initial={{
          name: staff.name,
          email: staff.email ?? "",
          phone: staff.phone ?? "",
          role: staff.role ?? "",
          permission: normalizePermission(staff.permission),
        }}
      />
    </div>
  );
}
