import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Card, NavBar, List, Button, Dialog, Toast } from "antd-mobile";
import {
  LogoutOutlined,
  PhoneOutlined,
  MessageOutlined,
  DatabaseOutlined,
  FolderOpenOutlined,
  BellOutlined,
  SettingOutlined,
} from "@ant-design/icons";
import MeauMobile from "@/components/MeauMobile/MeauMoible";
import Layout from "@/components/Layout/Layout";
import style from "./index.module.scss";

const Mine: React.FC = () => {
  const navigate = useNavigate();
  const [userInfo, setUserInfo] = useState<any>(null);
  const [stats, setStats] = useState({
    devices: 12,
    wechat: 25,
    traffic: 8,
    content: 156,
  });
  const [showLogoutDialog, setShowLogoutDialog] = useState(false);

  // 从localStorage获取用户信息
  useEffect(() => {
    const userInfoStr = localStorage.getItem("userInfo");
    if (userInfoStr) {
      setUserInfo(JSON.parse(userInfoStr));
    }
  }, []);

  // 用户信息
  const currentUserInfo = {
    name: userInfo?.username || "售前",
    email: userInfo?.email || "zhangsan@example.com",
    role: "管理员",
    lastLogin: "2024-01-20 14:30",
    avatar: userInfo?.avatar || "",
  };

  // 功能模块数据
  const functionModules = [
    {
      id: "devices",
      title: "设备管理",
      description: "管理您的设备和微信账号",
      icon: <PhoneOutlined />,
      count: stats.devices,
      path: "/devices",
      bgColor: "#e6f7ff",
      iconColor: "#1890ff",
    },
    {
      id: "wechat",
      title: "微信号管理",
      description: "管理微信账号和好友",
      icon: <MessageOutlined />,
      count: stats.wechat,
      path: "/wechat-accounts",
      bgColor: "#f6ffed",
      iconColor: "#52c41a",
    },
    {
      id: "traffic",
      title: "流量池",
      description: "管理用户流量池和分组",
      icon: <DatabaseOutlined />,
      count: stats.traffic,
      path: "/traffic-pool",
      bgColor: "#f9f0ff",
      iconColor: "#722ed1",
    },
    {
      id: "content",
      title: "内容库",
      description: "管理营销内容和素材",
      icon: <FolderOpenOutlined />,
      count: stats.content,
      path: "/content",
      bgColor: "#fff7e6",
      iconColor: "#fa8c16",
    },
  ];

  // 加载统计数据
  const loadStats = async () => {
    try {
      // 这里可以调用实际的API
      // const [deviceStats, wechatStats, trafficStats, contentStats] = await Promise.allSettled([
      //   getDeviceStats(),
      //   getWechatStats(),
      //   getTrafficStats(),
      //   getContentStats(),
      // ]);

      // 暂时使用模拟数据
      setStats({
        devices: 12,
        wechat: 25,
        traffic: 8,
        content: 156,
      });
    } catch (error) {
      console.error("加载统计数据失败:", error);
    }
  };

  useEffect(() => {
    loadStats();
  }, []);

  const handleLogout = () => {
    // 清除本地存储的用户信息
    localStorage.removeItem("token");
    localStorage.removeItem("token_expired");
    localStorage.removeItem("s2_accountId");
    localStorage.removeItem("userInfo");
    setShowLogoutDialog(false);
    navigate("/login");
    Toast.show({
      content: "退出成功",
      position: "top",
    });
  };

  const handleFunctionClick = (path: string) => {
    navigate(path);
  };

  // 渲染用户头像
  const renderUserAvatar = () => {
    if (currentUserInfo.avatar) {
      return <img src={currentUserInfo.avatar} alt="头像" />;
    }
    return (
      <div
        style={{
          width: "100%",
          height: "100%",
          backgroundColor: "#1890ff",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          color: "white",
          fontSize: "24px",
          fontWeight: "bold",
        }}
      >
        售
      </div>
    );
  };

  // 渲染功能模块图标
  const renderModuleIcon = (module: any) => (
    <div
      style={{
        width: "40px",
        height: "40px",
        backgroundColor: module.bgColor,
        borderRadius: "8px",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        color: module.iconColor,
        fontSize: "20px",
      }}
    >
      {module.icon}
    </div>
  );

  return (
    <Layout
      header={
        <NavBar back={null} style={{ background: "#fff" }}>
          <div style={{ color: "var(--primary-color)", fontWeight: 600 }}>
            我的
          </div>
        </NavBar>
      }
      footer={<MeauMobile activeKey="mine" />}
    >
      <div className={style["mine-page"]}>
        {/* 用户信息卡片 */}
        <Card className={style["user-card"]}>
          <div className={style["user-info"]}>
            <div className={style["user-avatar"]}>{renderUserAvatar()}</div>
            <div className={style["user-details"]}>
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: "8px",
                  marginBottom: "4px",
                }}
              >
                <div className={style["user-name"]}>{currentUserInfo.name}</div>
                <span
                  style={{
                    padding: "2px 8px",
                    backgroundColor: "#fa8c16",
                    color: "white",
                    borderRadius: "12px",
                    fontSize: "12px",
                    fontWeight: "500",
                  }}
                >
                  {currentUserInfo.role}
                </span>
              </div>
              <div
                style={{ fontSize: "14px", color: "#666", marginBottom: "4px" }}
              >
                {currentUserInfo.email}
              </div>
              <div style={{ fontSize: "12px", color: "#666" }}>
                最近登录: {currentUserInfo.lastLogin}
              </div>
            </div>
            <div
              style={{ display: "flex", flexDirection: "column", gap: "8px" }}
            >
              <BellOutlined style={{ fontSize: "20px", color: "#666" }} />
              <SettingOutlined style={{ fontSize: "20px", color: "#666" }} />
            </div>
          </div>
        </Card>

        {/* 我的功能 */}
        <Card className={style["menu-card"]}>
          <List>
            {functionModules.map((module) => (
              <List.Item
                key={module.id}
                prefix={renderModuleIcon(module)}
                title={module.title}
                description={module.description}
                extra={
                  <span
                    style={{
                      padding: "2px 8px",
                      backgroundColor: "#f0f0f0",
                      borderRadius: "12px",
                      fontSize: "12px",
                      color: "#666",
                    }}
                  >
                    {module.count}
                  </span>
                }
                arrow
                onClick={() => handleFunctionClick(module.path)}
              />
            ))}
          </List>
        </Card>

        {/* 退出登录按钮 */}
        <Button
          block
          color="danger"
          fill="outline"
          className={style["logout-btn"]}
          onClick={() => setShowLogoutDialog(true)}
        >
          <LogoutOutlined style={{ marginRight: "8px" }} />
          退出登录
        </Button>
      </div>

      {/* 退出登录确认对话框 */}
      <Dialog
        content="您确定要退出登录吗？退出后需要重新登录才能使用完整功能。"
        visible={showLogoutDialog}
        closeOnAction
        actions={[
          [
            {
              key: "cancel",
              text: "取消",
            },
            {
              key: "confirm",
              text: "确认退出",
              bold: true,
              danger: true,
              onClick: handleLogout,
            },
          ],
        ]}
        onClose={() => setShowLogoutDialog(false)}
      />
    </Layout>
  );
};

export default Mine;
