import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/http_status_manger.dart';
import 'package:test_sa/controllers/providers/api/gas_refill_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/controllers/validator/validator.dart';
import 'package:test_sa/models/gas_refill/gas_refill_details.dart';
import 'package:test_sa/models/gas_refill/gas_refill_model.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/models/timer_model.dart';
import 'package:test_sa/views/app_style/sizing.dart';
import 'package:test_sa/views/widgets/app_text_form_field.dart';
import 'package:test_sa/views/widgets/buttons/app_button.dart';
import 'package:test_sa/views/widgets/date_and_time/time_picker.dart';
import 'package:test_sa/views/widgets/gas_refill/building_type_menu.dart';
import 'package:test_sa/views/widgets/gas_refill/department_type_menu.dart';
import 'package:test_sa/views/widgets/gas_refill/floor_type_menu.dart';
import 'package:test_sa/views/widgets/gas_refill/gas_refill_create_details_item.dart';
import 'package:test_sa/views/widgets/hospitals/hospital_auto_complete_field_new.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/status/gas_refill/gas_cylinder_size.dart';
import 'package:test_sa/views/widgets/status/gas_refill/gas_cylinder_type.dart';
import 'package:test_sa/views/widgets/status/gas_refill/gas_status.dart';
import 'package:test_sa/views/widgets/status/gas_refill/gas_type.dart';
import 'package:test_sa/views/widgets/titles/app_sub_title.dart';

import '../../../../controllers/localization/localization.dart';
import '../../../../controllers/providers/api/hospitals_provider.dart';
import '../../../../models/enums/user_types.dart';
import '../../../widgets/e_signature/e_signature.dart';
import '../../../widgets/timer/app_timer.dart';

