"use client";

import { useState, useEffect, useMemo, useCallback, useRef } from "react";
import { useUrlFilters } from "~/hooks/useUrlFilters.js";
import { useLocalStorage } from "~/hooks/useLocalStorage.js";
import { formatDate } from "~/lib/format.js";
import { trpc } from "~/lib/trpc/client.js";
import { useInvalidatePlanningViews } from "~/hooks/useInvalidatePlanningViews.js";
import { AllocationModal } from "./AllocationModal.js";
import type {
  AllocationLike,
  AllocationReadModel,
  AllocationWithDetails,
  ColumnDef,
  AllocationStatus,
} from "@capakraken/shared";
import { ALLOCATION_COLUMNS } from "@capakraken/shared";
import { useSelection } from "~/hooks/useSelection.js";
import { FilterBar } from "~/components/ui/FilterBar.js";
import { FilterChips } from "~/components/ui/FilterChips.js";
import { ResourceCombobox } from "~/components/ui/ResourceCombobox.js";
import { ProjectCombobox } from "~/components/ui/ProjectCombobox.js";
import { ColumnTogglePanel } from "~/components/ui/ColumnTogglePanel.js";
import { SortableColumnHeader } from "~/components/ui/SortableColumnHeader.js";
import { useTableSort } from "~/hooks/useTableSort.js";
import { usePermissions } from "~/hooks/usePermissions.js";
import { useColumnConfig } from "~/hooks/useColumnConfig.js";
import { useViewPrefs } from "~/hooks/useViewPrefs.js";
import { getPlanningEntryMutationId } from "~/lib/planningEntryIds.js";
import { SuccessToast } from "~/components/ui/SuccessToast.js";
import { EmptyState } from "~/components/ui/EmptyState.js";
import { downloadWorkbookSheets } from "~/lib/workbook-export.js";
import {
  collapseAllAllocationGroups,
  createInitialCollapsedAllocationGroups,
  expandAllAllocationGroups,
  toggleCollapsedAllocationGroup,
  type CollapsedAllocationGroups,
} from "./allocationGroupState.js";
import {
  getAllocationEmptyState,
  shouldAutoRelaxAllocationFilters,
} from "./allocationVisibilityState.js";
import { AllocationRow } from "./AllocationRow.js";
import { AllocationGroupedBody, type AllocGroup } from "./AllocationGroupedBody.js";
import { OpenDemandsPanel } from "./OpenDemandsPanel.js";
import { AllocationBatchDialogs } from "./AllocationBatchDialogs.js";
import { ConfirmDialog } from "~/components/ui/ConfirmDialog.js";

const ALL_ALLOC_STATUSES = [
  { value: "PROPOSED", label: "Proposed" },
  { value: "CONFIRMED", label: "Confirmed" },
  { value: "ACTIVE", label: "Active" },
  { value: "COMPLETED", label: "Completed" },
  { value: "CANCELLED", label: "Cancelled" },
] as const;

type AllocationAssignmentsView = AllocationReadModel<AllocationLike>;
type DemandRow = AllocationWithDetails & {
  sourceAllocationId?: string;
  requestedHeadcount?: number;
  unfilledHeadcount?: number;
};

type AllocationQueryError = {
  data?: {
    code?: string;
  };
  message?: string;
} | null;

function getAllocationQueryFailure(error: AllocationQueryError) {
  const code = error?.data?.code;

  if (code === "FORBIDDEN") {
    return {
      testId: "allocations-access-error",
      title: "You do not have permission to view allocations.",
      detail: "Your account is missing planning read access for this page.",
      actionLabel: null,
      actionHref: null,
    };
  }

  if (code === "UNAUTHORIZED") {
    return {
      testId: "allocations-session-error",
      title: "Your session expired.",
      detail: "Sign in again to load allocations.",
      actionLabel: "Sign in again",
      actionHref: "/auth/signin",
    };
  }

  return {
    testId: "allocations-query-error",
    title: "Allocations could not be loaded.",
    detail: error?.message ?? "Refresh the page or try again in a moment.",
    actionLabel: null,
    actionHref: null,
  };
}

