import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/asset_transfer_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/employee/nurse_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/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/device/asset.dart';
import 'package:test_sa/models/device/asset_transfer.dart';
import 'package:test_sa/models/employee.dart';
import 'package:test_sa/models/new_models/department.dart';
import 'package:test_sa/models/new_models/floor.dart';
import 'package:test_sa/models/new_models/room_model.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/views/widgets/status/employee/nurse_menu.dart';

import '../../../models/new_models/building.dart';
import '../../../models/new_models/site.dart';
import '../../../new_views/common_widgets/app_filled_button.dart';
import '../../../new_views/common_widgets/default_app_bar.dart';
import '../../../new_views/common_widgets/single_item_drop_down_menu.dart';
import '../../../providers/gas_request_providers/site_provider.dart';
import '../../../providers/loading_list_notifier.dart';
import '../../widgets/equipment/pick_asset.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> {
  UserProvider? _userProvider;
  SettingProvider? _settingProvider;
  late AssetTransferProvider _deviceTransferProvider;
  final TextEditingController _requestedQuantityController = TextEditingController();
  final AssetTransfer _transferModel = AssetTransfer();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final TextEditingController _receiverNameController = TextEditingController(), _commentsController = TextEditingController();
  final Asset _assetDestination = Asset();
  Asset? _pickedAsset;
  Employee? receiverEndUser;
  Employee? _selectedNurse;

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

  void _onSubmit() async {
    _transferModel.assetId = _pickedAsset?.id;
    _transferModel.destSiteId = _assetDestination.site?.id;
    _transferModel.destBuildingId = _assetDestination.building?.id;
    _transferModel.destFloorId = _assetDestination.floor?.id;
    _transferModel.destDepartmentId = _assetDestination.department?.id;
    _transferModel.destRoomId = _assetDestination.room?.id;
    _transferModel.receiverEndUserId = _selectedNurse?.id;
    if (!_formKey.currentState!.validate() || !(await _transferModel.validate(context))) {
      return;
    }
    _formKey.currentState!.save();
    await _deviceTransferProvider.createRequest(context: context, assetDestination: _transferModel, asset: _pickedAsset!);
  }

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

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context, listen: false);
    _settingProvider = Provider.of<SettingProvider>(context, listen: false);
    _deviceTransferProvider = Provider.of<AssetTransferProvider>(context, listen: false);
    // _selectedNurse ??= Employee(id: _userProvider.user.userID, name: _userProvider.user.username);

    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: context.translation.newTransferRequest),
      body: Form(
        key: _formKey,
        child: SafeArea(
          child: Column(
            children: [
              SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    16.height,
                    PickAsset(
                      device: _pickedAsset,
                      onPickAsset: (asset) {
                        _pickedAsset = asset;
                        setState(() {});
                      },
                    ),
                    16.height,
                    context.translation.receiverDetails.heading5(context),
                    8.height,
                    SingleItemDropDownMenu<Site, SiteProvider>(
                      context: context,
                      title: context.translation.destinationSite,
                      initialValue: _assetDestination.site,
                      onSelect: (value) {
                        _assetDestination.site = value;
                        _assetDestination.building = null;
                        _assetDestination.floor = null;
                        _assetDestination.department = null;
                        _selectedNurse = null;
                        Provider.of<NurseProvider>(context, listen: false).siteId = value!.id!.toInt();
                        Provider.of<NurseProvider>(context, listen: false).getData();
                        setState(() {});
                      },
                    ),
                    8.height,
                    SingleItemDropDownMenu<Building, NullableLoadingProvider>(
                      context: context,
                      title: context.translation.building,
                      initialValue: _assetDestination.building,
                      enabled: _assetDestination.site?.buildings?.isNotEmpty ?? false,
                      staticData: _assetDestination.site?.buildings ?? [],
                      onSelect: (value) {
                        _assetDestination.building = value;
                        _assetDestination.floor = null;
                        _assetDestination.department = null;
                        setState(() {});
                      },
                    ),
                    8.height,
                    SingleItemDropDownMenu<Floor, NullableLoadingProvider>(
                      context: context,
                      title: context.translation.floor,
                      initialValue: _assetDestination.floor,
                      enabled: _assetDestination.building?.floors?.isNotEmpty ?? false,
                      staticData: _assetDestination.building?.floors ?? [],
                      onSelect: (value) {
                        _assetDestination.floor = value;
                        _assetDestination.department = null;
                        setState(() {});
                      },
                    ),
                    8.height,
                    SingleItemDropDownMenu<Department, NullableLoadingProvider>(
                      context: context,
                      title: context.translation.department,
                      initialValue: _assetDestination.department,
                      enabled: _assetDestination.floor?.departments?.isNotEmpty ?? false,
                      staticData: _assetDestination.floor?.departments ?? [],
                      onSelect: (value) {
                        _assetDestination.department = value;
                        _assetDestination.room = null;
                        setState(() {});
                      },
                    ),
                    8.height,
                    SingleItemDropDownMenu<Rooms, NullableLoadingProvider>(
                      context: context,
                      title: context.translation.room,
                      initialValue: _assetDestination.room,
                      enabled: _assetDestination.department?.rooms?.isNotEmpty ?? false,
                      staticData: _assetDestination.department?.rooms ?? [],
                      onSelect: (value) {
                        _assetDestination.room = value;
                        setState(() {});
                      },
                    ),
                    8.height,
                    NurseMenu(
                      title: context.translation.receiverName,
                      initialValue: _selectedNurse,
                      enable: _assetDestination.site != null,
                      onSelect: (employee) {
                        if (employee != null) {
                          _selectedNurse = employee;
                          setState(() {});
                        }
                      },
                    ),
                    16.height,
                    context.translation.comments.heading5(context),
                    8.height,
                    AppTextFormField(
                      controller: _commentsController,
                      labelText: context.translation.comments,
                      onSaved: (text) {
                        _transferModel.comment = text;
                      },
                    ),
                    100.height,
                  ],
                ),
              ).expanded,
              AppFilledButton(label: context.translation.submitRequest, maxWidth: true, onPressed: _onSubmit)
            ],
          ).paddingOnly(start: 16, end: 16, bottom: 24),
        ),
      ),
    );
  }
}