class RequestGasRefill extends StatefulWidget {
  static const String id = "/request-gas-refill";
  final GasRefillModel gasRefillModel;
  const RequestGasRefill({this.gasRefillModel, 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();
  final TextEditingController _requestedQuantityController = TextEditingController();
  final TextEditingController _deliveredQuantityController = TextEditingController();
  GasRefillModel _formModel = GasRefillModel(details: []);
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey _DetailsKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  bool _firstTime = true;

  @override
  void initState() {
    super.initState();
    if (widget.gasRefillModel != null) {
      _formModel = widget.gasRefillModel;
    }
  }

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

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

    _isLoading = true;
    setState(() {});
    if (widget.gasRefillModel != null) {
      if (!_formModel.validate()) {
        _isLoading = false;
        setState(() {});
        return;
      }
    }

    int status = widget.gasRefillModel == null
        ? await _gasRefillProvider.createModel(
            user: _userProvider.user,
            host: _settingProvider.host,
            model: _formModel,
          )
        : await _gasRefillProvider.updateModel(
            user: _userProvider.user,
            host: _settingProvider.host,
            oldModel: widget.gasRefillModel,
            newModel: _formModel,
          );
    _isLoading = false;
    setState(() {});
    if (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()) {
      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();
    _deliveredQuantityController.clear();
    _currentDetails = GasRefillDetails();
    setState(() {});
    return true;
  }

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

  @override
  Widget build(BuildContext context) {
    _subtitle = AppLocalization.of(context).subtitle;
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    if (_gasRefillProvider == null) {
      _gasRefillProvider = Provider.of<GasRefillProvider>(context, listen: false);
      _gasRefillProvider.reset();
    }
    if (_firstTime) {
      if (widget.gasRefillModel != null) {
        _formModel.status = widget.gasRefillModel?.status ?? const Lookup(value: 0);
        _gasRefillProvider.expectedDateTime = _formModel.expectedDate;
        _gasRefillProvider.timer = TimerModel(startAt: widget.gasRefillModel?.startDate, endAt: widget.gasRefillModel?.endDate);
      } else {
        _gasRefillProvider.timer = null;
      }
      HospitalsProvider().getHospitalsListByVal(searchVal: _userProvider.user?.clientName).then((value) {
        _gasRefillProvider.hospital = value?.firstWhere((element) => element.name == _userProvider.user?.clientName, orElse: () => null);
        _gasRefillProvider.building = _gasRefillProvider.hospital?.buildings?.firstWhere((element) => element.name == widget.gasRefillModel?.building?.name, orElse: () => null);
        _gasRefillProvider.floor = _gasRefillProvider.building?.floors?.firstWhere((element) => element.name == widget.gasRefillModel?.floor?.name, orElse: () => null);
        _gasRefillProvider.department = _gasRefillProvider.floor?.departments?.firstWhere((element) => element.name == widget.gasRefillModel?.department?.departmentName, orElse: () => null);
        _firstTime = false;
        setState(() {});
      });
    }
    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(
                        "${widget.gasRefillModel == null ? "Request" : "Update"} 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 ?? const Lookup(value: 0),
                    enabled: widget.gasRefillModel != null,
                    onSelect: (status) {
                      _formModel.status = status;
                    },
                  ),
                  const SizedBox(
                    height: 8,
                  ),
                  Divider(
                    color: Theme.of(context).colorScheme.primary,
                  ),
                  const SizedBox(
                    height: 4,
                  ),
                  HospitalAutoCompleteField(
                    enabled: false,
                    initialValue: _gasRefillProvider.hospital?.name,
                    // onSave: (value){
                    //   _search.hospital = value;
                    // },
                    onSearch: (value) {
                      _gasRefillProvider.hospital = value;
                      _gasRefillProvider.building = null;
                      _gasRefillProvider.floor = null;
                      _gasRefillProvider.department = null;
                      setState(() {});
                    },
                  ),
                  const SizedBox(
                    height: 8,
                  ),
                  BuildingTypeMenu(
                    initialValue: _gasRefillProvider?.building,
                    building: _gasRefillProvider?.hospital?.buildings,
                    enabled: widget.gasRefillModel == null,
                    onSelect: (status) {
                      _gasRefillProvider.building = status;
                      setState(() {});
                    },
                  ),
                  const SizedBox(height: 8),
                  FloorTypeMenu(
                    initialValue: _gasRefillProvider?.floor,
                    floors: _gasRefillProvider?.building?.floors,
                    enabled: widget.gasRefillModel == null,
                    onSelect: (status) {
                      _gasRefillProvider.floor = status;
                      setState(() {});
                    },
                  ),
                  const SizedBox(height: 8),
                  DepartmentTypeMenu(
                    initialValue: _gasRefillProvider?.department,
                    departments: _gasRefillProvider?.floor?.departments,
                    enabled: widget.gasRefillModel == null,
                    onSelect: (status) {
                      _gasRefillProvider.department = status;
                      setState(() {});
                    },
                  ),
                  const SizedBox(height: 8),
                  if (widget.gasRefillModel != null) ASubTitle(_subtitle.workingHours),
                  if (widget.gasRefillModel != null) const SizedBox(height: 8),
                  if (widget.gasRefillModel != null)
                    Row(
                      children: [
                        Expanded(
                          child: AppTimer(
                            timer: _gasRefillProvider.timer,
                            onChange: (timer) async {
                              _gasRefillProvider.timer = timer;
                              _formModel.workingHours = num.tryParse((((timer?.durationInSecond ?? 0) / 60) / 60)?.toStringAsFixed(2) ?? "0");
                              return true;
                            },
                          ),
                        ),
                      ],
                    ),
                  const SizedBox(height: 8),
                  if (_userProvider.user?.type == UsersTypes.normal_user || widget.gasRefillModel != null)
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        const ASubTitle("Expected Date"),
                        SizedBox(
                          height: 8 * AppStyle.getScaleFactor(context),
                        ),
                        ADateTimePicker(
                          date: _gasRefillProvider.expectedDateTime,
                          from: DateTime.now().subtract(const Duration(days: 365)),
                          to: DateTime.now().add(const Duration(days: 365)),
                          onDateTimePicker: (date) {
                            _gasRefillProvider.expectedDateTime = date;
                            _formModel.expectedDate = _gasRefillProvider.expectedDateTime;
                            setState(() {});
                          },
                        ),
                      ],
                    ),
                  // if (_userProvider.user?.type == UsersTypes.engineer)
                  //   Column(
                  //     children: [
                  //       Row(
                  //         children: [
                  //           Expanded(
                  //             child: Column(
                  //               crossAxisAlignment: CrossAxisAlignment.stretch,
                  //               children: [
                  //                 const ASubTitle("Start of Work"),
                  //                 SizedBox(
                  //                   height: 8 * AppStyle.getScaleFactor(context),
                  //                 ),
                  //                 ADateTimePicker(
                  //                   date: _gasRefillProvider.startDate,
                  //                   from: DateTime.now().subtract(const Duration(days: 365)),
                  //                   to: DateTime.now().add(const Duration(days: 365)),
                  //                   onDateTimePicker: (date) {
                  //                     _gasRefillProvider.startDate = date;
                  //                     setState(() {});
                  //                   },
                  //                 ),
                  //               ],
                  //             ),
                  //           ),
                  //           const SizedBox(width: 8),
                  //           Expanded(
                  //             child: Column(
                  //               crossAxisAlignment: CrossAxisAlignment.stretch,
                  //               children: [
                  //                 const ASubTitle("End of Work"),
                  //                 SizedBox(
                  //                   height: 8 * AppStyle.getScaleFactor(context),
                  //                 ),
                  //                 ADateTimePicker(
                  //                   date: _gasRefillProvider.endDate,
                  //                   from: DateTime.now().subtract(const Duration(days: 365)),
                  //                   to: DateTime.now().add(const Duration(days: 365)),
                  //                   onDateTimePicker: (date) {
                  //                     _gasRefillProvider.endDate = date;
                  //                     setState(() {});
                  //                   },
                  //                 ),
                  //               ],
                  //             ),
                  //           ),
                  //         ],
                  //       ),
                  //       const SizedBox(height: 8),
                  //       ASubTitle(_subtitle.workingHours),
                  //       const SizedBox(height: 4),
                  //       ATextFormField(
                  //         initialValue: null,
                  //         textAlign: TextAlign.center,
                  //         hintText: _gasRefillProvider.startDate == null
                  //             ? "0"
                  //             : ((_gasRefillProvider.endDate?.difference(_gasRefillProvider.startDate)?.inMinutes ?? 0) / 60)?.toStringAsFixed(2)?.toString() ?? "0",
                  //         enable: false,
                  //         style: Theme.of(context).textTheme.subtitle1,
                  //         validator: (value) => Validator.isNumeric(value) ? null : _subtitle.requiredWord,
                  //         textInputType: TextInputType.number,
                  //         onSaved: (value) {
                  //           //  _serviceReport.workHours = value;
                  //         },
                  //       ),
                  //     ],
                  //   ),
                  if (widget.gasRefillModel == null)
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(height: 8),
                        Divider(color: Theme.of(context).colorScheme.primary),
                        const SizedBox(height: 4),
                        const ASubTitle("Gas 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,
                        ),
                        const ASubTitle("Cylinder Type"),
                        if (_validate && _currentDetails.cylinderSize == null)
                          ASubTitle(
                            _subtitle.requiredWord,
                            color: Colors.red,
                          ),
                        const SizedBox(
                          height: 4,
                        ),
                        GasCylinderTypesMenu(
                          initialValue: _currentDetails.cylinderType,
                          onSelect: (status) {
                            _currentDetails.cylinderType = status;
                          },
                        ),
                        const SizedBox(
                          height: 8,
                        ),
                        ASubTitle(_subtitle.requestedQuantity),
                        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) ? null : "allow numbers only",
                          textInputType: TextInputType.number,
                          onChange: (value) {
                            _currentDetails?.requestedQuantity = double.tryParse(value);
                          },
                        ),
                        if (widget.gasRefillModel != null) const SizedBox(height: 16),
                        if (widget.gasRefillModel != null) ASubTitle(_subtitle.deliveredQuantity),
                        if (widget.gasRefillModel != null && _validate && _currentDetails?.deliveredQuantity == null)
                          ASubTitle(
                            _subtitle.requiredWord,
                            color: Colors.red,
                          ),
                        if (widget.gasRefillModel != null) const SizedBox(height: 4),
                        if (widget.gasRefillModel != null)
                          ATextFormField(
                            initialValue: (_currentDetails?.deliveredQuantity ?? "").toString(),
                            textAlign: TextAlign.center,
                            controller: _deliveredQuantityController,
                            style: Theme.of(context).textTheme.subtitle1,
                            validator: (value) => Validator.isNumeric(value) ? null : "allow numbers only",
                            textInputType: TextInputType.number,
                            onChange: (value) {
                              _currentDetails?.deliveredQuantity = double.tryParse(value);
                            },
                          ),
                        const SizedBox(height: 16),
                        AButton(
                          text: _subtitle.add,
                          onPressed: _addNewModel,
                        ),
                      ],
                    ),
                  const SizedBox(height: 16),
                  if (_formModel.details.isNotEmpty) 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(
                          isUpdate: widget.gasRefillModel != null,
                          model: model,
                          onPressed: () {
                            if (widget.gasRefillModel != null) {
                              model.selectedForEditing = !(model.selectedForEditing ?? false);
                            }
                            if (widget.gasRefillModel == null) {
                              _formModel.details.remove(model);
                            }
                            setState(() {});
                          },
                        );
                      }),
                  if (widget.gasRefillModel != null) const SizedBox(height: 16),
                  if (widget.gasRefillModel != null) const ASubTitle("Nurse Signature"),
                  if (widget.gasRefillModel != null)
                    ESignature(
                      oldSignature: _formModel.signatureNurse,
                      newSignature: _formModel.localNurseSignature,
                      onChange: (signature) {
                        if (signature == null || signature.isEmpty) {
                          return;
                        }
                        _formModel.localNurseSignature = signature;
                        _formModel.signatureNurse = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
                      },
                    ),
                  if (widget.gasRefillModel != null)
                    const SizedBox(
                      height: 8,
                    ),
                  if (widget.gasRefillModel != null) const ASubTitle("Engineer Signature"),
                  if (widget.gasRefillModel != null)
                    ESignature(
                      oldSignature: _formModel.signatureEngineer,
                      newSignature: _formModel.localNurseSignature,
                      onChange: (signature) {
                        if (signature == null || signature.isEmpty) {
                          return;
                        }
                        _formModel.localNurseSignature = signature;
                        _formModel.signatureEngineer = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
                      },
                    ),
                  const SizedBox(height: 16),
                  AButton(
                    text: widget.gasRefillModel == null ? _subtitle.submit : _subtitle.update,
                    onPressed: _onSubmit,
                  ),
                  const SizedBox(height: 100)
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
