"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { staffApi, type StaffPayload } from "@/lib/api/staff";
import { useToken } from "@/lib/auth/useToken";
import { useAuth } from "@/lib/auth/AuthContext";
import type { ApiPermissionTemplate } from "@/lib/api/types";
import { ApiException } from "@/lib/api/client";
import StaffForm from "@/components/staff/StaffForm";
import Loader from "@/components/ui/Loader";
import { ArrowLeft } from "lucide-react";

function Inner() {
  const router = useRouter();
  const { token, ready } = useToken();
  const [tpl, setTpl] = useState<ApiPermissionTemplate | null>(null);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    if (!ready || !token) return;
    staffApi.permissionTemplate(token).then(setTpl).catch((e) => setErr(e.message));
  }, [ready, token]);

  const submit = async (payload: StaffPayload) => {
    if (!token) return;
    setBusy(true);
    setErr(null);
    try {
      const r = await staffApi.create(token, payload);
      router.push(`/staff/${r.data.id}`);
    } catch (e) {
      setErr(e instanceof ApiException ? e.message : "Failed to create staff");
    } finally {
      setBusy(false);
    }
  };

  if (!tpl) {
    return (
      <div className="rounded-xl bg-white p-10 shadow-sm ring-1 ring-gray-100">
        <Loader label="Loading…" />
      </div>
    );
  }

  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>
      <h1 className="text-2xl font-bold text-gray-900">New Staff</h1>
      {err && <div className="rounded-lg bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200">{err}</div>}
      <StaffForm template={tpl.template} submitLabel="Create staff" onSubmit={submit} busy={busy} />
    </div>
  );
}

export default function NewStaffPage() {
  const { user, loading } = useAuth();
  if (loading) return <Loader label="Loading…" />;
  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>
    );
  }
  return <Inner />;
}
