import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/device_transfer_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/int_extensions.dart';
import 'package:test_sa/models/department.dart';
import 'package:test_sa/models/device/device_transfer.dart';
import 'package:test_sa/models/device/device_transfer_info.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/views/app_style/sizing.dart';
import 'package:test_sa/views/widgets/buttons/app_button.dart';
import 'package:test_sa/views/widgets/equipment/device_button.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/titles/app_sub_title.dart';

import '../../../../controllers/localization/localization.dart';
import '../../../controllers/validator/validator.dart';
import '../../app_style/colors.dart';
import '../../widgets/app_text_form_field.dart';
import '../../widgets/gas_refill/building_type_menu.dart';
import '../../widgets/gas_refill/department_type_menu.dart';
import '../../widgets/gas_refill/floor_type_menu.dart';
import '../../widgets/hospitals/hospital_auto_complete_field_new.dart';

class RequestDeviceTransfer extends StatefulWidget {
  static const String id = "/request-device-transfer";

  const RequestDeviceTransfer({Key key}) : super(key: key);

  @override
  State<RequestDeviceTransfer> createState() => _RequestDeviceTransferState();
}

class _RequestDeviceTransferState extends State<RequestDeviceTransfer> {
  bool _isLoading = false;
  bool _validate = false;
  Subtitle _subtitle;
  UserProvider _userProvider;
  SettingProvider _settingProvider;
  DeviceTransferProvider _deviceTransferProvider;
  final TextEditingController _requestedQuantityController = TextEditingController();
  final DeviceTransfer _formModel = DeviceTransfer(receiver: DeviceTransferInfo(), sender: DeviceTransferInfo());
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

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

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

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

