import { useEffect, useState } from "react";
import { RefreshIcon } from "tdesign-icons-react";
import { Button, Typography } from "tdesign-react";

import { formatCountdown } from "../utils/time";

interface RefreshCountdownProps {
  dashboardUpdatedAt: number;
  isFetching: boolean;
  isManualRefresh: boolean;
  onRefresh: () => void;
  refreshInterval: number;
}

export function RefreshCountdown({
  dashboardUpdatedAt,
  isFetching,
  isManualRefresh,
  onRefresh,
  refreshInterval,
}: RefreshCountdownProps) {
  const [now, setNow] = useState(() => new Date());

  useEffect(() => {
    const timer = window.setInterval(() => setNow(new Date()), 1000);
    return () => window.clearInterval(timer);
  }, []);

  const nextRefreshSeconds =
    dashboardUpdatedAt > 0 && !isManualRefresh
      ? Math.max(0, Math.ceil((dashboardUpdatedAt + refreshInterval - now.getTime()) / 1000))
      : null;

  if (isManualRefresh) {
    return (
      <Button
        aria-label="刷新 Dashboard"
        disabled={isFetching}
        icon={<RefreshIcon />}
        loading={isFetching}
        onClick={() => void onRefresh()}
        shape="circle"
        variant="outline"
      />
    );
  }

  const refreshText =
    dashboardUpdatedAt > 0 ? (isFetching ? "刷新中..." : formatCountdown(nextRefreshSeconds ?? 0)) : "等待首次刷新";

  return <Typography.Text theme="secondary">{refreshText}</Typography.Text>;
}
