'use client';

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

/**
 * Single source of truth for the in-call countdown shared by both the
 * patient and doctor pages. We re-anchor `endsAt` whenever the backend
 * pushes a `call.extended` event so both sides stay in lockstep.
 *
 *   - `warningWindowSeconds` (default 60) — pill turns amber.
 *   - `countdownSeconds`     (default 15) — full-screen overlay armed.
 *
 * `onAutoEnd` fires exactly once when remaining hits zero. The caller is
 * expected to call the /end endpoint and tear down the call.
 */
export interface CallTimerState {
  remaining: number; // seconds (clamped >= 0)
  mmss: string; // "MM:SS"
  isWarning: boolean; // remaining <= warningWindowSeconds
  isCountdown: boolean; // remaining <= countdownSeconds
  expired: boolean;
}

export function useCallTimer(opts: {
  endsAt: Date | null;
  enabled?: boolean;
  warningWindowSeconds?: number;
  countdownSeconds?: number;
  onAutoEnd?: () => void;
}): CallTimerState {
  const {
    endsAt,
    enabled = true,
    warningWindowSeconds = 60,
    countdownSeconds = 15,
    onAutoEnd,
  } = opts;

  const [now, setNow] = useState<number>(() => Date.now());
  const firedRef = useRef(false);
  const onAutoEndRef = useRef(onAutoEnd);
  onAutoEndRef.current = onAutoEnd;

  useEffect(() => {
    if (!enabled || !endsAt) return;
    firedRef.current = false;
    const id = setInterval(() => setNow(Date.now()), 500);
    return () => clearInterval(id);
  }, [enabled, endsAt?.getTime()]);

  const endsAtMs = endsAt ? endsAt.getTime() : 0;
  const remaining = endsAt ? Math.max(0, Math.floor((endsAtMs - now) / 1000)) : 0;

  // Fire auto-end exactly once.
  if (
    enabled &&
    endsAt &&
    remaining === 0 &&
    !firedRef.current &&
    onAutoEndRef.current
  ) {
    firedRef.current = true;
    onAutoEndRef.current();
  }

  const m = Math.floor(remaining / 60).toString().padStart(2, '0');
  const s = (remaining % 60).toString().padStart(2, '0');

  return {
    remaining,
    mmss: `${m}:${s}`,
    isWarning: remaining > 0 && remaining <= warningWindowSeconds,
    isCountdown: remaining > 0 && remaining <= countdownSeconds,
    expired: !!endsAt && remaining === 0,
  };
}
