import React, { useEffect, useState, useCallback } from 'react';
import { Dropdown, Spin, Space, Tooltip } from 'antd';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import {
  UserOutlined,
  LogoutOutlined,
  ClockCircleOutlined,
  CloudOutlined,
} from '@ant-design/icons';
import { logout, setMenus } from '../store/userSlice';
import type { MenuProps } from 'antd';
import { getCurrentUserMenus } from '@/pages/System/Menu/service';
import { getWeather } from '../services/weather';
import type { RootState } from '../store';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { AppMenu } from './AppMenu';
import { Layout, LayoutContent, Header, Main } from '@/components/ui/layout';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { useToast } from '@/components/ui/use-toast';
import { AlertCircle } from 'lucide-react';

// 设置中文语言
dayjs.locale('zh-cn');

const BasicLayout: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();
  const { toast } = useToast();
  const userInfo = useSelector((state: RootState) => state.user.userInfo);
  const [loading, setLoading] = useState(true);
  const [currentTime, setCurrentTime] = useState(dayjs());
  const [weather, setWeather] = useState({ temp: '--', weather: '未知', city: '未知' });
  const [logoutDialogOpen, setLogoutDialogOpen] = useState(false);

  // 根据当前路径获取需要展开的父级菜单
  const getDefaultOpenKeys = () => {
    const pathSegments = location.pathname.split('/').filter(Boolean);
    const openKeys: string[] = [];
    let currentPath = '';

    pathSegments.forEach((segment) => {
      currentPath += `/${segment}`;
      openKeys.push(currentPath);
    });

    return openKeys;
  };

  // 设置默认展开的菜单
  const [openKeys, setOpenKeys] = useState<string[]>(getDefaultOpenKeys());

  // 当路由变化时，自动展开对应的父级菜单
  useEffect(() => {
    const newOpenKeys = getDefaultOpenKeys();
    setOpenKeys((prevKeys) => {
      const mergedKeys = [...new Set([...prevKeys, ...newOpenKeys])];
      return mergedKeys;
    });
  }, [location.pathname]);

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

  // 初始化用户数据
  useEffect(() => {
    const initializeUserData = async () => {
      setLoading(true);
      try {
        const menuData = await getCurrentUserMenus();
        dispatch(setMenus(menuData));
      } catch (error) {
        toast({
          title: '加载失败',
          description: '获取菜单数据失败',
          variant: 'destructive',
        });
        console.error('获取菜单数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    if (!userInfo) {
      initializeUserData();
    } else {
      setLoading(false);
    }
  }, [dispatch, userInfo, toast]);

  // 处理时间和天气更新
  useEffect(() => {
    // 每秒更新时间
    const timer = setInterval(() => {
      setCurrentTime(dayjs());
    }, 1000);

    // 初始化天气并设置定时更新
    fetchWeather();
    const weatherTimer = setInterval(fetchWeather, 30 * 60 * 1000);

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

  const handleLogout = () => {
    setLogoutDialogOpen(true);
  };

  const confirmLogout = () => {
    dispatch(logout());
    toast({
      title: '退出成功',
      description: '已成功退出系统',
    });
    navigate('/login', { replace: true });
  };

  const userMenuItems: MenuProps['items'] = [
    {
      key: 'userInfo',
      icon: <UserOutlined />,
      label: (
        <div style={{ padding: '4px 0' }}>
          <div>当前用户：{userInfo?.nickname || userInfo?.username}</div>
          {userInfo?.email && <div style={{ fontSize: '12px', color: '#999' }}>{userInfo.email}</div>}
        </div>
      ),
      disabled: true,
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout,
    },
  ];

  // 处理菜单展开/收起
  const handleOpenChange = (keys: string[]) => {
    setOpenKeys(keys);
  };

  if (loading) {
    return (
      <div className="flex h-screen w-screen flex-col items-center justify-center bg-slate-50">
        <Spin size="large" />
        <div className="mt-6 text-center text-slate-500">
          <p className="text-base">正在为您准备系统资源</p>
          <p className="text-sm">请稍候，马上就好...</p>
        </div>
      </div>
    );
  }

  return (
    <Layout>
      <AppMenu openKeys={openKeys} onOpenChange={handleOpenChange} />
      <LayoutContent>
        <Header className="justify-end">
          <Space size={24}>
            <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>
            <Dropdown menu={{ items: userMenuItems }} trigger={['hover']}>
              <Space className="cursor-pointer">
                <UserOutlined />
                <span>{userInfo?.nickname || userInfo?.username}</span>
              </Space>
            </Dropdown>
          </Space>
        </Header>
        <Main className="bg-white">
          <Outlet />
        </Main>
      </LayoutContent>

      {/* 退出登录确认对话框 */}
      <AlertDialog open={logoutDialogOpen} onOpenChange={setLogoutDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <AlertCircle className="h-5 w-5 text-amber-500" />
              确认退出
            </AlertDialogTitle>
            <AlertDialogDescription>
              确定要退出系统吗？
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setLogoutDialogOpen(false)}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction onClick={confirmLogout}>确定</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Layout>
  );
};

export default BasicLayout;
