import React, { useState, useEffect, useCallback } from 'react';
import { Space, Tooltip } from 'antd';
import { ClockCircleOutlined, CloudOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { getWeather } from '@/services/weather';

dayjs.locale('zh-cn');

/**
 * 时间和天气显示组件
 * 
 * 功能：
 * 1. 实时显示当前时间（每秒更新）
 * 2. 显示天气信息（每30分钟更新）
 * 3. 使用 React.memo 优化，避免父组件重渲染影响
 */
const TimeWeather: React.FC = React.memo(() => {
  const [currentTime, setCurrentTime] = useState(dayjs());
  const [weather, setWeather] = useState({ 
    temp: '--', 
    weather: '未知', 
    city: '未知' 
  });

  // 获取天气数据
  const fetchWeather = useCallback(async () => {
    try {
      const data = await getWeather();
      setWeather(data);
    } catch (error) {
      console.error('获取天气信息失败:', error);
    }
  }, []);

  // 时间更新 effect
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(dayjs());
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  // 天气更新 effect
  useEffect(() => {
    // 初始化天气数据
    fetchWeather();
    
    // 每30分钟更新一次
    const weatherTimer = setInterval(fetchWeather, 30 * 60 * 1000);

    return () => clearInterval(weatherTimer);
  }, [fetchWeather]);

  return (
    <Space size={16}>
      {/* 时间显示 */}
      <span className="inline-flex items-center text-sm text-slate-600">
        <ClockCircleOutlined className="mr-2" />
        {currentTime.format('YYYY年MM月DD日 HH:mm:ss')} 星期{currentTime.format('dd')}
      </span>
      
      {/* 天气显示 */}
      <Tooltip title={`${weather.city}`}>
        <span className="inline-flex items-center text-sm text-slate-600">
          <CloudOutlined className="mr-2" />
          {weather.weather} {weather.temp}℃
        </span>
      </Tooltip>
    </Space>
  );
});

TimeWeather.displayName = 'TimeWeather';

export default TimeWeather;

