import 'dart:collection';

import 'package:aitrainer_app/bloc/account/account_bloc.dart';
import 'package:aitrainer_app/library/custom_icon_icons.dart';
import 'package:aitrainer_app/util/app_language.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/model/customer.dart';
import 'package:aitrainer_app/util/common.dart';
import 'package:aitrainer_app/util/trans.dart';
import 'package:aitrainer_app/widgets/app_bar_min.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:aitrainer_app/widgets/bottom_nav.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

// ignore: must_be_immutable
class AccountPage extends StatelessWidget with Trans {
  // ignore: close_sinks
  late AccountBloc accountBloc;

  @override
  Widget build(BuildContext context) {
    setContext(context);
    accountBloc = BlocProvider.of<AccountBloc>(context);
    return Scaffold(
        appBar: AppBarMin(),
        body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('asset/image/WT_light_background.jpg'),
              fit: BoxFit.cover,
              alignment: Alignment.center,
            ),
          ),
          child: BlocConsumer<AccountBloc, AccountState>(listener: (context, state) {
            if (state is AccountError) {
              ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white))));
            } else if (state is AccountLoading) {}
          }, builder: (context, state) {
            return accountWidget(context, accountBloc);
          }),
        ),
        bottomNavigationBar: BottomNavigator(bottomNavIndex: 3));
  }

  ListView accountWidget(BuildContext context, AccountBloc accountBloc) {
    String customerName = "";
    String goal = t("Set your goal");
    String fitnessLevel = t("Set your fitness level");
    String bodyType = "";

    customerName = accountBloc.customerRepository.firstName! + " " + accountBloc.customerRepository.name!;
    customerName = customerName.length < 3 ? t("Personal data") : customerName;
    goal = accountBloc.customerRepository.customer != null && accountBloc.customerRepository.customer!.goal != null
        ? t(accountBloc.customerRepository.customer!.goal!)
        : goal;
    fitnessLevel = accountBloc.customerRepository.customer != null && accountBloc.customerRepository.customer!.fitnessLevel != null
        ? t(capitalize(accountBloc.customerRepository.customer!.fitnessLevel!))
        : fitnessLevel;
    bodyType = accountBloc.getAccurateBodyType();

    final HashMap<String, dynamic> args = HashMap();
    return ListView(padding: EdgeInsets.only(top: 35), children: <Widget>[
      ListTile(
        leading: Common.badgedIcon(Colors.grey, Icons.perm_identity, "personalData"), //Icon(Icons.perm_identity),
        subtitle: Text(t("Profile")),
        title: TextButton(
          child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            Text(customerName, style: TextStyle(color: Colors.blue)),
            Icon(Icons.arrow_forward_ios),
          ]),
          style: TextButton.styleFrom(
            backgroundColor: Colors.white,
            onSurface: Colors.grey,
          ),
          onPressed: () => {
            if (Cache().userLoggedIn != null)
              {
                args['personal_data'] = true,
                Navigator.of(context).pushNamed('customerModifyPage', arguments: args),
              }
          },
        ),
      ),
      ListTile(
        leading: Common.badgedIcon(Colors.grey, Icons.arrow_forward_sharp, "Goal"), //Icon(Icons.arrow_forward_sharp),
        subtitle: Text(t("Goal")),
        title: TextButton(
          child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            Text(goal, style: TextStyle(color: Colors.blue)),
            Icon(Icons.arrow_forward_ios),
          ]),
          style: TextButton.styleFrom(
            backgroundColor: Colors.white,
            onSurface: Colors.grey,
          ),
          onPressed: () => {
            if (Cache().userLoggedIn != null)
              {
                args['personal_data'] = true,
                args['bloc'] = accountBloc.customerRepository,
                Navigator.of(context).pushNamed('customerGoalPage', arguments: args),
              }
          },
        ),
      ),
      ListTile(
        leading: Common.badgedIcon(Colors.grey, Icons.perm_contact_cal, "FitnessLevel"), //Icon(Icons.perm_contact_cal),
        subtitle: Text(t("Activity") + " " + t("and") + " " + t("Sport")),
        title: TextButton(
          child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            Text(fitnessLevel, style: TextStyle(color: Colors.blue)),
            Icon(Icons.arrow_forward_ios),
          ]),
          style: TextButton.styleFrom(
            backgroundColor: Colors.white,
            onSurface: Colors.grey,
          ),
          onPressed: () => {
            if (Cache().userLoggedIn != null)
              {
                args['personal_data'] = true,
                args['bloc'] = accountBloc.customerRepository,
                Navigator.of(context).pushNamed('customerFitnessPage', arguments: args),
              }
          },
        ),
      ),
      ListTile(
        leading: Common.badgedIcon(Colors.grey, CustomIcon.people_arrows, "bodyType"), //Icon(CustomIcon.people_arrows),
        subtitle: Text(t("Body Type")),
        title: TextButton(
          style: TextButton.styleFrom(
            backgroundColor: Colors.white,
            onSurface: Colors.grey,
          ),
          child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            Text(t(bodyType), style: TextStyle(color: Colors.blue)),
            Icon(Icons.arrow_forward_ios),
          ]),
          onPressed: () => {
            if (Cache().userLoggedIn != null)
              {
                args['personal_data'] = true,
                args['bloc'] = accountBloc.customerRepository,
                Navigator.of(context).pushNamed('customerBodyTypePage', arguments: args),
              }
          },
        ),
      ),
      devices(context, accountBloc),
      loginOut(context, accountBloc),
      getMyTrainees(context, accountBloc),
    ]);
  }

  ListTile devices(BuildContext context, AccountBloc accountBloc) {
    ListTile element = ListTile();
    element = ListTile(
      leading: Common.badgedIcon(Colors.grey, Icons.device_hub, "customerDevice"),
      subtitle: Text(t("These equipments and devices are available")),
      title: TextButton(
        style: TextButton.styleFrom(
          backgroundColor: Colors.white,
          onSurface: Colors.grey,
        ),
        child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [Text(t("Available Devices"), style: TextStyle(color: Colors.orange)), Icon(Icons.arrow_forward_ios)]),
        onPressed: () => {
          if (Cache().userLoggedIn != null)
            {
              Navigator.of(context).pushNamed('customerExerciseDevicePage'),
            }
        },
      ),
    );
    return element;
  }

  ListTile loginOut(BuildContext context, AccountBloc accountBloc) {
    ListTile element = ListTile();

    String text = "Logout";
    Color buttonColor = Colors.orange;

    if (accountBloc.customerRepository.customer == null || accountBloc.customerRepository.customer!.email == null) {
      text = "Login";
      buttonColor = Colors.blue;
    }

    element = ListTile(
      enabled: true,
      leading: Icon(Icons.input),
      title: TextButton(
        style: TextButton.styleFrom(
          backgroundColor: Colors.white,
          onSurface: Colors.grey,
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Text(t(text), style: TextStyle(color: buttonColor)),
          Icon(Icons.arrow_forward_ios),
        ]),
        onPressed: () => {
          if (accountBloc.loggedIn)
            {
              confirmationDialog(accountBloc),
            }
          else
            {
              accountBloc.add(AccountLogin()),
              Navigator.of(context).pushNamed('login'),
            }
        },
      ),
    );

    return element;
  }

  Widget getMyTrainees(BuildContext context, AccountBloc accountBloc) {
    if (accountBloc.customerRepository.customer == null || accountBloc.customerRepository.customer!.trainer == 0) {
      return ListTile(
        title: Container(),
      );
    }

    if (accountBloc.customerRepository.getTraineesList() == null) {
      return ListTile(
        leading: Icon(Icons.people),
        title: ElevatedButton(
          style: ElevatedButton.styleFrom(
            primary: Colors.white70,
          ),
          onPressed: () => accountBloc.add(AccountGetTrainees()),
          child: Text("See my trainees"),
        ),
      );
    }

    List<Widget> elements = [];
    accountBloc.customerRepository.getTraineesList()!.forEach((element) {
      Customer trainee = element;
      String name = trainee.name!;
      String firstName = trainee.firstname!;
      String nodeName = AppLanguage().appLocal == Locale("en") ? firstName + " " + name : name + " " + firstName;

      bool selected = accountBloc.traineeId == trainee.customerId;

      Widget widget = TextButton(
        style: TextButton.styleFrom(
          padding: EdgeInsets.all(10),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(8)),
            side: BorderSide(width: 2, color: selected ? Colors.blue : Colors.black26),
          ),
        ),
        onPressed: () {
          accountBloc.add(AccountSelectTrainee(traineeId: trainee.customerId!));
          //Navigator.of(context).pushNamed('login');
        },
        child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Text(
            nodeName,
            style: TextStyle(color: selected ? Colors.blue : Colors.black54, fontWeight: selected ? FontWeight.bold : FontWeight.normal),
          ),
          Icon(Icons.arrow_forward_ios),
        ]),
      );
      elements.add(widget);
    });

    return ListTile(
        leading: Icon(Icons.people),
        subtitle: Text("My Trainees"),
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: elements,
        ));
  }

  void confirmationDialog(AccountBloc accountBloc) {
    showCupertinoDialog(
        useRootNavigator: true,
        context: context,
        builder: (_) => CupertinoAlertDialog(
              title: Text(t("Are you sure to logout?")),
              content: Column(children: [
                Divider(),
              ]),
              actions: [
                TextButton(
                  child: Text(t("No")),
                  onPressed: () => Navigator.pop(context),
                ),
                TextButton(
                  child: Text(t("Yes")),
                  onPressed: () => {
                    accountBloc.add(AccountLogout()),
                    Navigator.pop(context),
                  },
                )
              ],
            ));
  }

  String capitalize(String? s) {
    if (s == null || s.isEmpty) {
      return " ";
    }
    return s[0].toUpperCase() + s.substring(1);
  }
}