import 'dart:developer';

import 'package:elysia/page/ChatRoomPage.dart';
import 'package:elysia/page/child/CreateRobotPage.dart';
import 'package:elysia/plugin/RouteAnimation.dart';
import 'package:elysia/plugin/Toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:alive_plugin/alive_plugin.dart';
import '../plugin/C.dart';
import '../plugin/HTTP.dart';
import '../plugin/LoadingOverlay.dart';
import '../plugin/Notify.dart';
import '../plugin/WebSocketService.dart';
import 'FollowListPage.dart';
import 'ProfilePage.dart';
import 'package:oktoast/oktoast.dart';

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;
  bool reconnect_ws =false;
  final PageController _pageController = PageController();
  final List<Widget> _pages = [
   ChatRoomPage(),
    FollowListPage(),
    ProfilePage()
  ];

  final List<String> _titles = ["聊天", "机器人", "我"];

  void _onPageChanged(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  void _onNavTapped(int index) {
    _pageController.animateToPage(
      index,
      duration: Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  @override
  void dispose() {
    _pageController.dispose();
    C.socket.removeMessageListener(onMessage);
    C.socket.removeReconnectListener(onReconnect);

    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    Notify.setBuildContext(context);
    C.socket.addMessageListener(onMessage);
    C.socket.addReconnectListener(onReconnect);
  }
  void onMessage(dynamic message){
    if(!C.PUSH_STATUS){return;}
    Notify.showNotification(channel: NotifyChannel.message, title:message["name"], body:  message["content"],smallIcon: message["avatar"],payload:{"type":C.NOTIFY_MESSAGE,"roomId": message["roomId"],"avatar": message["avatar"],"name": message["name"]});
    ChatRoomPage.flushData!(message);
  }

  void onReconnect(ReconnectStatus status){
    switch (status){
      case ReconnectStatus.start:
        setState(() {
          reconnect_ws=true;
        });
        break;
      case ReconnectStatus.trying:
        break;
      case ReconnectStatus.success:
        setState(() {
          reconnect_ws=false;
        });
        break;
    }
  }

  Future<void> _onAddPressed() async {

    LoadingOverlay.show(context: context, barrierColor: Colors.black54);
    try{
      dynamic result = await HTTP
          .create("${C.BASE_URL}/robot/template")
          .setHeader(C.TOKEN)
          .setRequestType(RequestType.GET)
          .execute();
      LoadingOverlay.hide();
      if (result["code"] != 200) {
        Toast.show("获取回复模板失败！",type: ToastType.Error,position: ToastPosition.center);
      } else {
        List<Map<String, String>> templateList = [{"key":"请选择回复模板","value":"NULL","example":''}];
        for(dynamic item in result['data']){
          log(item.toString());
          templateList.add({"key":item["templateName"],"value":item["templateId"],"example":item["example"]??''});
        }
        Navigator.push(context, RouteAnimation(CreateRobotPage(templateList: templateList), Offset(1,0)));
      }
    }catch(e){
      LoadingOverlay.hide();
      Toast.show("获取回复模板失败！",type: ToastType.Error,position: ToastPosition.center);
    }

  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
        onPopInvokedWithResult: (didPop, result) async {
          if (didPop) {
            return;
          }
          AlivePlugin.backToDesktopButKeepAlive(); //返回到系统首页
        },
        child: Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.grey[100], // 透明背景
        elevation: 0, // 无阴影
        centerTitle: true,
        leading:reconnect_ws?Padding(
          padding: const EdgeInsets.all(12.0),
          child: SizedBox(
            width: 24,
            height: 24,
            child: CupertinoActivityIndicator(
              radius: 8,
              color: Colors.grey[1000],
            ),
          ),
        ):SizedBox(),
        title: Text(
          _titles[_currentIndex],
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black),
        ),
        actions: [
          _currentIndex==1?Padding(
            padding: EdgeInsets.only(right: 10), // 距离右侧 20
            child: GestureDetector(
              child: Icon(Icons.add_circle_outline, color: Colors.black),
              onTap: _onAddPressed,
            ),
          ):SizedBox(),
        ],
      ),
      body: ScrollConfiguration(
        behavior: NoGlowScrollBehavior(),
        child: PageView(
          controller: _pageController,
          physics: const NeverScrollableScrollPhysics(),
          children: _pages,
          onPageChanged: _onPageChanged,
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: _onNavTapped,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.chat),
            label: '聊天',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.supervised_user_circle),
            label: '机器人',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.account_circle_rounded),
            label: '我',
          ),
        ],
        selectedFontSize: 12,     // 明确指定字体大小
        unselectedFontSize: 12,   // 保持一致
      ),
    ));
  }
}

// 自定义无边缘阴影 ScrollBehavior
class NoGlowScrollBehavior extends ScrollBehavior {
  @override
  Widget buildViewportChrome(
      BuildContext context, Widget child, AxisDirection axisDirection) {
    return child;
  }

  @override
  Widget buildOverscrollIndicator(
      BuildContext context, Widget child, ScrollableDetails details) {
    return child;
  }
}
