import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/http_status_manger.dart';
import 'package:test_sa/controllers/localization/localization.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/extensions/context_extension.dart';
import 'package:test_sa/models/gas_refill/gas_refill_model.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/views/app_style/sizing.dart';
import 'package:test_sa/views/pages/user/gas_refill/request_gas_refill.dart';
import 'package:test_sa/views/widgets/buttons/app_back_button.dart';
import 'package:test_sa/views/widgets/buttons/app_button.dart';
import 'package:test_sa/views/widgets/buttons/app_icon_button.dart';
import 'package:test_sa/views/widgets/gas_refill/gas_refill_update_details_item.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/requests/info_row.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';
import 'package:test_sa/views/widgets/status/gas_refill/gas_status.dart';
import 'package:test_sa/views/widgets/titles/app_sub_title.dart';

import '../../../../models/enums/user_types.dart';
import '../../../app_style/colors.dart';

class GasRefillDetails extends StatefulWidget {
  GasRefillModel model;

  GasRefillDetails({Key key, this.model}) : super(key: key);

  @override
  State<GasRefillDetails> createState() => _GasRefillDetailsState();
}

class _GasRefillDetailsState extends State<GasRefillDetails> {
  GasRefillModel _model = GasRefillModel();
  bool _enableEdit = false;
  bool _validate = false;
  UserProvider _userProvider;
  SettingProvider _settingProvider;
  GasRefillProvider _gasRefillProvider;
  bool _isLoading = false;

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  _update() async {
    _validate = true;
    if (!_formKey.currentState.validate()) {
      setState(() {});
      return false;
    }
    _formKey.currentState.save();

    _isLoading = true;
    setState(() {});
    int status = await _gasRefillProvider.updateModel(user: _userProvider.user, host: _settingProvider.host, newModel: _model, oldModel: widget.model);
    _isLoading = false;
    setState(() {});
    if (status >= 200 && status < 300) {
      Fluttertoast.showToast(
        msg: context.translation.successfulRequestMessage,
      );
      _enableEdit = false;
      _validate = false;
      //Navigator.of(context).pop();
    } else {
      String errorMessage = HttpStatusManger.getStatusMessage(status: status, subtitle: context.translation);
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(errorMessage),
      ));
    }
  }

  @override
  void initState() {
    _model?.fromGasRefillModel(widget.model);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
 
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _gasRefillProvider = Provider.of<GasRefillProvider>(context);
    return Scaffold(
      key: _scaffoldKey,
      body: SafeArea(
        child: Form(
          key: _formKey,
          child: LoadingManager(
            isLoading: _isLoading,
            isFailedLoading: false,
            stateCode: 200,
            onRefresh: () async {},
            child: Column(
              children: [
                Container(
                  color: Theme.of(context).colorScheme.primary,
                  padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 4),
                  child: Row(
                    children: [
                      ABackButton(
                        onPressed: () {
                          Navigator.of(context).pop(_model);
                        },
                      ),
                      Expanded(
                        child: Center(
                          child: Text(
                            "Gas Refill Request",
                            style: Theme.of(context).textTheme.headline6.copyWith(color: AColors.white, fontStyle: FontStyle.italic),
                          ),
                        ),
                      ),
                      if (_userProvider.user.type == UsersTypes.engineer)
                        AIconButton(
                          iconData: /*_enableEdit ? Icons.cancel :*/ Icons.edit,
                          color: Theme.of(context).colorScheme.onPrimary,
                          buttonSize: 42,
                          backgroundColor: AColors.green,
                          onPressed: (widget.model.status?.value ?? 0) == 2
                              ? null
                              : () async {
                                  // _enableEdit = !_enableEdit;
                                  _model?.fromGasRefillModel(widget.model);
                                  // setState(() {});
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => RequestGasRefill(
                                        gasRefillModel: widget.model,
                                      ),
                                    ),
                                  ).then((value) {
                                    if (value != null) {
                                      _model = value;
                                    }
                                  });
                                  setState(() {});
                                },
                        ),
                      const SizedBox(
                        width: 16,
                      )
                    ],
                  ),
                ),
                Expanded(
                  child: SingleChildScrollView(
                    padding: EdgeInsets.all(16 * AppStyle.getScaleFactor(context)),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        RequestInfoRow(
                          title: "Gas Refill No",
                          info: _model.title,
                        ),
                        RequestInfoRow(
                          title: context.translation.hospital,
                          info: _model.clientName,
                        ),
                        RequestInfoRow(
                          title: "Building",
                          info: _model.building?.name,
                        ),
                        RequestInfoRow(
                          title: "Floor",
                          info: _model.floor?.name,
                        ),
                        RequestInfoRow(
                          title: "Department",
                          info: _model.department?.departmentName,
                        ),
                        RequestInfoRow(
                          title: context.translation.startDate,
                          info: _model.startDate == null ? null : "${DateFormat.yMd().format(_model.startDate)} ${DateFormat.Hms().format(_model.startDate)}",
                        ),
                        RequestInfoRow(
                          title: context.translation.endDate,
                          info: _model.endDate == null ? null : "${DateFormat.yMd().format(_model.endDate)} ${DateFormat.Hms().format(_model.endDate)}",
                        ),
                        _enableEdit
                            ? Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const SizedBox(
                                    height: 8,
                                  ),
                                  ASubTitle(context.translation.status),
                                  if (_validate && _model.status == null)
                                    ASubTitle(
                                      context.translation.requiredWord,
                                      color: Colors.red,
                                    ),
                                  const SizedBox(
                                    height: 4,
                                  ),
                                  GasStatusMenu(
                                    initialValue: _model.status,
                                    onSelect: (status) {
                                      _model.status = status;
                                    },
                                  )
                                ],
                              )
                            : Row(
                                children: [
                                  Expanded(
                                    child: Text(
                                      "${context.translation.status} :  ",
                                      style: Theme.of(context).textTheme.subtitle2,
                                      textScaleFactor: AppStyle.getScaleFactor(context),
                                    ),
                                  ),
                                  if (_model.status?.id != null) StatusLabel(label: _model.status.name, backgroundColor: AColors.getGasStatusColor(_model.status.id)),
                                ],
                              ),
                        const SizedBox(
                          height: 8,
                        ),
                        const ASubTitle("Gas Requests"),
                        const SizedBox(
                          height: 8,
                        ),
                        ListView.builder(
                            shrinkWrap: true,
                            physics: const ClampingScrollPhysics(),
                            itemCount: _model.details.length,
                            itemBuilder: (context, index) {
                              final details = _model.details[index];
                              return GasRefillUpdateDetailsItem(
                                details: details,
                                validate: _validate,
                                enableEdit: _enableEdit,
                              );
                            }),
                        if (_enableEdit)
                          Column(
                            children: [
                              const SizedBox(
                                height: 16,
                              ),
                              AButton(
                                text: context.translation.update,
                                onPressed: _update,
                              ),
                            ],
                          ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
