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 '../../../../../models/pantry/pentry.dart';
import '../../../../../models/subtitle.dart';
import '../../../../../models/visits/visit.dart';
import '../../../../widgets/buttons/app_small_button.dart';
import '../../../../widgets/loaders/loading_manager.dart';
import '../../../../widgets/pentry/pentry_calibration_tool_form.dart';
import '../../../../widgets/pentry/pentry_info_form.dart';
import '../../../../widgets/pentry/pentry_pm_kit_form.dart';
import '../../../../widgets/pentry/pentry_ppm_check_list_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;
  late SettingProvider _settingProvider;
  late RegularVisitsProvider _regularVisitsProvider;
  Pentry? _pentry;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  late final TabController _tabController;

  _onSubmit() async {
    _validate = true;

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

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

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

  @override
  void initState() {
    _pentry = widget.pentry;
    _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;
    _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: "PK Kits",
                        ),
                        Tab(
                          text: "Pentry",
                        ),
                      ]),
                ),
              ),
              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,
                              ),
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
