import 'dart:convert';
import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mnemo_cards/admin/add_card.dart';
import 'package:mnemo_cards/admin/add_user.dart';
import 'package:mnemo_cards/admin/admin_api.dart';
import 'package:mnemo_cards/di/injector.dart';
import 'package:mnemo_cards/di/locator.dart';
import 'package:mnemo_cards/managers/repository/dio_provider.dart';
import 'package:mnemo_cards/widgets/header.dart';
import 'package:mnemo_cards_common/mnemo_cards_common.dart';

import '../main.dart';

class AllUsers extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _AllUsersState();

  const AllUsers();
}

class _AllUsersState extends State<AllUsers> {
  static List<String> ids = [];
  static Set<UserDto> users = {};
  static String filter = '';
  static UserDto? _currentUser;
  static String? _currentId;

  bool get selectingMode => false; //_selectedCards.isNotEmpty;

  Dio get dio => getIt.get<DioProvider>().dio;

  AdminApi get api => getIt.get<AdminApi>();

  Future<void> loadUsers() async {
    var loadingIds = ids.toList();
    users.clear();
    while (loadingIds.isNotEmpty) {
      try {
        final ids = loadingIds.take(10).toList();
        loadingIds.removeRange(0, ids.length);
        final usersPage = await api.getUsers(ids);
        users.addAll(usersPage);
        setState(() {});
      } catch (e) {
        print(e);
      }
    }
  }

  Future<void> loadIds() async {
    ids = await api.getUserIds();
    setState(() {});
  }

  Future<void> loadCurrentUser() async {
    if (_currentId != null) {
      _currentUser = (await api.getUsers([_currentId!])).firstOrNull;
      setState(() {});
    }
  }

  void clearCurrentUser() {
    _currentId = null;
    _currentUser = null;
    setState(() {});
  }

  Future<void> editUser(UserDto user) async {
    final result = await api.editUser(user);
    if (!result) {
      ScaffoldMessenger.of(scaffoldKey.currentContext!).showSnackBar(SnackBar(
        content: Text('ERROR'),
      ));
    } else {
      ScaffoldMessenger.of(scaffoldKey.currentContext!).showSnackBar(SnackBar(
        content: Text('Success!!!'),
      ));
    }
  }

  List<UserDto> buildUsersList() {
    final filteredCards = users.where((dto) {
      final filterOk = filter.isEmpty ||
          dto.name.toString().toLowerCase().contains(filter) ||
          dto.id.toString().toLowerCase().contains(filter) ||
          dto.packs.any((p) => p.toLowerCase().contains(filter));
      return filterOk;
    });
    return filteredCards.toList();
  }

  @override
  Widget build(BuildContext context) {
    final filteredCards = buildUsersList();
    return Scaffold(
      body: SafeArea(
        child: Stack(
          children: [
            ListView.builder(itemBuilder: (context, index) {
              if (index == 0)
                return Container(
                  height: 270,
                  child: Column(
                    children: [
                      Header(
                        _currentId == null
                            ? 'Все'
                            : _currentUser?.name ?? 'Пак ${_currentUser?.id}',
                        subtitle: filteredCards.isEmpty
                            ? 'Нет пользователей'
                            : '${filteredCards.length} пользователя',
                        hasPopButton: true,
                        trail: IconButton(
                            onPressed: () async {
                              setState(() {});
                              await loadIds();
                              await loadUsers();
                            },
                            icon: Icon(Icons.sync)),
                      ),
                      dropdownButton(context),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextField(
                          decoration: InputDecoration(hintText: 'Поиск'),
                          onChanged: (v) {
                            if (filter != v.toLowerCase()) {
                              filter = v.toLowerCase();
                              setState(() {});
                            }
                          },
                        ),
                      ),
                      // Expanded(
                      //   child: GestureDetector(
                      //     onTap: () => EditUser(null, api).addCard(context),
                      //     child: Container(
                      //       color: Colors.green.withOpacity(0.1),
                      //       alignment: Alignment.center,
                      //       child: Icon(Icons.add, size: 30),
                      //     ),
                      //   ),
                      // ),
                    ],
                  ),
                );
              else if (filteredCards.length > index - 1)
                return userWidget(filteredCards[index - 1]);
              else
                return null;
            }),
            if (selectingMode)
              Align(
                alignment: Alignment.bottomCenter,
                child: Container(
                  height: 100,
                  padding: EdgeInsets.all(10.0),
                  alignment: Alignment.center,
                  child: Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          setState(() {});
                        },
                        child: Container(
                          color: Colors.blue,
                          padding: EdgeInsets.all(8.0),
                          child: Row(
                            children: [Icon(Icons.clear)],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget userWidget(UserDto user) {
    void toggleSelect() {
      final id = user.id.toString();
      setState(() {});
    }

    return GestureDetector(
      onTap: () {
        if (selectingMode) {
          toggleSelect();
        } else {
          EditUser(user, api).addUser(context);
        }
      },
      onLongPress: toggleSelect,
      child: _User(user, api, false),
    );
  }

  Widget dropdownButton(BuildContext context) {
    return Row(
      children: [
        IconButton(
          onPressed: null,
          icon: _currentUser == null ? Icon(Icons.add) : Icon(Icons.edit),
        ),
      ],
    );
  }
}

class _User extends StatelessWidget {
  final UserDto userDto;
  final AdminApi api;
  final bool selected;

  _User(this.userDto, this.api, this.selected);

  @override
  Widget build(BuildContext context) {
    final isCurrent = locator.userManager.userStateHolder.user?.id == userDto.id;
    return ListTile(
      title: Text('${userDto.id}${isCurrent ? ' (you)' : ''}'),
      subtitle: Text(userDto.name ?? ''),
      trailing: userDto.admin ? Text('admin') : null,
    );
  }
}
