import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

import '../../../../api/login_api_client.dart';
import '../../../../controllers/http_status_manger/http_status_manger.dart';
import '../../../../controllers/localization/localization.dart';
import '../../../../controllers/providers/api/regular_visits_provider.dart';
import '../../../../controllers/providers/settings/setting_provider.dart';
import '../../../../controllers/providers/user_provider.dart';
import '../../../../models/subtitle.dart';
import '../../../../models/visits/visits_group.dart';
import '../../../../models/visits/visits_search.dart';
import '../../../app_style/colors.dart';
import '../../../widgets/buttons/app_back_button.dart';
import '../../../widgets/buttons/app_button.dart';
import '../../../widgets/buttons/app_icon_button.dart';
import '../../../widgets/loaders/loading_manager.dart';
import '../../../widgets/search/visits_search_bar.dart';
import '../../../widgets/visits/visits_list.dart';
import 'update_visits_group_sheet.dart';

class RegularVisitsPage extends StatefulWidget {
  static const String id = "/Regular-visits";

  const RegularVisitsPage({super.key});
  @override
  _RegularVisitsPageState createState() => _RegularVisitsPageState();
}

class _RegularVisitsPageState extends State<RegularVisitsPage> with TickerProviderStateMixin {
  late RegularVisitsProvider _visitsProvider;
  late UserProvider _userProvider;
  late SettingProvider _settingProvider;
  bool _expandedSearch = false;
  late Subtitle _subtitle;
  @override
  Widget build(BuildContext context) {
    _visitsProvider = Provider.of<RegularVisitsProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _userProvider = Provider.of<UserProvider>(context);
    _subtitle = AppLocalization.of(context)!.subtitle!;
    return Scaffold(
      body: SafeArea(
        child: LoadingManager(
          isLoading: _visitsProvider.isLoading,
          stateCode: _visitsProvider.stateCode,
          onRefresh: () async {
            _visitsProvider.reset();
            //_visitsProvider.visitsSearch = VisitsSearch();
            await _visitsProvider.getVisits(
              user: UserApiClient().user,
              host: _settingProvider.host,
            );
          },
          child: Stack(
            children: [
              Column(
                children: [
                  Container(
                    color: AColors.primaryColor,
                    padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 4),
                    child: Column(
                      children: [
                        Row(
                          children: [
                            ABackButton(),
                            Expanded(
                              child: Center(
                                child: Text(
                                  _subtitle.preventiveMaintenance,
                                  style: Theme.of(context).textTheme.headline6?.copyWith(color: AColors.white, fontStyle: FontStyle.italic),
                                ),
                              ),
                            ),
                            AnimatedSwitcher(
                              duration: Duration(milliseconds: 400),
                              child: AIconButton(
                                key: ValueKey(_expandedSearch),
                                iconData: _expandedSearch ? Icons.keyboard_arrow_up : Icons.search,
                                color: AColors.secondaryColor,
                                buttonSize: 42,
                                backgroundColor: AColors.white,
                                onPressed: () async {
                                  VisitsSearch _temp = await showModalBottomSheet(
                                      context: context,
                                      isScrollControlled: true,
                                      builder: (context) {
                                        return VisitsSearchDialog(
                                          initialSearchValue: _visitsProvider.visitsSearch!,
                                          onSearch: (VisitsSearch) {},
                                        );
                                      });
                                  _visitsProvider.visitsSearch?.fromSearch(_temp);
                                  _visitsProvider.reset();
                                  setState(() {});
                                },
                              ),
                            ),
                            SizedBox(
                              width: 16,
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                  Visibility(
                    visible: _visitsProvider.visitsSearch?.toSearchString().isNotEmpty ?? false,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: AButton(
                        text: _subtitle.clearSearch,
                        onPressed: () {
                          _visitsProvider.visitsSearch = VisitsSearch();
                          _visitsProvider.reset();
                          setState(() {});
                        },
                      ),
                    ),
                  ),
                  Expanded(
                    child: VisitsList(
                      nextPage: _visitsProvider.nextPage,
                      onLazyLoad: () async {
                        await _visitsProvider.getVisits(
                          user: UserApiClient().user!,
                          host: _settingProvider.host ?? "",
                        );
                      },
                      onEditGroup: (visits) async {
                        VisitsGroup? group = await showModalBottomSheet(
                          isScrollControlled: true,
                          context: context,
                          builder: (context) {
                            return UpdateVisitsGroupSheet(
                              visits: visits,
                              title: _subtitle.updateRegularVisits,
                            );
                          },
                        ) as VisitsGroup?;
                        if (group != null) {
                          showDialog<void>(
                            context: context,
                            barrierDismissible: false,
                            builder: (BuildContext context) {
                              return CupertinoAlertDialog(
                                title: Text(_subtitle.updatingDots),
                                content: Center(child: CircularProgressIndicator()),
                              );
                            },
                          );
                          int status = await _visitsProvider.updateGroupOfVisits(user: UserApiClient().user!, host: _settingProvider.host ?? "", group: group);
                          Navigator.of(context).pop();
                          if (status >= 200 && status < 300) {
                            Fluttertoast.showToast(
                              msg: _subtitle.regularVisitsUpdatedSuccessfully,
                              toastLength: Toast.LENGTH_LONG,
                              gravity: ToastGravity.BOTTOM,
                            );
                          } else {
                            Fluttertoast.showToast(
                              msg: HttpStatusManger.getStatusMessage(status: status, subtitle: _subtitle),
                              toastLength: Toast.LENGTH_LONG,
                              gravity: ToastGravity.BOTTOM,
                            );
                          }
                        }
                      },
                      visits: _visitsProvider.visits,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
