import NumberFlow from "@number-flow/react";
import { useEffect, useState } from "react";
import { RefreshIcon } from "tdesign-icons-react";
import { Button, Typography } from "tdesign-react";

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"
      />
    );
  }

  if (dashboardUpdatedAt <= 0) {
    return <Typography.Text theme="secondary">等待首次刷新</Typography.Text>;
  }

  if (isFetching) {
    return <Typography.Text theme="secondary">刷新中...</Typography.Text>;
  }

  const seconds = nextRefreshSeconds ?? 0;
  const isMinuteMode = refreshInterval >= 60000;

  if (isMinuteMode) {
    const mm = Math.floor(seconds / 60);
    const ss = seconds % 60;

    return (
      <span aria-label={formatAccessibleLabel(seconds, true)} className="refresh-countdown-flow">
        <NumberFlow
          className="refresh-countdown-flow__number"
          format={{ minimumIntegerDigits: 1 }}
          trend={-1}
          value={mm}
        />
        <span className="refresh-countdown-flow__unit">分</span>
        <NumberFlow
          className="refresh-countdown-flow__number"
          digits={{ 1: { max: 5 } }}
          format={{ minimumIntegerDigits: 2 }}
          trend={-1}
          value={ss}
        />
        <span className="refresh-countdown-flow__unit">秒</span>
      </span>
    );
  }

  return (
    <span aria-label={formatAccessibleLabel(seconds, false)} className="refresh-countdown-flow">
      <NumberFlow className="refresh-countdown-flow__number" trend={-1} value={seconds} />
      <span className="refresh-countdown-flow__unit">秒</span>
    </span>
  );
}

function formatAccessibleLabel(seconds: number, isMinuteMode: boolean): string {
  if (isMinuteMode) {
    const mm = Math.floor(seconds / 60);
    const ss = seconds % 60;
    return `${mm}分${String(ss).padStart(2, "0")}秒`;
  }
  return `${seconds}秒`;
}