    _isLoading = true;
    setState(() {});
    // _formModel.sender?.client?.id = _userProvider.user?.clientId;
    int status = await _deviceTransferProvider.createRequest(
      user: _userProvider.user,
      host: _settingProvider.host,
      model: _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),
    //   ));
    // }
  }

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

  @override
  Widget build(BuildContext context) {
    _subtitle = AppLocalization.of(context).subtitle;
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _deviceTransferProvider = Provider.of<DeviceTransferProvider>(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(
                        "Transfer Asset",
                        style: Theme.of(context).textTheme.headline5.copyWith(color: Theme.of(context).primaryColor, fontSize: 28, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                  // const SizedBox(height: 8,),
                  // ASubTitle(_subtitle.title),
                  // if(_validate && _formModel.title == null || _formModel.title?.isEmpty == true)
                  //   ASubTitle(_subtitle.requiredWord,color: Colors.red,),
                  // const SizedBox(height: 4,),
                  // ATextFormField(
                  //   initialValue: _formModel?.title,
                  //   textAlign: TextAlign.center,
                  //   style: Theme.of(context).textTheme.subtitle1,
                  //   textInputType: TextInputType.text,
                  //   onSaved: (value){
                  //     _formModel.title = value;
                  //   },
                  // ),
                  12.height,
                  const ASubTitle("Asset"),
                  if (_validate && _formModel.device == null)
                    ASubTitle(
                      _subtitle.requiredWord,
                      color: Colors.red,
                    ),
                  6.height,
                  DeviceButton(
                    device: _formModel.device,
                    onDevicePick: (device) {
                      _formModel.device = device;
                      _formModel.sender.client = device.hospital;
                      print("device : ${device.hospital.id}");
                      print("_formModel : ${_formModel.sender.client.id}");
                      setState(() {});
                    },
                  ),
                  if (_formModel.device != null) 8.height,
                  if (_formModel.device != null) const ASubTitle("Asset Site"),
                  if (_formModel.device != null)
                    Container(
                      width: double.infinity,
                      alignment: Alignment.center,
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
                      decoration: BoxDecoration(
                        color: AColors.inputFieldBackgroundColor,
                        border: Border.all(
                          color: const Color(0xffefefef),
                        ),
                        borderRadius: BorderRadius.circular(AppStyle.borderRadius * AppStyle.getScaleFactor(context)),
                        // boxShadow: const [
                        //   AppStyle.boxShadow
                        // ]
                      ),
                      child: ASubTitle(_formModel.device?.hospital?.name),
                    ),
                  if (_formModel.device != null) 4.height,
                  if (_formModel.device != null && _formModel.device.destDepartmentName != null) const ASubTitle("Asset Department"),
                  if (_formModel.device != null && _formModel.device.destDepartmentName != null)
                    Container(
                      width: double.infinity,
                      alignment: Alignment.center,
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
                      decoration: BoxDecoration(
                        color: AColors.inputFieldBackgroundColor,
                        border: Border.all(
                          color: const Color(0xffefefef),
                        ),
                        borderRadius: BorderRadius.circular(AppStyle.borderRadius * AppStyle.getScaleFactor(context)),
                        // boxShadow: const [
                        //   AppStyle.boxShadow
                        // ]
                      ),
                      child: ASubTitle(_formModel.device.destDepartmentName.toString()),
                    ),
                  if (_formModel.device != null) 8.height,
                  // const SizedBox(height: 8,),
                  // const ASubTitle("Sender Department"),
                  // if(_validate && _formModel.senderDepartment == null)
                  //   ASubTitle(_subtitle.requiredWord,color: Colors.red,),
                  // const SizedBox(height: 4,),
                  // DepartmentButton(
                  //   department: _formModel.senderDepartment,
                  //   onDepartmentPick: (department){
                  //     _formModel.senderDepartment = department;
                  //     setState(() {});
                  //   },
                  // ),
                  // 12.height,
                  // const ASubTitle("Destination Client"),
                  // if (_validate && _formModel.receiver.client == null)
                  //   ASubTitle(
                  //     _subtitle.requiredWord,
                  //     color: Colors.red,
                  //   ),
                  // 6.height,
                  // HospitalButton(
                  //   hospital: _formModel.receiver.client,
                  //   onHospitalPick: (hospital) {
                  //     _formModel.receiver.client = hospital;
                  //     setState(() {});
                  //   },
                  // ),
                  // 12.height,
                  // const ASubTitle("Destination Department"),
                  // if (_validate && _formModel.receiver.department == null)
                  //   ASubTitle(
                  //     _subtitle.requiredWord,
                  //     color: Colors.red,
                  //   ),
                  // 6.height,
                  // DepartmentButton(
                  //   department: _formModel.receiver.department,
                  //   onDepartmentPick: (department) {
                  //     _formModel.receiver.department = department;
                  //     setState(() {});
                  //   },
                  // ),
                  const SizedBox(
                    height: 4,
                  ),
                  Divider(
                    color: Theme.of(context).colorScheme.primary,
                  ),
                  const SizedBox(height: 8),
                  const ASubTitle("Destination"),
                  const SizedBox(
                    height: 4,
                  ),
                  HospitalAutoCompleteField(
                    initialValue: _deviceTransferProvider.hospital?.name,
                    // onSave: (value){
                    //   _search.hospital = value;
                    // },
                    onSearch: (value) {
                      _deviceTransferProvider.hospital = value;
                      _deviceTransferProvider.building = null;
                      _deviceTransferProvider.floor = null;
                      _deviceTransferProvider.department = null;
                      _formModel.receiver.client = value;
                      setState(() {});
                    },
                  ),
                  const SizedBox(
                    height: 8,
                  ),
                  BuildingTypeMenu(
                    initialValue: _deviceTransferProvider?.building,
                    building: _deviceTransferProvider?.hospital?.buildings,
                    onSelect: (status) {
                      _deviceTransferProvider.building = status;
                      setState(() {});
                    },
                  ),
                  const SizedBox(height: 8),
                  FloorTypeMenu(
                    initialValue: _deviceTransferProvider?.floor,
                    floors: _deviceTransferProvider?.building?.floors,
                    onSelect: (status) {
                      _deviceTransferProvider.floor = status;
                      setState(() {});
                    },
                  ),
                  const SizedBox(height: 8),
                  DepartmentTypeMenu(
                    initialValue: _deviceTransferProvider?.department,
                    departments: _deviceTransferProvider?.floor?.departments,
                    onSelect: (status) {
                      _deviceTransferProvider.department = status;
                      _formModel.receiver.department = Department(id: status.id, name: status.name);
                      setState(() {});
                    },
                  ),
                  const SizedBox(height: 8),
                  const ASubTitle("Room"),
                  const SizedBox(
                    height: 4,
                  ),
                  ATextFormField(
                    textAlign: TextAlign.center,
                    controller: _requestedQuantityController,
                    style: Theme.of(context).textTheme.subtitle1,
                    validator: (value) => Validator.isNumeric(value) ? null : "allow numbers only",
                    textInputType: TextInputType.number,
                    onSaved: (value) {
                      _deviceTransferProvider.room = value;
                    },
                  ),
                  12.height,
                  AButton(
                    text: _subtitle.submit,
                    onPressed: _onSubmit,
                  ),
                  const SizedBox(
                    height: 100,
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
