import { ActionIcon, Group, SegmentedControl, Text } from "@mantine/core";
import { RefreshCw } from "lucide-react";

import type { OverviewRange } from "@/types/overview";

const RANGE_OPTIONS = [
  { label: "7 days", value: "7d" },
  { label: "30 days", value: "30d" },
  { label: "90 days", value: "90d" },
];

function formatRelativeTime(iso: string | undefined) {
  if (!iso) return "—";
  const diffMs = Date.now() - new Date(iso).getTime();
  const minutes = Math.floor(diffMs / 60_000);
  if (minutes < 1) return "just now";
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  return new Date(iso).toLocaleString();
}

interface OverviewPageHeaderProps {
  range: OverviewRange;
  onRangeChange: (range: OverviewRange) => void;
  generatedAt?: string;
  onRefresh: () => void;
  isRefreshing?: boolean;
}

export function OverviewPageHeader({
  range,
  onRangeChange,
  generatedAt,
  onRefresh,
  isRefreshing,
}: OverviewPageHeaderProps) {
  return (
    <Group justify="space-between" align="center" wrap="wrap" gap="md">
      <Text size="sm" c="dimmed">
        Updated {formatRelativeTime(generatedAt)}
      </Text>
      <Group gap="sm">
        <SegmentedControl
          value={range}
          onChange={(value) => onRangeChange(value as OverviewRange)}
          data={RANGE_OPTIONS}
          size="sm"
          radius="lg"
          color="edr-green"
        />
        <ActionIcon
          variant="light"
          color="edr-green"
          size="lg"
          radius="lg"
          aria-label="Refresh dashboard"
          onClick={onRefresh}
          loading={isRefreshing}
        >
          <RefreshCw size={18} />
        </ActionIcon>
      </Group>
    </Group>
  );
}
