'use client';

import { useState, useEffect, useCallback, useRef } from 'react';

export interface MeetingTimerState {
  /** Elapsed time in seconds */
  elapsedSeconds: number;
  /** Timer is currently running */
  isRunning: boolean;
  /** Timer has been started at least once */
  hasStarted: boolean;
  /** Formatted time string (MM:SS) */
  formattedTime: string;
  /** Formatted time string with hours (HH:MM:SS) */
  formattedTimeLong: string;
}

export interface MeetingTimerActions {
  /** Start or resume the timer */
  start: () => void;
  /** Pause the timer */
  pause: () => void;
  /** Stop and reset the timer */
  reset: () => void;
  /** Set initial elapsed time (for resuming) */
  setInitialTime: (seconds: number) => void;
}

export type UseMeetingTimerReturn = MeetingTimerState & MeetingTimerActions;

/**
 * Format seconds to MM:SS
 */
function formatTime(seconds: number): string {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

/**
 * Format seconds to HH:MM:SS
 */
function formatTimeLong(seconds: number): string {
  const hours = Math.floor(seconds / 3600);
  const mins = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

/**
 * Calculate elapsed seconds from start time
 */
function calculateElapsedSeconds(startTime: Date | string | null): number {
  if (!startTime) return 0;
  const start = typeof startTime === 'string' ? new Date(startTime) : startTime;
  const now = new Date();
  return Math.floor((now.getTime() - start.getTime()) / 1000);
}

/**
 * Hook for managing a meeting timer
 *
 * @param startTime - Optional start time to calculate initial elapsed time
 * @param autoStart - Whether to auto-start the timer if startTime is provided
 */
export function useMeetingTimer(
  startTime?: Date | string | null,
  autoStart = false
): UseMeetingTimerReturn {
  const [elapsedSeconds, setElapsedSeconds] = useState(0);
  const [isRunning, setIsRunning] = useState(false);
  const [hasStarted, setHasStarted] = useState(false);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  // Initialize from startTime if provided
  useEffect(() => {
    if (startTime) {
      const elapsed = calculateElapsedSeconds(startTime);
      setElapsedSeconds(elapsed);
      setHasStarted(true);
      if (autoStart) {
        setIsRunning(true);
      }
    }
  }, [startTime, autoStart]);

  // Timer tick effect
  useEffect(() => {
    if (isRunning) {
      intervalRef.current = setInterval(() => {
        setElapsedSeconds((prev) => prev + 1);
      }, 1000);
    }

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    };
  }, [isRunning]);

  const start = useCallback(() => {
    setIsRunning(true);
    setHasStarted(true);
  }, []);

  const pause = useCallback(() => {
    setIsRunning(false);
  }, []);

  const reset = useCallback(() => {
    setIsRunning(false);
    setHasStarted(false);
    setElapsedSeconds(0);
  }, []);

  const setInitialTime = useCallback((seconds: number) => {
    setElapsedSeconds(seconds);
    if (seconds > 0) {
      setHasStarted(true);
    }
  }, []);

  return {
    elapsedSeconds,
    isRunning,
    hasStarted,
    formattedTime: formatTime(elapsedSeconds),
    formattedTimeLong: formatTimeLong(elapsedSeconds),
    start,
    pause,
    reset,
    setInitialTime,
  };
}

/**
 * Hook for a countdown timer (e.g., for meeting time limit)
 *
 * @param targetMinutes - Target duration in minutes
 * @param onComplete - Callback when countdown reaches zero
 */
export function useMeetingCountdown(
  targetMinutes: number,
  onComplete?: () => void
): UseMeetingTimerReturn & { isOvertime: boolean; remainingSeconds: number } {
  const timer = useMeetingTimer();
  const targetSeconds = targetMinutes * 60;
  const remainingSeconds = Math.max(0, targetSeconds - timer.elapsedSeconds);
  const isOvertime = timer.elapsedSeconds > targetSeconds;

  // Call onComplete when countdown reaches zero
  useEffect(() => {
    if (timer.isRunning && remainingSeconds === 0 && onComplete) {
      onComplete();
    }
  }, [remainingSeconds, timer.isRunning, onComplete]);

  return {
    ...timer,
    isOvertime,
    remainingSeconds,
    formattedTime: isOvertime
      ? `+${formatTime(timer.elapsedSeconds - targetSeconds)}`
      : formatTime(remainingSeconds),
    formattedTimeLong: isOvertime
      ? `+${formatTimeLong(timer.elapsedSeconds - targetSeconds)}`
      : formatTimeLong(remainingSeconds),
  };
}
