import 'dart:io';

import 'package:elysia/page/LoginPage.dart';
import 'package:elysia/plugin/HTTP.dart';
import 'package:flutter/material.dart';

import '../plugin/C.dart';
import '../plugin/CacheAavatar.dart';
import '../plugin/RouteAnimation.dart';
import 'FollowListPage.dart';
import 'SettingPage.dart';
import 'child/ChangePasswordDialog.dart';
import 'child/MyRobotPage.dart';

import 'package:path_provider/path_provider.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({Key? key}) : super(key: key);

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage>
    with AutomaticKeepAliveClientMixin {
  String? balance; // 余额
  bool isLoadingBalance = true;

  @override
  void initState() {
    super.initState();
    fetchBalance();
  }

  Future<void> fetchBalance() async {
    try {
      final result = await HTTP
          .create("${C.BASE_URL}/server/balance")
          .setHeader(C.TOKEN)
          .setRequestType(RequestType.GET)
          .execute();
      if (result['code'] == 200) {
        setState(() {
          balance = result['data']['balance'].toString()+"元";
          isLoadingBalance = false;
        });
      }else{
        setState(() {
          balance = "Deepseek API Key错误";
          isLoadingBalance = false;
        });
      }
    } catch (e) {
      setState(() => isLoadingBalance = false);
    }
  }



  Widget _buildMenuItem({
    required IconData icon,
    required String title,
    required Color bg,
    required Color color,
    VoidCallback? onTap,
    String? trailingText,
  }) {
    return Container(
      decoration: BoxDecoration(
        border: Border(bottom: BorderSide(color: Colors.grey, width: 0.5)),
      ),
      child: ListTile(
        leading: Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            color: bg,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(icon, color: color),
        ),
        title: Text(title, style: const TextStyle(fontSize: 16)),
        trailing: trailingText != null
            ? Text(trailingText, style: const TextStyle(color: Colors.grey))
            : Icon(Icons.chevron_right, color: Colors.grey),
        onTap: onTap,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // 第一行：头像 + 昵称 + 账号
          Container(
            padding: const EdgeInsets.all(16),
            color: Colors.white,
            child: Row(
              children: [
                CacheAvatar(url: C.PROFILE["avatar"],),
                const SizedBox(width: 16),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      C.PROFILE["nickname"] ?? "-",
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      "账号: ${C.PROFILE["userName"] ?? '-'}",
                      style: const TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
                Expanded(child: SizedBox()),
                GestureDetector(onTap: (){
                  showChangePasswordDialog(context);
                },child: Icon(Icons.password, color: Colors.grey),),
              ],
            ),
          ),
          const SizedBox(height: 12),

          // 第二行：邮箱
          _buildMenuItem(
            bg: Colors.blue,
            color: Colors.white,
            icon: Icons.email,
            title: "邮箱",
            trailingText: (C.PROFILE["email"] ?? "-"),
          ),

          const SizedBox(height: 5),
          // 第三行：余额
          _buildMenuItem(
            bg: Colors.amber,
            color: Colors.white,
            icon: Icons.account_balance_wallet,
            title: "余额",
            trailingText: isLoadingBalance ? "加载中..." : "${balance ?? "0元"}",
          ),

          const SizedBox(height: 5),
          // 第四行：我创建的机器人
          _buildMenuItem(
            bg: Colors.deepOrangeAccent,
            color: Colors.white,
            icon: Icons.android,
            title: "我的机器人",
            onTap: () async {
              bool status = await Navigator.push(
                context,
                RouteAnimation(MyRobotPage(), Offset(1, 0)),
              );
              if (status) {
                FollowListPage.flushData!(false);
              }
            },
          ),

          const SizedBox(height: 5),
          // 第五行：设置
          _buildMenuItem(
            bg: Colors.teal,
            color: Colors.white,
            icon: Icons.settings,
            title: "设置",
            onTap: () {
              Navigator.push(context, RouteAnimation(SettingPage(), Offset(1, 0)));
            },
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => false;
}
