import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/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/generic_attachment_model.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/modules/cm_module/cm_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/traf_module/traf_request_model.dart';
import 'package:test_sa/modules/traf_module/traf_request_provider.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/new_views/common_widgets/multiple_item_drop_down_menu.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/lookups/classification_lookup_provider.dart';
import 'package:test_sa/providers/lookups/recommendation_lookup_provider.dart';
import 'package:test_sa/providers/lookups/request_type_lookup_provider.dart';
import 'package:test_sa/views/widgets/equipment/asset_picker.dart';
import 'package:test_sa/models/device/asset.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';

class UpdateTrafRequestPage extends StatefulWidget {
  static const String id = "/update-TRAF";

  UpdateTrafRequestPage({Key? key}) : super(key: key);

  @override
  _UpdateTrafRequestPageState createState() {
    return _UpdateTrafRequestPageState();
  }
}

class _UpdateTrafRequestPageState extends State<UpdateTrafRequestPage> {
  Lookup? requestType;
  Lookup? assessorRecommendation;
  Lookup? classificationType;
  late TrafRequestProvider trafRequestProvider;

  late TrafRequestDataModel trafRequest;

  List<Lookup> abc = [];

  List<Asset> _deviceList = [];
  Asset? asset;
  List<GenericAttachmentModel> attachments = [];

  @override
  void initState() {
    super.initState();
    Provider.of<ClassificationLookupProvider>(context, listen: false).reset();
    Provider.of<RecommendationLookupProvider>(context, listen: false).reset();
    trafRequestProvider = Provider.of<TrafRequestProvider>(context, listen: false);
    trafRequest = trafRequestProvider.trafRequestDataModel!;
    attachments = trafRequest.attachments?.whereType<GenericAttachmentModel>().map((item) => GenericAttachmentModel(id: item.id, name: item.name ?? '')).toList() ?? [];
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: const DefaultAppBar(title: "Update TRAF Request"),
        body: Column(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SingleItemDropDownMenu<Lookup, ClassificationLookupProvider>(
                    context: context,
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.neutral100,
                    showShadow: false,
                    title: "Classification",
                    initialValue: classificationType,
                    onSelect: (value) {
                      classificationType = value;
                      // trafRequest?.cla = value?.value;
                      // setState(() {});
                    },
                  ),
                  12.height,
                  SingleItemDropDownMenu<Lookup, RequestTypeLookupProvider>(
                    context: context,
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.neutral100,
                    showShadow: false,
                    title: context.translation.requestType,
                    initialValue: requestType,
                    onSelect: (value) {
                      requestType = value;
                      setState(() {});
                    },
                  ),
                  if (requestType?.id == 732) ...[
                    12.height,
                    AppTextFormField(
                      initialValue: "",
                      makeMultiLinesNull: true,
                      labelText: "Recommended Quantity",
                      backgroundColor: AppColor.fieldBgColor(context),
                      labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                      showShadow: false,
                      textInputType: TextInputType.number,
                      onChange: (value) {
                        trafRequest.qty = int.tryParse(value);
                      },
                    ),
                  ],
                  if (requestType?.id == 733) ...[
                    12.height,
                    AssetPicker(
                      overWriteStyle: true,
                      device: asset,
                      editable: false,
                      showLoading: false,

                      // borderColor: AppColor.black20,
                      // backgroundColor: AppColor.white936,
                      onPick: (asset) async {
                        this.asset = asset;
                        setState(() {});
                        // pendingAssetServiceRequest = null;
                        // _serviceRequest.device = asset;
                        // await checkAssetForPendingServiceRequest(asset.id!.toInt());
                        // if (pendingAssetServiceRequest != null && pendingAssetServiceRequest!.details!.isNotEmpty) {
                        //   showPendingRequestBottomSheet();
                        // }
                      },
                    ),
                  ],
                  // 12.height,
                  // MultipleItemDropDownMenu<Lookup, RequestTypeLookupProvider>(
                  //   context: context,
                  //   showAsBottomSheet: true,
                  //   backgroundColor: AppColor.neutral100,
                  //   showShadow: false,
                  //   showCancel: true,
                  //   title: "Please specify departments and relations",
                  //   initialValue: abc,
                  //   onSelect: (value) {
                  //     abc = value ?? [];
                  //     // setState(() {
                  //     //
                  //     // });
                  //   },
                  // ),
                  12.height,
                  Text(
                    "Quantity to be Transfer",
                    style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50, fontWeight: FontWeight.w500),
                  ),
                  8.height,
                  AssetPicker(
                    overWriteStyle: true,
                    deviceList: _deviceList,
                    showLoading: false,
                    borderColor: AppColor.black20,
                    buttonColor: AppColor.white936,
                    multiSelection: true,
                    onAssetRemove: (itemId) {
                      _deviceList.removeWhere((asset) => asset.id?.toInt() == itemId);
                      setState(() {});
                    },
                    onMultiAssetPick: (assetList) {
                      _deviceList.addAll(assetList);
                      final seenIds = <num?>{};
                      _deviceList = _deviceList.where((item) => seenIds.add(item.id)).toList();
                      setState(() {});
                    },
                  ),
                  12.height,
                  SingleItemDropDownMenu<Lookup, RecommendationLookupProvider>(
                    context: context,
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.neutral100,
                    showShadow: false,
                    title: "Assessor Recommendation",
                    initialValue: assessorRecommendation,
                    onSelect: (value) {
                      assessorRecommendation = value;
                      trafRequest?.requestTypeId = value?.value;
                      // trafRequest?.requestTypeId = value?.value;
                      // setState(() {});
                    },
                  ),
                  12.height,
                  AppTextFormField(
                    initialValue: "",
                    textInputType: TextInputType.multiline,
                    alignLabelWithHint: true,
                    labelText: "Assessor comment",
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    showShadow: false,
                    onChange: (value) {
                      trafRequest?.comment = value; // todo confirm parameter shaheer
                    },
                  ),
                  12.height,
                  AttachmentPicker(
                    label: context.translation.attachFiles,
                    showAsListView: true,
                    attachment: attachments,
                    buttonColor: AppColor.black10,
                    onlyImages: false,
                    buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10),
                    onChange: (attachment) {
                      attachments = attachment;
                    },
                  ),
                ],
              ).toShadowContainer(context, borderRadius: 20, padding: 12),
            ).expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(
                  buttonColor: AppColor.primary10,
                  label: "Update",
                  onPressed: () {
                    trafRequest.attachments = [];
                    for (var item in attachments) {
                      String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? '';
                      trafRequest.attachments!.add(
                        GenericAttachmentModel(id: item.id, moduleReferenceId: item.id, name: fileName, documentType: item.documentType),
                      );
                    }
                  }
                  // buttonColor: AppColor.primary10,
                  ),
            ),
          ],
        ));
  }
}
