'use client';

import {Card} from '@astryxdesign/core/Card';
import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';

interface TooltipEntry {
  name?: string;
  value?: number | string;
  color?: string;
  dataKey?: string | number;
}

/**
 * recharts' default tooltip is a bare div with inline styles that ignore the
 * theme. This renders the same data through Astryx surfaces so the tooltip
 * matches every other popover in the app.
 */
export function ChartTooltip({
  active,
  payload,
  label,
  labelFormat,
  valueFormat,
}: {
  active?: boolean;
  payload?: TooltipEntry[];
  label?: string | number;
  labelFormat?: (v: string | number) => string;
  valueFormat?: (v: number) => string;
}) {
  if (!active || !payload?.length) return null;

  return (
    <Card elevation="high" padding={3}>
      <VStack gap={1.5}>
        <Text size="sm" color="secondary">
          {labelFormat && label !== undefined ? labelFormat(label) : label}
        </Text>
        <VStack gap={1}>
          {payload.map((entry) => (
            <HStack
              key={String(entry.dataKey)}
              gap={3}
              vAlign="center"
              hAlign="between"
            >
              <HStack gap={1.5} vAlign="center">
                {/* Swatch mirrors the series' assigned gray so the tooltip
                    row is traceable back to the mark it describes. */}
                <span
                  aria-hidden
                  style={{
                    width: 8,
                    height: 8,
                    borderRadius: 2,
                    background: entry.color,
                    flex: 'none',
                  }}
                />
                <Text size="sm">{entry.name}</Text>
              </HStack>
              <Text size="sm" weight="medium">
                {typeof entry.value === 'number' && valueFormat
                  ? valueFormat(entry.value)
                  : entry.value}
              </Text>
            </HStack>
          ))}
        </VStack>
      </VStack>
    </Card>
  );
}
