import { useState, useEffect, useCallback } from 'react';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezonePlugin from 'dayjs/plugin/timezone';
import localizedFormat from 'dayjs/plugin/localizedFormat';
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/en';

import { formatToDatetime } from '../Util';

dayjs.extend(utc);
dayjs.extend(timezonePlugin);
dayjs.extend(localizedFormat);

const currentTimezone = dayjs.tz.guess();

// 获取时间段
const getTimePhase = (hour: number) => {
  if (hour >= 0 && hour < 6) return { phase: 'dawn', icon: '🌒' }; // 凌晨 00:00-05:59
  if (hour >= 6 && hour < 12) return { phase: 'morning', icon: '🌞' }; // 上午 06:00-11:59
  if (hour >= 12 && hour < 18) return { phase: 'afternoon', icon: '🌞' }; // 下午 12:00-17:59
  return { phase: 'night', icon: '🌒' }; // 晚上 18:00-23:59
};

export default function useClock(timezone = currentTimezone, locale = 'zh') {
  const getLatestTimeInfo = useCallback(() => {
    const currentLocale = locale === 'zh' ? 'zh-cn' : 'en';
    const localeOption = locale === 'zh' ? 'zh-cn' : 'en-us';
    dayjs.locale(currentLocale);

    const now = dayjs().tz(timezone);
    const hour = now.hour();
    const { phase, icon } = getTimePhase(hour);

    return {
      formattedTime: now.format('LT'),
      fullDateTime: formatToDatetime(now.toDate(), { tz: timezone, locale: localeOption }),
      phase,
      icon,
      rawTime: now,
    };
  }, [timezone, locale]);

  const [timeInfo, setTimeInfo] = useState(getLatestTimeInfo());

  useEffect(() => {
    // 立即更新一次，确保初始状态是最新的
    setTimeInfo(getLatestTimeInfo());

    // 设置定时器
    const timerId = setInterval(() => {
      setTimeInfo(getLatestTimeInfo());
    }, 6000);

    // 清理函数
    return () => {
      clearInterval(timerId);
    };
  }, [timezone, locale, getLatestTimeInfo]);

  return timeInfo;
}
