import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/localization/localization.dart';
import 'package:test_sa/controllers/providers/api/regular_visits_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_provider.dart';
import 'package:test_sa/models/pantry/calibration_tools.dart';
import 'package:test_sa/models/pantry/pentry.dart';
import 'package:test_sa/models/pantry/pm_kit.dart';
import 'package:test_sa/models/pantry/ppm_check_list.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/models/visits/visit.dart';
import 'package:test_sa/views/widgets/buttons/app_small_button.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/pentry/pentry_calibration_tool_form.dart';
import 'package:test_sa/views/widgets/pentry/pentry_pm_kit_form.dart';
import 'package:test_sa/views/widgets/pentry/pentry_ppm_check_list_form.dart';

import '../../../../widgets/pentry/pentry_info_form.dart';

class EditPentry extends StatefulWidget {
  final Pentry pentry;
  final Visit visit;
  const EditPentry({Key key, this.pentry, this.visit}) : super(key: key);

  @override
  State<EditPentry> createState() => _EditPentryState();
}

class _EditPentryState extends State<EditPentry> with SingleTickerProviderStateMixin {
  bool _isLoading = false;
  bool _validate = false;
  Subtitle _subtitle;
  UserProvider _userProvider;
  SettingProvider _settingProvider;
  RegularVisitsProvider _regularVisitsProvider;
  Pentry _pentry;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  TabController _tabController;
  _onSubmit() async {
    _validate = true;

    if (!_pentry.validate()) {
      setState(() {});
      return;
    }

    _isLoading = true;
    setState(() {});

    int status = await _regularVisitsProvider.updatePentry(user: _userProvider.user, host: _settingProvider.host, pentry: _pentry, visit: widget.visit);
    _isLoading = false;
    setState(() {});
    if (status >= 200 && status < 300) {
      Fluttertoast.showToast(
        msg: _subtitle.requestCompleteSuccessfully,
      );
      Navigator.of(context).pop();
      Navigator.of(context).pop();
    } else {
      // String errorMessage = HttpStatusManger.getStatusMessage(
      //     status: status, subtitle: _subtitle);
      // Fluttertoast.showToast(
      //   msg: errorMessage,
      // );
    }
  }

  @override
  void initState() {
    _pentry = widget.pentry.copyWith();
    if (_pentry.pmKits.isEmpty) _pentry.pmKits.add(PMKit());
    if (_pentry.calibrationTools.isEmpty) _pentry.calibrationTools.add(CalibrationTool());
    if (_pentry.ppmCheckLists.isEmpty) _pentry.ppmCheckLists.add(PPMCheckList());
    _tabController = TabController(length: 4, vsync: this);
    super.initState();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _subtitle = AppLocalization.of(context).subtitle;
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _regularVisitsProvider = Provider.of<RegularVisitsProvider>(context);
    return Scaffold(
      key: _scaffoldKey,
      body: SafeArea(
        child: LoadingManager(
            isLoading: _isLoading,
            isFailedLoading: false,
            stateCode: 200,
            onRefresh: () async {},
            child: Column(
              children: [
                Material(
                  color: Theme.of(context).colorScheme.primary,
                  child: Padding(
                    padding: const EdgeInsets.all(2.0),
                    child: TabBar(
                      controller: _tabController,
                      isScrollable: true,
                      onTap: (index) {
                        setState(() {});
                      },
                      tabs: const [
                        Tab(
                          text: "PPM Check List",
                        ),
                        Tab(
                          text: "Calibration Tools",
                        ),
                        Tab(
                          text: "PM Kits",
                        ),
                        Tab(
                          text: "PM Entry",
                        ),
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: Stack(
                    children: [
                      TabBarView(
                        physics: const NeverScrollableScrollPhysics(),
                        controller: _tabController,
                        children: [
                          PentryPPMCheckListForm(
                            models: _pentry.ppmCheckLists,
                            enableValidate: _validate,
                          ),
                          PentryCalibrationToolForm(
                            models: _pentry.calibrationTools,
                            enableValidate: _validate,
                          ),
                          PentryPMKitForm(
                            models: _pentry.pmKits,
                            enableValidate: _validate,
                          ),
                          PentryInfoForm(
                            model: _pentry,
                            enableValidate: _validate,
                          ),
                        ],
                      ),
                      Align(
                        alignment: Alignment.bottomCenter,
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Row(
                            children: [
                              if (_tabController.index != 0)
                                ASmallButton(
                                  text: _subtitle.back,
                                  onPressed: () {
                                    _tabController.animateTo(
                                      _tabController.index - 1,
                                    );
                                    setState(() {});
                                  },
                                ),
                              const Spacer(),
                              if (_tabController.index != _tabController.length - 1)
                                ASmallButton(
                                  text: _subtitle.next,
                                  onPressed: () {
                                    _tabController.animateTo(
                                      _tabController.index + 1,
                                    );
                                    setState(() {});
                                  },
                                ),
                              if (_tabController.index == _tabController.length - 1)
                                ASmallButton(
                                  text: _subtitle.update,
                                  onPressed: _onSubmit,
                                ),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            )),
      ),
    );
  }
}
