import 'dart:math';

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

import '../../../../api/login_api_client.dart';
import '../../../../controllers/providers/api/status_drop_down/report/service_report_last_calls_provider.dart';
import '../../../../controllers/providers/api/status_drop_down/report/service_report_status_provider.dart';
import '../../../../controllers/providers/settings/setting_provider.dart';
import '../../../../controllers/providers/user_provider.dart';
import '../../../../models/lookup.dart';
import '../../../../models/service_report.dart';
import '../../loaders/loading_manager.dart';
import '../single_status_menu.dart';

class ServiceReportStatusMenu extends StatefulWidget {
  final Function(Lookup?) onSelect;
  final ServiceReport? report;

  const ServiceReportStatusMenu({
    Key? key,
    required this.onSelect,
    this.report,
  }) : super(key: key);

  @override
  State<ServiceReportStatusMenu> createState() => _ServiceReportStatusMenuState();
}

class _ServiceReportStatusMenuState extends State<ServiceReportStatusMenu> {
  bool firstTime = true;

  @override
  Widget build(BuildContext context) {
    SettingProvider settingProvider = Provider.of<SettingProvider>(context);
    UserProvider userProvider = Provider.of<UserProvider>(context);
    ServiceReportStatusProvider menuProvider = Provider.of<ServiceReportStatusProvider>(context);
    ServiceReportLastCallsProvider callsLastSituationsProvider = Provider.of<ServiceReportLastCallsProvider>(context, listen: false);
    if (firstTime) {
      callsLastSituationsProvider.reset();

      firstTime = false;
    }
    return LoadingManager(
        isLoading: menuProvider.isLoading == true || callsLastSituationsProvider.isLoading == true,
        isFailedLoading: menuProvider.statuses == null || callsLastSituationsProvider.calls == null,
        stateCode: menuProvider.stateCode == null || callsLastSituationsProvider.stateCode == null ? null : max(menuProvider.stateCode ?? 0, callsLastSituationsProvider.stateCode ?? 0),
        onRefresh: () async {
          if (menuProvider.stateCode == null) {
            menuProvider.reset();
            await menuProvider.getTypes(
              user: UserApiClient().user,
              host: settingProvider.host,
            );
          }
          await callsLastSituationsProvider.getCalls(user: UserApiClient().user, host: settingProvider.host, serviceStatus: widget.report?.status?.id.toString());
        },
        child: SingleStatusMenu(
          statuses: menuProvider.statuses,
          initialStatus: widget.report?.status,
          onSelect: (status) {
            callsLastSituationsProvider.getCalls(user: UserApiClient().user, host: settingProvider.host, serviceStatus: status?.id.toString());
            widget.report?.callLastSituation = null;
            widget.onSelect(status);
          },
        ));
  }
}
