// app/(app)/staff/salaries/page.tsx
import { cookies } from "next/headers";
import NextDynamic from "next/dynamic";
import { createSbServer } from "@/lib/supabaseServer";

export const dynamic = "force-dynamic";

const SalariesGrid = NextDynamic<any>(() => import("../../../../components/staff/SalariesGridSimple"), { ssr: false });

export default async function StaffSalariesPage() {
  const sb = createSbServer();
  const { data: { user } } = await sb.auth.getUser();

  if (!user) {
    return (
      <main className="p-6">
        <h1 className="text-lg font-semibold">Accès refusé</h1>
        <p className="text-sm text-slate-600">Vous devez être connecté.</p>
      </main>
    );
  }

  const { data: me } = await sb.from("staff_users").select("is_staff").eq("user_id", user.id).maybeSingle();
  const isStaff = !!me?.is_staff;
  if (!isStaff) {
    return (
      <main className="p-6">
        <h1 className="text-lg font-semibold">Accès refusé</h1>
        <p className="text-sm text-slate-600">Cette page est réservée au Staff.</p>
      </main>
    );
  }

  // Initial fetch: server-side list of latest salaries (limited)
  const { data: salaries, error } = await sb
    .from("salaries")
    .select(
      `id, code_salarie, num_salarie, salarie, nom, nom_de_naissance, prenom, civilite, pseudonyme,
       compte_transat, topaze, justificatifs_personnels, rf_au_sens_fiscal, intermittent_mineur_16,
       adresse_mail, nir, conges_spectacles, tel, adresse, date_naissance, lieu_de_naissance,
       iban, bic, abattement_2024, infos_caisses_organismes, notif_nouveau_salarie, notif_employeur,
       derniere_profession, employer_id, notes, last_notif_justifs, created_at, updated_at,
       organizations(name)`
    )
    .order("nom", { ascending: true })
    .limit(200);

  // Server-side debug logging to help diagnose empty results (will appear in Next.js server logs)
  try {
    console.log("[staff/salaries] supabase fetch salaries result count:", Array.isArray(salaries) ? salaries.length : typeof salaries);
    if (error) console.log("[staff/salaries] supabase error:", error);
    if (salaries && salaries.length > 0) console.log("[staff/salaries] sample:", salaries.slice(0, 5));
  } catch (e) {
    // ignore logging errors
  }

  if (error) {
    return (
      <main className="p-6">
        <h1 className="text-lg font-semibold">Erreur</h1>
        <p className="text-sm text-rose-600">{error.message}</p>
        <div className="mt-4 p-3 bg-slate-50 rounded text-sm text-slate-700">
          <div><strong>Debug</strong></div>
          <div>Supabase returned an error when reading <code>salaries</code>. See server logs for details.</div>
        </div>
      </main>
    );
  }

  // active org (optional) for staff we allow global view; keep cookie reading for parity
  const c = cookies();
  const activeOrgId = c.get("active_org_id")?.value || null;

  // Transform data to include organization name
  const transformedSalaries = (salaries || []).map((salarie: any) => ({
    ...salarie,
    organization_name: salarie.organizations?.name || null
  }));

  return (
    <main className="p-6">
      <div className="flex items-center justify-between mb-4">
        <h1 className="text-lg font-semibold">Salariés (Staff)</h1>
      </div>

      <div className="rounded-2xl border bg-white p-4">
        {(!salaries || salaries.length === 0) && (
          <div className="mb-4 p-3 rounded bg-yellow-50 text-sm text-slate-800 border">
            <div><strong>Debug:</strong> Aucun salarié trouvé côté serveur (initialData vide).</div>
            <div className="mt-2 text-xs text-slate-600">Si tu utilises Realtime / RLS, vérifie que la table <code>salaries</code> est publiée pour Realtime et que les policies autorisent la lecture pour ton utilisateur staff.</div>
            <details className="mt-2 text-xs">
              <summary className="cursor-pointer text-xs underline">Voir le payload serveur (preview)</summary>
              <pre className="mt-2 max-h-48 overflow-auto text-xs bg-slate-50 p-2 rounded border">{JSON.stringify(salaries ?? [], null, 2)}</pre>
            </details>
          </div>
        )}
        {/* Client-side interactive grid */}
        <SalariesGrid initialData={transformedSalaries} activeOrgId={activeOrgId} />
      </div>
    </main>
  );
}