import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import '/models/conversations.dart';
import '/models/friends.dart';
import '/models/my_profile.dart';
import '/utils/storage/conversations.dart';
import '/utils/storage/friends.dart';
import '/utils/storage/messages.dart';
import '/utils/storage/session_cookie.dart';
import '/views/main/conversation/list.dart';
import '/views/main/friend/list.dart';
import '/views/main/profile/profile.dart';

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

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  List<Conversation> conversations = [];
  List<Friend> friends = [];
  List<Friend> friendRequests = [];
  MyProfile profile = MyProfile(
    id: '',
    username: '',
    messageExpiryDefault: 'no_expiry',
  );

  bool isLoading = true;
  int _selectedIndex = 0;
  List<Widget> _widgetOptions = <Widget>[
    const ConversationList(conversations: [], friends: []),
    FriendList(friends: const [], friendRequests: const [], callback: () {}),
    Profile(
      profile: MyProfile(
        id: '',
        username: '',
        messageExpiryDefault: 'no_expiry',
      )
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async => false,
        child: isLoading ? loading() : Scaffold(
            body: _widgetOptions.elementAt(_selectedIndex),
            bottomNavigationBar: isLoading ? const SizedBox.shrink() : BottomNavigationBar(
                currentIndex: _selectedIndex,
                onTap: _onItemTapped,
                selectedItemColor: Theme.of(context).primaryColor,
                unselectedItemColor: Theme.of(context).hintColor,
                selectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600),
                unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600),
                type: BottomNavigationBarType.fixed,
                items: const [
                  BottomNavigationBarItem(
                      icon: Icon(Icons.message),
                      label: 'Chats',
                  ),
                  BottomNavigationBarItem(
                      icon: Icon(Icons.group_work),
                      label: 'Friends',
                  ),
                  BottomNavigationBarItem(
                      icon: Icon(Icons.account_box),
                      label: 'Profile',
                  ),
                ],
            ),
        ),
    );
  }

  Future<bool> checkLogin() async {
    bool isLoggedIn = false;

    try {
      isLoggedIn = await MyProfile.isLoggedIn();
    } catch (Exception) {
      Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing'));
      return false;
    }

    if (!isLoggedIn) {
      await MyProfile.logout();
      Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing'));
      return false;
    }

    int statusCode = 200;
    try {
      var resp = await http.get(
          await MyProfile.getServerUrl('api/v1/auth/check'),
          headers: {
            'cookie': await getSessionCookie(),
          }
      );
      statusCode = resp.statusCode;
    } catch(SocketException) {
      if (await MyProfile.isLoggedIn()) {
        return true;
      }
    }

    if (isLoggedIn && statusCode == 200) {
      return true;
    }

    MyProfile.logout();
    Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing'));
    return false;
  }

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

  Widget loading() {
    return Stack(
        children: <Widget>[
          const Opacity(
              opacity: 0.1,
              child: ModalBarrier(dismissible: false, color: Colors.black),
          ),
          Center(
              child: Column(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: const <Widget> [
                    CircularProgressIndicator(),
                    SizedBox(height: 25),
                    Text('Loading...'),
                  ],
              )
          ),
        ]
    );
  }

  void updateData() async {
    if (!await checkLogin()) {
      return;
    }

    await updateFriends();
    await updateConversations();
    await updateMessageThreads();

    conversations = await getConversations();
    friends = await getFriends(accepted: true);
    friendRequests = await getFriends(accepted: false);
    profile = await MyProfile.getProfile();

    setState(() {
      _widgetOptions = <Widget>[
        ConversationList(
            conversations: conversations,
            friends: friends,
        ),
        FriendList(
          friends: friends,
          friendRequests: friendRequests,
          callback: reinitDatabaseRecords,
        ),
        Profile(profile: profile),
      ];
      isLoading = false;
    });
  }

  Future<void> reinitDatabaseRecords() async {

    conversations = await getConversations();
    friends = await getFriends(accepted: true);
    friendRequests = await getFriends(accepted: false);
    profile = await MyProfile.getProfile();

    setState(() {
      _widgetOptions = <Widget>[
        ConversationList(
            conversations: conversations,
            friends: friends,
        ),
        FriendList(
          friends: friends,
          friendRequests: friendRequests,
          callback: reinitDatabaseRecords,
        ),
        Profile(profile: profile),
      ];
      isLoading = false;
    });
  }

  void _onItemTapped(int index) async {
    await reinitDatabaseRecords();
    setState(() {
      _selectedIndex = index;
    });
  }
}
