/**
 * Mawidi Demo Scheduler - useTimezone Hook
 * Manages timezone detection and conversion
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import { SCHEDULER_CONFIG } from "../config/schedulerConfig";
import {
  detectUserTimezone,
  convertToTimezone,
} from "../utils/timezoneHelpers";

// Stable empty options object to prevent re-renders
const EMPTY_OPTIONS: UseTimezoneOptions = {};

export interface UseTimezoneOptions {
  /** Default timezone if detection fails */
  defaultTimezone?: string;
  /** Whether to automatically detect user's timezone */
  autoDetect?: boolean;
}

export interface UseTimezoneReturn {
  /** Current selected timezone */
  timezone: string;
  /** User's detected timezone */
  userTimezone: string;
  /** Scheduler's configured timezone */
  schedulerTimezone: string;
  /** Whether timezone detection is in progress */
  detecting: boolean;
  /** Set a new timezone */
  setTimezone: (tz: string) => void;
  /** Convert a date to the current timezone */
  convertDate: (date: Date) => Date;
  /** Reset to scheduler's default timezone */
  resetToDefault: () => void;
  /** Whether user's timezone differs from scheduler timezone */
  hasTimezoneMismatch: boolean;
}

/**
 * useTimezone Hook
 *
 * Manages timezone detection, selection, and date conversion
 * Helps users understand time differences and schedule correctly
 *
 * @example
 * ```tsx
 * const {
 *   timezone,
 *   userTimezone,
 *   hasTimezoneMismatch,
 *   convertDate
 * } = useTimezone({ autoDetect: true });
 *
 * // Show timezone warning if mismatch
 * {hasTimezoneMismatch && (
 *   <p>Your timezone ({userTimezone}) differs from our scheduling timezone</p>
 * )}
 * ```
 */
export function useTimezone({
  defaultTimezone = SCHEDULER_CONFIG.timezone,
  autoDetect = true,
}: UseTimezoneOptions = EMPTY_OPTIONS): UseTimezoneReturn {
  const schedulerTimezone = SCHEDULER_CONFIG.timezone;

  const [timezone, setTimezone] = useState<string>(defaultTimezone);
  const [userTimezone, setUserTimezone] = useState<string>(defaultTimezone);
  const [detecting, setDetecting] = useState(autoDetect);

  /**
   * Detect user's timezone on mount
   */
  useEffect(() => {
    if (!autoDetect) {
      setDetecting(false);
      return;
    }

    try {
      const detected = detectUserTimezone();
      setUserTimezone(detected);

      // Optionally set as active timezone if different
      // For now, we keep scheduler timezone as default for consistency
      // User can manually change if needed
    } catch (error) {
      console.error("Failed to detect timezone:", error);
      setUserTimezone(defaultTimezone);
    } finally {
      setDetecting(false);
    }
  }, [autoDetect, defaultTimezone]);

  /**
   * Convert a date to the current timezone
   */
  const convertDate = useCallback(
    (date: Date): Date => {
      return convertToTimezone(date, schedulerTimezone, timezone);
    },
    [schedulerTimezone, timezone],
  );

  /**
   * Reset to scheduler's default timezone
   */
  const resetToDefault = useCallback(() => {
    setTimezone(schedulerTimezone);
  }, [schedulerTimezone]);

  /**
   * Check if there's a timezone mismatch
   */
  const hasTimezoneMismatch = userTimezone !== schedulerTimezone;

  return {
    timezone,
    userTimezone,
    schedulerTimezone,
    detecting,
    setTimezone,
    convertDate,
    resetToDefault,
    hasTimezoneMismatch,
  };
}
