import { useEffect, useRef, useState } from "react";
import { Text } from "react-native";
import { COUNTDOWN_INTERVAL_MS } from "@/lib/constants";
import { formatResetCountdown, formatResetCountdownISO } from "@/lib/timeUtils";

interface ResetCountdownProps {
  resetAtSeconds?: number;
  resetAtISO?: string;
}

export function ResetCountdown({ resetAtSeconds, resetAtISO }: ResetCountdownProps) {
  const latest = useRef({ resetAtSeconds, resetAtISO });
  latest.current = { resetAtSeconds, resetAtISO };

  const getLabel = () => {
    if (latest.current.resetAtSeconds !== undefined) {
      return formatResetCountdown(latest.current.resetAtSeconds);
    }
    if (latest.current.resetAtISO) return formatResetCountdownISO(latest.current.resetAtISO);
    return "";
  };

  const [label, setLabel] = useState(getLabel);

  useEffect(() => {
    const update = () => setLabel(getLabel());
    update();
    const interval = setInterval(update, COUNTDOWN_INTERVAL_MS);
    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    setLabel(getLabel());
  }, [resetAtSeconds, resetAtISO]);

  if (!label) return null;

  return (
    <Text className="text-xs text-neutral-500 dark:text-neutral-400">{label}</Text>
  );
}
