import type { ReactNode } from 'react';
import { Group, Paper, Text, ThemeIcon, UnstyledButton } from '@mantine/core';
import type { Icon } from '@tabler/icons-react';
import { STATUS_TONE_COLOR, type StatusTone } from '@ema-platform/shared';
import './stat-tile.css';

export interface StatTileProps {
  label: string;
  /** The number itself. A string so callers can pass "—" while loading. */
  value: ReactNode;
  /** One line under the value: what the number means, or how it is trending. */
  hint?: ReactNode;
  icon?: Icon;
  /**
   * Which tone the icon carries. Tone rather than colour so a tile counting
   * overdue work is the same red as an overdue badge.
   */
  tone?: StatusTone;
  /** Makes the whole tile a button — use when the number has somewhere to go. */
  onClick?: () => void;
}

/**
 * One figure on a dashboard.
 *
 * The four stat cards on the backoffice home were `<Card>` + two `<Text>`,
 * re-declared inline on every dashboard that wanted them — so the logistics
 * overview and the backoffice home showed the same kind of number at different
 * sizes. The number leads, the label sits above it small and quiet, and the
 * icon is decoration that carries the tone.
 *
 * A tile with `onClick` becomes a real button: dashboards exist to be a
 * jumping-off point, and a count you cannot click is a dead end.
 */
export function StatTile({ label, value, hint, icon: TileIcon, tone, onClick }: StatTileProps) {
  const body = (
    <>
      <Group justify="space-between" align="flex-start" wrap="nowrap">
        <Text size="xs" c="dimmed" tt="uppercase" fw={700} lh={1.4}>
          {label}
        </Text>
        {TileIcon && (
          <ThemeIcon
            size={38}
            radius="md"
            variant="light"
            color={tone ? STATUS_TONE_COLOR[tone] : undefined}
          >
            <TileIcon size={20} stroke={1.7} />
          </ThemeIcon>
        )}
      </Group>
      <Text fz={30} fw={800} lh={1.15} mt="xs">
        {value}
      </Text>
      {hint && (
        <Text size="xs" c="dimmed" mt={2}>
          {hint}
        </Text>
      )}
    </>
  );

  if (!onClick) {
    return (
      <Paper withBorder radius="lg" p="lg">
        {body}
      </Paper>
    );
  }

  return (
    <UnstyledButton
      onClick={onClick}
      className="ema-stat-tile-clickable"
      style={{ display: 'block', width: '100%', height: '100%' }}
    >
      <Paper withBorder radius="lg" p="lg" h="100%">
        {body}
      </Paper>
    </UnstyledButton>
  );
}