export function AllocationsClient() {
  const [modalOpen, setModalOpen] = useState(false);
  const [editingAllocation, setEditingAllocation] = useState<AllocationWithDetails | null>(null);

  const [allocFilters, setAllocFilters] = useUrlFilters({
    projectId: "",
    resourceId: "",
    status: "",
    hidePast: "true",
    hideCompleted: "true",
    hideDraft: "false",
  });

  const filterProjectId = allocFilters.projectId;
  const filterResourceId = allocFilters.resourceId;
  const filterStatus = allocFilters.status;
  const hidePastProjects = allocFilters.hidePast === "true";
  const hideCompletedProjects = allocFilters.hideCompleted === "true";
  const hideDraftProjects = allocFilters.hideDraft === "true";

  const setFilterProjectId = useCallback(
    (v: string) => setAllocFilters({ projectId: v }),
    [setAllocFilters],
  );
  const setFilterResourceId = useCallback(
    (v: string) => setAllocFilters({ resourceId: v }),
    [setAllocFilters],
  );
  const setFilterStatus = useCallback(
    (v: string) => setAllocFilters({ status: v }),
    [setAllocFilters],
  );
  const setHidePastProjects = useCallback(
    (v: boolean) => setAllocFilters({ hidePast: v ? "true" : "false" }),
    [setAllocFilters],
  );
  const setHideCompletedProjects = useCallback(
    (v: boolean) => setAllocFilters({ hideCompleted: v ? "true" : "false" }),
    [setAllocFilters],
  );
  const setHideDraftProjects = useCallback(
    (v: boolean) => setAllocFilters({ hideDraft: v ? "true" : "false" }),
    [setAllocFilters],
  );
  const [confirmDelete, setConfirmDelete] = useState<{
    single?: AllocationWithDetails;
    ids?: string[];
  } | null>(null);
  const [batchStatusPicker, setBatchStatusPicker] = useState(false);
  const [confirmBatchStatus, setConfirmBatchStatus] = useState<{
    ids: string[];
    status: string;
  } | null>(null);
  const [showStatusToast, setShowStatusToast] = useState(false);
  const [showDateShiftModal, setShowDateShiftModal] = useState(false);

  const selection = useSelection();
  const invalidatePlanningViews = useInvalidatePlanningViews();
  const { canViewCosts } = usePermissions();

  // ─── Column visibility ────────────────────────────────────────────────────
  const baseColumns = useMemo<ColumnDef[]>(
    () => (canViewCosts ? ALLOCATION_COLUMNS : ALLOCATION_COLUMNS.filter((c) => c.key !== "cost")),
    [canViewCosts],
  );
  const { allColumns, visibleColumns, visibleKeys, setVisible } = useColumnConfig(
    "allocations",
    baseColumns,
  );
  const defaultKeys = useMemo(
    () => baseColumns.filter((c) => c.defaultVisible).map((c) => c.key),
    [baseColumns],
  );

  const allocationQuery = trpc.allocation.listView.useQuery(
    {
      projectId: filterProjectId || undefined,
      resourceId: filterResourceId || undefined,
      status: (filterStatus as AllocationStatus) || undefined,
    },
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    { placeholderData: (prev: any) => prev, staleTime: 15_000 },
  ) as {
    data: AllocationAssignmentsView | undefined;
    isLoading: boolean;
    isError: boolean;
    error: AllocationQueryError;
  };
  const { data: allocationView, isLoading, isError, error } = allocationQuery;
  const allocationQueryFailure = isError ? getAllocationQueryFailure(error) : null;

  const deleteDemandMutation = trpc.allocation.deleteDemandRequirement.useMutation({
    onSuccess: () => invalidatePlanningViews(),
  });

  const deleteAssignmentMutation = trpc.allocation.deleteAssignment.useMutation({
    onSuccess: () => invalidatePlanningViews(),
  });

  const batchDeleteMutation = trpc.allocation.batchDelete.useMutation({
    onSuccess: async () => {
      await invalidatePlanningViews();
      selection.clear();
    },
  });

  const batchStatusMutation = trpc.allocation.batchUpdateStatus.useMutation({
    onSuccess: async () => {
      await invalidatePlanningViews();
      selection.clear();
      setShowStatusToast(true);
    },
  });

  const batchDateShiftMutation = trpc.timeline.batchShiftAllocations.useMutation({
    onSuccess: async () => {
      await invalidatePlanningViews();
      selection.clear();
      setShowDateShiftModal(false);
    },
  });

  useEffect(() => {
    selection.clear();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    filterProjectId,
    filterResourceId,
    filterStatus,
    hidePastProjects,
    hideCompletedProjects,
    hideDraftProjects,
  ]);

  function handleExportExcel() {
    const rows: (string | number | null)[][] = [
      ["Resource", "Project", "Role", "Start Date", "End Date", "Hours/Day", "Status"],
      ...sorted.map((a) => [
        (a.resource as { displayName?: string } | null | undefined)?.displayName ?? "Unassigned",
        (a.project as { shortCode?: string; name?: string } | null | undefined)
          ? `${(a.project as { shortCode: string }).shortCode} — ${(a.project as { name: string }).name}`
          : "",
        a.role ?? "",
        typeof a.startDate === "string"
          ? a.startDate
          : (a.startDate as Date).toISOString().slice(0, 10),
        typeof a.endDate === "string" ? a.endDate : (a.endDate as Date).toISOString().slice(0, 10),
        a.hoursPerDay,
        a.status,
      ]),
    ];
    void downloadWorkbookSheets("allocations.xlsx", [{ name: "Allocations", rows }]);
  }

  function openCreate() {
    setEditingAllocation(null);
    setModalOpen(true);
  }

  function openEdit(alloc: AllocationWithDetails) {
    setEditingAllocation(alloc);
    setModalOpen(true);
  }

  function closeModal() {
    setModalOpen(false);
    setEditingAllocation(null);
  }

  const assignmentList = (allocationView?.assignments ?? []) as unknown as AllocationWithDetails[];
  const demandList = (allocationView?.demands ?? []) as unknown as DemandRow[];

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const filteredAllocations = assignmentList.filter((alloc) => {
    if (hidePastProjects && alloc.project?.endDate && new Date(alloc.project.endDate) < today)
      return false;
    if (
      hideCompletedProjects &&
      alloc.project?.status &&
      ["COMPLETED", "CANCELLED"].includes(alloc.project.status)
    )
      return false;
    if (hideDraftProjects && alloc.project?.status === "DRAFT") return false;
    return true;
  });

  const filteredDemands = demandList.filter((alloc) => {
    if (filterResourceId) return false;
    if (hidePastProjects && alloc.project?.endDate && new Date(alloc.project.endDate) < today)
      return false;
    if (
      hideCompletedProjects &&
      alloc.project?.status &&
      ["COMPLETED", "CANCELLED"].includes(alloc.project.status)
    )
      return false;
    if (hideDraftProjects && alloc.project?.status === "DRAFT") return false;
    return true;
  });

  const allocViewPrefs = useViewPrefs("allocations");
  const { sorted, sortField, sortDir, toggle } = useTableSort(filteredAllocations, {
    initialField: allocViewPrefs.savedSort?.field ?? null,
    initialDir: allocViewPrefs.savedSort?.dir ?? null,
    onSortChange: (field, dir) => {
      allocViewPrefs.setSavedSort(field && dir ? { field, dir } : null);
    },
  });
  const allocationIds = sorted.map((a) => a.id);
  const allocationMutationIdsByDisplayId = useMemo(
    () =>
      new Map(sorted.map((allocation) => [allocation.id, getPlanningEntryMutationId(allocation)])),
    [sorted],
  );
  const selectedMutationIds = useMemo(
    () =>
      selection.selectedArray.flatMap((displayId) => {
        const mutationId = allocationMutationIdsByDisplayId.get(displayId);
        return mutationId ? [mutationId] : [];
      }),
    [allocationMutationIdsByDisplayId, selection.selectedArray],
  );

  // ─── View mode: grouped (default) vs flat ──────────────────────────────────
  const [viewMode, setViewMode] = useLocalStorage<"grouped" | "flat">(
    "capakraken:allocations:viewMode",
    "grouped",
  );
  const [collapsedGroups, setCollapsedGroups] = useState<CollapsedAllocationGroups>(() =>
    createInitialCollapsedAllocationGroups(),
  );
  const [expandedSubGroups, setExpandedSubGroups] = useState<Set<string>>(new Set());
  const hasEvaluatedInitialVisibility = useRef(false);

  const toggleViewMode = useCallback(() => {
    setViewMode((prev) => (prev === "grouped" ? "flat" : "grouped"));
  }, [setViewMode]);

  const groups = useMemo<AllocGroup[]>(() => {
    const map = new Map<string, AllocGroup>();
    for (const alloc of sorted) {
      const rid = alloc.resource?.id ?? "__unassigned__";
      let group = map.get(rid);
      if (!group) {
        group = {
          resourceId: rid,
          resourceName: alloc.resource?.displayName ?? "Unassigned",
          eid: alloc.resource?.eid ?? "",
          chapter: (alloc.resource as { chapter?: string | null } | undefined)?.chapter ?? null,
          allocations: [],
          projectSubGroups: [],
        };
        map.set(rid, group);
      }
      group.allocations.push(alloc);
    }

    for (const group of map.values()) {
      const projMap = new Map<string, AllocationWithDetails[]>();
      for (const alloc of group.allocations) {
        const pid = alloc.project?.id ?? "__no_project__";
        let list = projMap.get(pid);
        if (!list) {
          list = [];
          projMap.set(pid, list);
        }
        list.push(alloc);
      }
      group.projectSubGroups = [...projMap.entries()].map(([pid, allocs]) => {
        const first = allocs[0]!;
        let earliest = new Date(first.startDate);
        let latest = new Date(first.endDate);
        const hpdCounts = new Map<number, number>();
        for (const a of allocs) {
          const s = new Date(a.startDate);
          const e = new Date(a.endDate);
          if (s < earliest) earliest = s;
          if (e > latest) latest = e;
          hpdCounts.set(a.hoursPerDay, (hpdCounts.get(a.hoursPerDay) ?? 0) + 1);
        }
        let typicalH = first.hoursPerDay;
        let maxCount = 0;
        for (const [h, count] of hpdCounts) {
          if (count > maxCount) {
            typicalH = h;
            maxCount = count;
          }
        }
        return {
          projectId: pid,
          projectName: first.project?.name ?? "Unknown",
          projectCode: first.project?.shortCode ?? "",
          allocations: allocs,
          typicalHoursPerDay: typicalH,
          earliestStart: earliest,
          latestEnd: latest,
        };
      });
      group.projectSubGroups.sort((a, b) => a.projectName.localeCompare(b.projectName));
    }

    const arr = [...map.values()];
    arr.sort((a, b) => {
      if (a.resourceId === "__unassigned__") return 1;
      if (b.resourceId === "__unassigned__") return -1;
      return a.resourceName.localeCompare(b.resourceName);
    });
    return arr;
  }, [sorted]);

  const groupIds = useMemo(() => groups.map((g) => g.resourceId), [groups]);

  const toggleGroup = useCallback(
    (resourceId: string) => {
      setCollapsedGroups((prev) => toggleCollapsedAllocationGroup(prev, groupIds, resourceId));
    },
    [groupIds],
  );

  const collapseAll = useCallback(() => {
    setCollapsedGroups(collapseAllAllocationGroups());
  }, []);

  const expandAll = useCallback(() => {
    setCollapsedGroups(expandAllAllocationGroups());
  }, []);

  const toggleSubGroup = useCallback((resourceId: string, projectId: string) => {
    const key = `${resourceId}::${projectId}`;
    setExpandedSubGroups((prev) => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key);
      else next.add(key);
      return next;
    });
  }, []);

  function handleSort(field: string) {
    if (field === "resource") {
      toggle("resource", (a) => a.resource?.displayName ?? null);
    } else if (field === "project") {
      toggle("project", (a) => a.project?.name ?? null);
    } else {
      toggle(field);
    }
  }

  function clearAll() {
    setAllocFilters({
      projectId: "",
      resourceId: "",
      status: "",
      hidePast: "false",
      hideCompleted: "false",
      hideDraft: "false",
    });
  }

  const chips = [
    ...(filterProjectId
      ? [{ label: `Project filter active`, onRemove: () => setFilterProjectId("") }]
      : []),
    ...(filterResourceId
      ? [{ label: `Resource filter active`, onRemove: () => setFilterResourceId("") }]
      : []),
    ...(filterStatus
      ? [{ label: `Status: ${filterStatus}`, onRemove: () => setFilterStatus("") }]
      : []),
    ...(hidePastProjects
      ? [{ label: "Hiding past projects", onRemove: () => setHidePastProjects(false) }]
      : []),
    ...(hideCompletedProjects
      ? [{ label: "Hiding completed/cancelled", onRemove: () => setHideCompletedProjects(false) }]
      : []),
    ...(hideDraftProjects
      ? [{ label: "Hiding draft projects", onRemove: () => setHideDraftProjects(false) }]
      : []),
  ];

  const emptyState = getAllocationEmptyState({
    totalAssignments: assignmentList.length,
    totalDemands: demandList.length,
    visibleAssignments: filteredAllocations.length,
    visibleDemands: filteredDemands.length,
    hidePastProjects,
    hideCompletedProjects,
    hideDraftProjects,
  });

  useEffect(() => {
    if (isLoading || hasEvaluatedInitialVisibility.current) {
      return;
    }

    hasEvaluatedInitialVisibility.current = true;

    if (
      shouldAutoRelaxAllocationFilters({
        totalAssignments: assignmentList.length,
        totalDemands: demandList.length,
        visibleAssignments: filteredAllocations.length,
        visibleDemands: filteredDemands.length,
        hidePastProjects,
        hideCompletedProjects,
        hideDraftProjects,
      })
    ) {
      setAllocFilters({ hidePast: "false", hideCompleted: "false", hideDraft: "false" });
    }
  }, [
    assignmentList.length,
    demandList.length,
    filteredAllocations.length,
    filteredDemands.length,
    hideCompletedProjects,
    hideDraftProjects,
    hidePastProjects,
    isLoading,
  ]);

  function formatPeriod(alloc: AllocationWithDetails) {
    return formatDate(alloc.startDate) + " \u2192 " + formatDate(alloc.endDate);
  }

  function handleSingleDelete(allocation: AllocationWithDetails) {
    const id = getPlanningEntryMutationId(allocation);

    if (!allocation.resourceId) {
      deleteDemandMutation.mutate({ id });
      return;
    }

    deleteAssignmentMutation.mutate({ id });
  }

  const singleDeletePending = deleteDemandMutation.isPending || deleteAssignmentMutation.isPending;

  // colSpan for empty/loading states: checkbox + visible columns + actions
  const totalColSpan = 1 + visibleColumns.length + 1;

  return (
    <div className="app-page space-y-5 pb-24">
      <SuccessToast
        show={showStatusToast}
        message="Allocation status updated"
        onDone={() => setShowStatusToast(false)}
      />
      <div className="app-page-header gap-4">
        <div>
          <h1 className="app-page-title">Allocations</h1>
          <p className="app-page-subtitle mt-1">
            {isLoading
              ? "Loading…"
              : allocationQueryFailure
                ? allocationQueryFailure.title
                : `${filteredAllocations.length} assignment${filteredAllocations.length !== 1 ? "s" : ""}${filteredDemands.length > 0 ? ` · ${filteredDemands.length} open demand${filteredDemands.length !== 1 ? "s" : ""}` : ""}`}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <a
            href="/api/reports/allocations"
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-2 rounded-xl border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-700 transition hover:border-gray-400 hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-900 dark:text-gray-200 dark:hover:bg-gray-800"
          >
            ↓ PDF
          </a>
          <a
            href="/api/reports/allocations?format=xlsx"
            download
            className="inline-flex items-center gap-2 rounded-xl border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-700 transition hover:border-gray-400 hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-900 dark:text-gray-200 dark:hover:bg-gray-800"
          >
            ↓ XLS
          </a>
          <button
            type="button"
            onClick={openCreate}
            className="rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-brand-700 disabled:opacity-50"
          >
            New Planning Entry
          </button>
        </div>
      </div>

      <FilterBar>
        <ProjectCombobox
          value={filterProjectId || null}
          onChange={(id) => setFilterProjectId(id ?? "")}
          placeholder="Filter by project…"
          className="min-w-[280px]"
        />

        <ResourceCombobox
          value={filterResourceId || null}
          onChange={(id) => setFilterResourceId(id ?? "")}
          placeholder="Filter by resource…"
          className="min-w-[180px]"
        />

        <select
          value={filterStatus}
          onChange={(e) => setFilterStatus(e.target.value)}
          className="app-select"
        >
          <option value="">All Statuses</option>
          {ALL_ALLOC_STATUSES.map((s) => (
            <option key={s.value} value={s.value}>
              {s.label}
            </option>
          ))}
        </select>

        <label className="flex cursor-pointer items-center gap-1.5 whitespace-nowrap text-sm text-gray-600 dark:text-gray-300">
          <input
            type="checkbox"
            checked={hidePastProjects}
            onChange={(e) => setHidePastProjects(e.target.checked)}
            className="rounded border-gray-300 dark:border-gray-600"
          />
          Hide past
        </label>

        <label className="flex cursor-pointer items-center gap-1.5 whitespace-nowrap text-sm text-gray-600 dark:text-gray-300">
          <input
            type="checkbox"
            checked={hideCompletedProjects}
            onChange={(e) => setHideCompletedProjects(e.target.checked)}
            className="rounded border-gray-300 dark:border-gray-600"
          />
          Hide completed
        </label>

        <label className="flex cursor-pointer items-center gap-1.5 whitespace-nowrap text-sm text-gray-600 dark:text-gray-300">
          <input
            type="checkbox"
            checked={hideDraftProjects}
            onChange={(e) => setHideDraftProjects(e.target.checked)}
            className="rounded border-gray-300 dark:border-gray-600"
          />
          Hide drafts
        </label>
        <ColumnTogglePanel
          allColumns={allColumns}
          visibleKeys={visibleKeys}
          onSetVisible={setVisible}
          defaultKeys={defaultKeys}
        />

        {/* View mode toggle */}
        <div className="flex items-center rounded-lg border border-gray-300 dark:border-gray-600 overflow-hidden">
          <button
            type="button"
            onClick={toggleViewMode}
            title="Grouped by person"
            className={`px-2.5 py-2 text-sm transition-colors ${viewMode === "grouped" ? "bg-brand-600 text-white" : "bg-white text-gray-600 hover:bg-gray-50 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800"}`}
          >
            <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"
              />
            </svg>
          </button>
          <button
            type="button"
            onClick={toggleViewMode}
            title="Flat list"
            className={`px-2.5 py-2 text-sm transition-colors ${viewMode === "flat" ? "bg-brand-600 text-white" : "bg-white text-gray-600 hover:bg-gray-50 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800"}`}
          >
            <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M4 6h16M4 10h16M4 14h16M4 18h16"
              />
            </svg>
          </button>
        </div>

        {sorted.length > 0 && (
          <button
            type="button"
            onClick={handleExportExcel}
            title="Export visible rows to Excel"
            className="inline-flex items-center gap-1.5 rounded-lg border border-gray-300 dark:border-gray-600 px-2.5 py-2 text-sm font-medium text-gray-600 dark:text-gray-300 transition hover:border-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800"
          >
            <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
              />
            </svg>
            Export
          </button>
        )}

        {viewMode === "grouped" && groups.length > 1 && (
          <div className="flex items-center gap-1">
            <button
              type="button"
              onClick={expandAll}
              className="text-xs text-brand-600 hover:text-brand-800 dark:text-brand-400 dark:hover:text-brand-200 whitespace-nowrap"
            >
              Expand all
            </button>
            <span className="text-gray-300 dark:text-gray-600">|</span>
            <button
              type="button"
              onClick={collapseAll}
              className="text-xs text-brand-600 hover:text-brand-800 dark:text-brand-400 dark:hover:text-brand-200 whitespace-nowrap"
            >
              Collapse all
            </button>
          </div>
        )}
      </FilterBar>

      {/* Filter chips */}
      {chips.length > 0 && (
        <div className="mb-3">
          <FilterChips chips={chips} onClearAll={clearAll} />
        </div>
      )}

      <div className="app-data-table">
        <table data-testid="allocations-table" className="w-full">
          <thead className="border-b border-gray-200 dark:border-gray-700">
            <tr>
              <th className="px-4 py-3 w-10">
                <input
                  type="checkbox"
                  checked={selection.isAllSelected(allocationIds)}
                  ref={(el) => {
                    if (el) el.indeterminate = selection.isIndeterminate(allocationIds);
                  }}
                  onChange={() => selection.toggleAll(allocationIds)}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
              </th>
              {visibleColumns.map((col) => {
                const tooltips: Record<string, { tip: string; width?: string }> = {
                  resource: {
                    tip: "The person assigned to this time block. Grouped view clusters entries by resource.",
                  },
                  project: {
                    tip: "The project this allocation belongs to, identified by short code and name.",
                  },
                  role: {
                    tip: "The role this allocation was created for. May differ from the resource's primary role.",
                  },
                  dates: { tip: "Start and end date of this allocation period (inclusive)." },
                  hoursPerDay: {
                    tip: "Planned working hours per calendar day for this allocation.",
                  },
                  cost: {
                    tip: "Daily cost = resource LCR x hours per day. Total cost = daily cost x working days.",
                    width: "w-72",
                  },
                  status: {
                    tip: "PROPOSED = requested · CONFIRMED = approved · ACTIVE = ongoing · COMPLETED = finished · CANCELLED = removed.",
                    width: "w-72",
                  },
                };
                const t = tooltips[col.key];
                const fieldMap: Record<string, string> = {
                  dates: "startDate",
                  hoursPerDay: "hoursPerDay",
                  cost: "dailyCostCents",
                };
                return (
                  <SortableColumnHeader
                    key={col.key}
                    label={col.label}
                    field={fieldMap[col.key] ?? col.key}
                    sortField={sortField}
                    sortDir={sortDir}
                    onSort={handleSort}
                    {...(t?.tip ? { tooltip: t.tip } : {})}
                    {...(t?.width ? { tooltipWidth: t.width } : {})}
                  />
                );
              })}
              <th className="px-4 py-3" />
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
            {isLoading && (
              <tr>
                <td
                  colSpan={totalColSpan}
                  className="py-12 text-center text-sm text-gray-500 dark:text-gray-400"
                >
                  Loading allocations…
                </td>
              </tr>
            )}

            {!isLoading && allocationQueryFailure && (
              <tr>
                <td
                  colSpan={totalColSpan}
                  className="py-12 text-center text-sm text-gray-500 dark:text-gray-400"
                >
                  <div
                    data-testid={allocationQueryFailure.testId}
                    className="flex flex-col items-center gap-2"
                  >
                    <p className="font-medium text-gray-700 dark:text-gray-200">
                      {allocationQueryFailure.title}
                    </p>
                    <p>{allocationQueryFailure.detail}</p>
                    {allocationQueryFailure.actionLabel && allocationQueryFailure.actionHref && (
                      <a
                        href={allocationQueryFailure.actionHref}
                        className="rounded-lg border border-gray-300 px-3 py-1.5 text-xs font-medium text-gray-700 transition hover:border-gray-400 hover:bg-gray-50 dark:border-gray-600 dark:text-gray-200 dark:hover:bg-gray-800"
                      >
                        {allocationQueryFailure.actionLabel}
                      </a>
                    )}
                  </div>
                </td>
              </tr>
            )}

            {!isLoading && !allocationQueryFailure && sorted.length === 0 && (
              <tr>
                <td colSpan={totalColSpan}>
                  {emptyState.showResetAction ? (
                    <EmptyState
                      testId="allocations-empty-state"
                      title={emptyState.title}
                      detail={emptyState.detail}
                      action={{ label: "Show all assignments", onClick: clearAll }}
                    />
                  ) : (
                    <EmptyState
                      testId="allocations-empty-state"
                      title={emptyState.title}
                      detail={emptyState.detail}
                    />
                  )}
                </td>
              </tr>
            )}

            {!isLoading &&
              !allocationQueryFailure &&
              viewMode === "flat" &&
              sorted.map((alloc, index) => (
                <AllocationRow
                  key={alloc.id}
                  alloc={alloc}
                  visibleColumns={visibleColumns}
                  rowIndex={index}
                  isSelected={selection.selectedIds.has(alloc.id)}
                  onToggleSelection={() => selection.toggle(alloc.id)}
                  onEdit={() => openEdit(alloc)}
                  onRequestDelete={() => setConfirmDelete({ single: alloc })}
                  deleteDisabled={singleDeletePending}
                  formatPeriod={formatPeriod}
                />
              ))}

            {!isLoading && !allocationQueryFailure && viewMode === "grouped" && (
              <AllocationGroupedBody
                groups={groups}
                collapsedGroups={collapsedGroups}
                expandedSubGroups={expandedSubGroups}
                visibleColumns={visibleColumns}
                selectedIds={selection.selectedIds}
                isAllSelected={selection.isAllSelected}
                onToggleSelection={selection.toggle}
                onToggleAllSelection={selection.toggleAll}
                onToggleGroup={toggleGroup}
                onToggleSubGroup={toggleSubGroup}
                onEdit={openEdit}
                onRequestDelete={(alloc) => setConfirmDelete({ single: alloc })}
                deleteDisabled={singleDeletePending}
                formatPeriod={formatPeriod}
              />
            )}
          </tbody>
        </table>
      </div>

      {!isLoading && (
        <OpenDemandsPanel
          demands={filteredDemands}
          onEdit={openEdit}
          onRequestDelete={(alloc) => setConfirmDelete({ single: alloc })}
          deleteDisabled={singleDeletePending}
          formatPeriod={formatPeriod}
        />
      )}

      <AllocationBatchDialogs
        selectionCount={selection.count}
        selectedMutationIds={selectedMutationIds}
        onClearSelection={selection.clear}
        batchStatusPickerOpen={batchStatusPicker}
        onOpenBatchStatusPicker={() => setBatchStatusPicker(true)}
        onCloseBatchStatusPicker={() => setBatchStatusPicker(false)}
        batchStatusPending={batchStatusMutation.isPending}
        onBatchStatusConfirm={(ids, status) => {
          setConfirmBatchStatus({ ids, status });
        }}
        confirmDelete={confirmDelete}
        onSetConfirmDelete={setConfirmDelete}
        onSingleDelete={handleSingleDelete}
        onBatchDelete={(ids) => batchDeleteMutation.mutate({ ids })}
        batchDeletePending={batchDeleteMutation.isPending}
        showDateShiftModal={showDateShiftModal}
        onOpenDateShiftModal={() => setShowDateShiftModal(true)}
        onCloseDateShiftModal={() => setShowDateShiftModal(false)}
        onDateShiftConfirm={(daysDelta) =>
          batchDateShiftMutation.mutate({
            allocationIds: selectedMutationIds,
            daysDelta,
            mode: "move",
          })
        }
        dateShiftPending={batchDateShiftMutation.isPending}
      />

      {/* Confirm batch status */}
      {confirmBatchStatus && (
        <ConfirmDialog
          title="Update Allocation Status"
          message={`Set ${confirmBatchStatus.ids.length} allocation${confirmBatchStatus.ids.length !== 1 ? "s" : ""} to "${confirmBatchStatus.status}"?`}
          confirmLabel="Update"
          onConfirm={() => {
            batchStatusMutation.mutate({
              ids: confirmBatchStatus.ids,
              status: confirmBatchStatus.status as never,
            });
            setConfirmBatchStatus(null);
          }}
          onCancel={() => setConfirmBatchStatus(null)}
        />
      )}

      {/* Modal */}
      {modalOpen && (
        <AllocationModal
          allocation={editingAllocation}
          onClose={closeModal}
          onSuccess={closeModal}
        />
      )}
    </div>
  );
}
