"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";

import { formatSecondsToHHMMSS } from "@/shared/utils/date";

interface UseTimerOptions {
  initialSeconds: number;
  persist?: boolean;
  storageKey?: string;
}

export function useTimer({
  initialSeconds,
  persist = false,
  storageKey,
}: UseTimerOptions) {
  // Always initialize with initialSeconds to match SSR
  const [seconds, setSeconds] = useState<number>(initialSeconds);

  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  // Load from localStorage after mount (client-only)
  useEffect(() => {
    if (persist && storageKey && typeof window !== "undefined") {
      const saved = localStorage.getItem(storageKey);
      if (saved !== null) {
        const parsed = parseInt(saved, 10);
        if (!isNaN(parsed)) {
          setSeconds(parsed);
          return; // Don't save again if we just loaded
        }
      }
    }
  }, [persist, storageKey]); // Run once on mount

  // Save to localStorage when seconds change
  useEffect(() => {
    if (persist && storageKey && typeof window !== "undefined") {
      localStorage.setItem(storageKey, seconds.toString());
    }
  }, [seconds, persist, storageKey]);

  useEffect(() => {
    if (seconds <= 0) return;
    intervalRef.current = setInterval(() => {
      setSeconds(prev => {
        if (prev <= 1) {
          if (intervalRef.current) {
            clearInterval(intervalRef.current);
          }
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [seconds]);

  const reset = useCallback(() => {
    setSeconds(initialSeconds);
    if (persist && storageKey && typeof window !== "undefined") {
      localStorage.setItem(storageKey, initialSeconds.toString());
    }
  }, [initialSeconds, persist, storageKey]);

  return useMemo(
    () => ({
      time: formatSecondsToHHMMSS(seconds, { isHours: false }),
      seconds,
      reset,
      isFinished: seconds === 0,
    }),
    [seconds, reset]
  );
}
