import { PositionsPageClient } from "@/components/positions/PositionsPageClient";
import { daysBetween } from "@/lib/format";
import { loadOpenPositions } from "@/lib/positions";
import { createClient } from "@/lib/supabase/server";

export default async function PositionsPage() {
  const supabase = await createClient();

  const [openPositions, { data: divisions }, { data: departments }, { data: teams }, { data: activeEmployees }, { data: leads }] =
    await Promise.all([
      loadOpenPositions(supabase),
      supabase.from("divisions").select("*").order("name"),
      supabase.from("departments").select("*"),
      supabase.from("teams").select("*"),
      supabase.from("employees_directory").select("team_id, division_id, weekly_hours").in("status", ["Aktiv", "Karenz"]),
      supabase
        .from("employees_directory")
        .select("id, first_name, last_name, team_id, division_id, org_level, is_lead")
        .eq("status", "Aktiv")
        .or("is_lead.eq.true,org_level.eq.0"),
    ]);

  const teamStats = new Map<string, { headcount: number; fte: number }>();
  const divisionHeadcount = new Map<string, number>();
  for (const e of activeEmployees ?? []) {
    if (e.team_id) {
      const s = teamStats.get(e.team_id) ?? { headcount: 0, fte: 0 };
      s.headcount += 1;
      s.fte += Number(e.weekly_hours) / 38.5;
      teamStats.set(e.team_id, s);
    }
    if (e.division_id) {
      divisionHeadcount.set(e.division_id, (divisionHeadcount.get(e.division_id) ?? 0) + 1);
    }
  }

  const divisionHeadByDivision = new Map<string, { id: string; name: string }>();
  const teamLeadByTeam = new Map<string, { id: string; name: string }>();
  for (const p of leads ?? []) {
    const name = `${p.first_name} ${p.last_name}`;
    if (p.org_level === 1 && p.division_id) divisionHeadByDivision.set(p.division_id, { id: p.id, name });
    if (p.is_lead && p.team_id) teamLeadByTeam.set(p.team_id, { id: p.id, name });
  }

  const openPositionCountByTeam = new Map<string, number>();
  for (const pos of openPositions) {
    openPositionCountByTeam.set(pos.team_id, (openPositionCountByTeam.get(pos.team_id) ?? 0) + 1);
  }

  const divisionCards = (divisions ?? []).map((div) => ({
    ...div,
    head: divisionHeadByDivision.get(div.id) ?? null,
    headcount: divisionHeadcount.get(div.id) ?? 0,
    departments: (departments ?? [])
      .filter((d) => d.division_id === div.id)
      .map((dept) => ({
        ...dept,
        teams: (teams ?? [])
          .filter((t) => t.department_id === dept.id)
          .map((t) => ({
            ...t,
            lead: teamLeadByTeam.get(t.id) ?? null,
            headcount: teamStats.get(t.id)?.headcount ?? 0,
            fte: teamStats.get(t.id)?.fte ?? 0,
            openCount: openPositionCountByTeam.get(t.id) ?? 0,
          })),
      })),
  }));

  const openPositionsWithDays = openPositions.map((p) => ({ ...p, daysOpen: daysBetween(p.created_at) }));

  return <PositionsPageClient openPositions={openPositionsWithDays} divisionCards={divisionCards} teams={teams ?? []} />;
}
