"use client";

import { Badge, Tooltip } from "@mantine/core";
import { useCallback, useEffect, useState } from "react";
import { listWorkflowTasksByEntityType } from "@/lib/features/workflow/query";
import {
  WORKFLOW_STATE_COLOR,
  WORKFLOW_STATE_LABEL,
  type WorkflowEntityType,
  type WorkflowStatus,
} from "@/lib/features/workflow/types";

/**
 * Approval state of one record, for list and grid views.
 *
 * Renders nothing when there is no task. A record with no workflow has not been
 * put through approval at all, which is different from being in its first
 * state, and showing "Draft" for both would hide that distinction.
 */
export function WorkflowStatusBadge({
  status,
  size = "sm",
}: {
  status?: WorkflowStatus | null;
  size?: string;
}) {
  if (!status) return null;
  return (
    <Tooltip label="Approval status">
      <Badge
        size={size}
        variant="light"
        color={WORKFLOW_STATE_COLOR[status] ?? "gray"}
      >
        {WORKFLOW_STATE_LABEL[status] ?? status}
      </Badge>
    </Tooltip>
  );
}

/**
 * Same information as the badge, for rows too narrow to hold a word.
 *
 * The tooltip carries the label, so the colour is a hint rather than the only
 * way to read it — a coloured dot alone is not something everyone can tell
 * apart.
 */
export function WorkflowStatusDot({ status }: { status?: WorkflowStatus | null }) {
  if (!status) return null;
  return (
    <Tooltip label={`Approval: ${WORKFLOW_STATE_LABEL[status] ?? status}`}>
      <div
        style={{
          width: 7,
          height: 7,
          borderRadius: "50%",
          flexShrink: 0,
          backgroundColor: `var(--mantine-color-${WORKFLOW_STATE_COLOR[status] ?? "gray"}-6)`,
        }}
      />
    </Tooltip>
  );
}

/**
 * Approval state of every record of one type, keyed by entity id.
 *
 * One request covers a whole listing. `refresh` is exposed because the sidebar
 * changes state outside this hook's knowledge — after a transition the caller
 * has to ask again or the badge keeps showing the old state.
 */
export function useWorkflowStatuses(
  entityType: WorkflowEntityType,
  /** Bump to refetch — for callers whose own refresh signal lives elsewhere. */
  refreshToken?: number,
) {
  const [statuses, setStatuses] = useState<Record<string, WorkflowStatus>>({});

  const refresh = useCallback(async () => {
    const res = await listWorkflowTasksByEntityType(entityType);
    if (!res.success || !Array.isArray(res.data)) return;
    const next: Record<string, WorkflowStatus> = {};
    for (const task of res.data) {
      if (task.entity_id && task.status) next[task.entity_id] = task.status;
    }
    setStatuses(next);
    // refreshToken is not read in the body — it is here so a bump refetches.
  }, [entityType, refreshToken]);

  useEffect(() => {
    void refresh();
  }, [refresh]);

  return { statuses, refresh };
}
