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/gas_refill_provider.dart';
import '../../../../controllers/providers/settings/setting_provider.dart';
import '../../../../controllers/providers/user_provider.dart';
import '../../../../controllers/validator/validator.dart';
import '../../../../models/gas_refill/gas_refill_details.dart';
import '../../../../models/gas_refill/gas_refill_model.dart';
import '../../../../models/subtitle.dart';
import '../../../../models/user.dart';
import '../../../app_style/sizing.dart';
import '../../../widgets/app_text_form_field.dart';
import '../../../widgets/buttons/app_button.dart';
import '../../../widgets/gas_refill/gas_refill_create_details_item.dart';
import '../../../widgets/loaders/loading_manager.dart';
import '../../../widgets/status/gas_refill/gas_type.dart';
import '../../../widgets/titles/app_sub_title.dart';

class RequestGasRefill extends StatefulWidget {
  static const String id = "/request-gas-refill";
  const RequestGasRefill({Key? key}) : super(key: key);

  @override
  State<RequestGasRefill> createState() => _RequestGasRefillState();
}

class _RequestGasRefillState extends State<RequestGasRefill> {
  bool _isLoading = false;
  bool _validate = false;
  Subtitle? _subtitle;
  UserProvider? _userProvider;
  SettingProvider? _settingProvider;
  GasRefillProvider? _gasRefillProvider;
  GasRefillDetails _currentDetails = GasRefillDetails(model: null);
  final TextEditingController _requestedQuantityController = TextEditingController();
  final GasRefillModel _formModel = GasRefillModel(details: []);
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey _DetailsKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void setState(VoidCallback fn) {
    if (mounted) super.setState(() {});
  }

  _onSubmit() async {
    if ((_formModel.details?.isEmpty ?? false)) {
      if (!_addNewModel()) return;
    }

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

    int? status = await _gasRefillProvider?.createModel(
      user: UserApiClient().user ?? User(),
      host: _settingProvider?.host ?? "",
      model: _formModel,
    );
    _isLoading = false;
    setState(() {});
    if (status != null && status >= 200 && status < 300) {
      Fluttertoast.showToast(
        msg: _subtitle?.requestCompleteSuccessfully ?? "",
      );
      Navigator.of(context).pop();
    } else {
      String errorMessage = HttpStatusManger.getStatusMessage(status: status, subtitle: _subtitle);
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(errorMessage),
      ));
    }
  }

  bool _addNewModel() {
    _validate = true;
    if (!(_formKey.currentState?.validate() ?? false)) {
      setState(() {});
      return false;
    }
    _formKey.currentState?.save();
    if (!_currentDetails.validate()) {
      setState(() {});
      return false;
    }

    _formModel.details?.insert(0, _currentDetails);
    _validate = false;
    Scrollable.ensureVisible(_DetailsKey.currentContext!);
    _requestedQuantityController.clear();
    _currentDetails = GasRefillDetails(model: null);
    setState(() {});
    return true;
  }

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

  @override
  Widget build(BuildContext context) {
    _subtitle = AppLocalization.of(context)?.subtitle;
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _gasRefillProvider = Provider.of<GasRefillProvider>(context, listen: false);
    return Scaffold(
      key: _scaffoldKey,
      body: Form(
        key: _formKey,
        child: SafeArea(
          child: LoadingManager(
            isLoading: _isLoading,
            isFailedLoading: false,
            stateCode: 200,
            onRefresh: () async {},
            child: SingleChildScrollView(
              padding: EdgeInsets.all(12 * AppStyle.getScaleFactor(context)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Center(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        "Request Gas Refill",
                        style: Theme.of(context).textTheme.headline5?.copyWith(color: Theme.of(context).primaryColor, fontSize: 28, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                  // const SizedBox(height: 4,),
                  // ASubTitle(_subtitle.title),
                  // if(_validate && _formModel.title == null)
                  // ASubTitle(_subtitle.requiredWord,color: Colors.red,),
                  // SizedBox(height: 4,),
                  // ATextFormField(
                  //   initialValue: _formModel?.title,
                  //   textAlign: TextAlign.center,
                  //   style: Theme.of(context).textTheme.subtitle1,
                  //   textInputType: TextInputType.text,
                  //   onSaved: (value){
                  //     _formModel.title = value;
                  //   },
                  // ),
                  // // const SizedBox(height: 8,),
                  // ASubTitle(_subtitle.status),
                  // if(_validate && _formModel.status == null)
                  //   ASubTitle(_subtitle.requiredWord,color: Colors.red,),
                  // const SizedBox(height: 4,),
                  // GasStatusMenu(
                  //   initialValue: _formModel.status,
                  //   onSelect: (status){
                  //     _formModel.status = status;
                  //   },
                  // ),
                  // const SizedBox(height: 8,),
                  // Divider(color: Theme.of(context).colorScheme.primary,),
                  const SizedBox(
                    height: 4,
                  ),
                  const ASubTitle("Type"),
                  if (_validate && _currentDetails.type == null)
                    ASubTitle(
                      _subtitle?.requiredWord ?? "",
                      color: Colors.red,
                    ),
                  const SizedBox(
                    height: 4,
                  ),
                  GasTypeMenu(
                    initialValue: _currentDetails.type,
                    onSelect: (status) {
                      _currentDetails.type = status;
                    },
                  ),

                  // const SizedBox(height: 8,),
                  // const ASubTitle("Cylinder Size"),
                  // if(_validate && _currentDetails.cylinderSize == null)
                  //   ASubTitle(_subtitle.requiredWord,color: Colors.red,),
                  // const SizedBox(height: 4,),
                  // GasCylinderSizeMenu(
                  //   initialValue: _currentDetails.cylinderSize,
                  //   onSelect: (status){
                  //     _currentDetails.cylinderSize = status;
                  //   },
                  // ),
                  const SizedBox(
                    height: 8,
                  ),
                  ASubTitle(_subtitle?.quantity ?? ""),
                  if (_validate && _currentDetails.requestedQuantity == null)
                    ASubTitle(
                      _subtitle?.requiredWord ?? "",
                      color: Colors.red,
                    ),
                  SizedBox(
                    height: 4,
                  ),
                  ATextFormField(
                    initialValue: (_currentDetails?.requestedQuantity ?? "").toString(),
                    textAlign: TextAlign.center,
                    controller: _requestedQuantityController,
                    style: Theme.of(context).textTheme.subtitle1,
                    validator: (value) => Validator.isNumeric(value!) ? '' : "allow numbers only",
                    textInputType: TextInputType.number,
                    onSaved: (value) {
                      _currentDetails.requestedQuantity = int.tryParse(value!);
                    },
                  ),
                  const SizedBox(height: 16),
                  AButton(
                    text: _subtitle?.add ?? "",
                    onPressed: _addNewModel,
                  ),
                  if ((_formModel.details?.isNotEmpty ?? false)) const ASubTitle("Gas Requests"),
                  ListView.builder(
                      key: _DetailsKey,
                      shrinkWrap: true,
                      physics: const ClampingScrollPhysics(),
                      itemCount: _formModel.details?.length,
                      itemBuilder: (context, index) {
                        final model = _formModel.details![index];
                        return GasRefillCreateDetailsItem(
                          model: model,
                          onDelete: () {
                            _formModel.details?.remove(model);
                            setState(() {});
                          },
                        );
                      }),
                  const SizedBox(height: 16),
                  AButton(
                    text: _subtitle?.submit ?? "",
                    onPressed: _onSubmit,
                  ),
                  const SizedBox(
                    height: 100,
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
