import 'dart:convert';
import 'dart:developer';
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/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/helper/utils.dart';
import 'package:test_sa/models/device/asset.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/new_models/traf_customer.dart';
import 'package:test_sa/models/new_models/traf_department.dart';
import 'package:test_sa/models/new_models/users_based_on_search_model.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/asset_auto_complete_field.dart';
import 'package:test_sa/modules/traf_module/users_auto_complete_field.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/customer_lookup_provider.dart';
import 'package:test_sa/providers/lookups/department_lookup_provider.dart';
import 'package:test_sa/providers/lookups/request_type_lookup_provider.dart';
import 'package:test_sa/providers/lookups/yes_no_lookup_provider.dart';
import 'package:test_sa/views/widgets/equipment/asset_picker.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';

import 'traf_request_model.dart';
import 'traf_request_provider.dart';

class CreateTRAFRequestPage extends StatefulWidget {
  static const String id = "/create-TRAF";

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

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

class _CreateTRAFRequestPageState extends State<CreateTRAFRequestPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  bool _acknowledgement = false;
  Asset? asset;

  Lookup? requestType;
  Lookup? isUsedSolelyOrShared;
  Lookup? otherServicesEffects;
  Lookup? useInCombination;

  TrafCustomer? selectedSite;
  TrafDepartment? selectedDepartment;

  TrafRequestDataModel? trafRequest;

  List<Lookup> abc = [];

  List<TrafDepartment> departments = [];
  List<UsersBasedOnSearchModel> userBasedOnSearch = [];
  List<GenericAttachmentModel> attachments = [];

  FocusNode otherServicesEffectsNode = FocusNode();
  FocusNode useInCombinationNode = FocusNode();
  FocusNode departmentNode = FocusNode();
  FocusNode siteDepartmentNode = FocusNode();

  @override
  void initState() {
    super.initState();
    trafRequest = TrafRequestDataModel(id: 0, attachments: [], departments: [], qty: 1);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final requestTypeProvider = Provider.of<RequestTypeLookupProvider>(context, listen: false);
      final yesNoProvider = Provider.of<YesNoLookupProvider>(context, listen: false);
      final customerProvider = Provider.of<CustomerLookupProvider>(context, listen: false);
      if (requestTypeProvider.items.isEmpty) {
        requestTypeProvider.reset();
      }
      if (yesNoProvider.items.isEmpty) {
        yesNoProvider.reset();
      }
      final userId = context.userProvider.user?.userID;
      if (customerProvider.items.isEmpty && userId != null && userId.isNotEmpty) {
        customerProvider.getDataByUserId(userId);
      }
      log('user id is ${userId}');
    });
  }

  void resetProviders() {
    Provider.of<RequestTypeLookupProvider>(context, listen: false).reset();
    Provider.of<YesNoLookupProvider>(context, listen: false).reset();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const DefaultAppBar(title: "Assessment of Need & Technology"),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            ListView(padding: const EdgeInsets.all(16), children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // SingleItemDropDownMenu<TaskType, TaskTypeProvider>(
                  //   context: context,
                  //   height: 56.toScreenHeight,
                  //   title: context.translation.taskType,
                  //   showShadow: false,
                  //   backgroundColor: AppColor.fieldBgColor(context),
                  //   showAsBottomSheet: true,
                  //   initialValue: selectedType,
                  //   onSelect: (type) {},
                  // ),
                  SingleItemDropDownMenu<Lookup, RequestTypeLookupProvider>(
                    context: context,
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.neutral100,
                    showShadow: false,
                    title: context.translation.requestType,
                    initialValue: requestType,
                    onSelect: (value) {
                      requestType = value;
                      trafRequest?.requestTypeId = value?.id;
                      if (requestType?.value == 1) {
                        trafRequest?.assetId = null;
                        // trafRequest?.qty = 0;
                      } else if (requestType?.value == 2) {
                        trafRequest?.assetNDId = null;
                        trafRequest?.qty = 1;
                      }
                      setState(() {});
                    },
                  ),
                  if (requestType?.value == 1) ...[
                    12.height,
                    AssetAutoCompleteField(
                      clearAfterPick: false,
                      byName: true,
                      initialValue: "",
                      onPick: (asset) {
                        trafRequest?.assetNDId = asset.id;
                        // model.partCatalogItem = PartCatalogItem(id: part.sparePart?.id, partNumber: part.sparePart?.partNo, partName: part.sparePart?.partName, oracleCode: part.sparePart?.oracleCode);
                        // setState(() {});
                      },
                    ),
                    12.height,
                    AppTextFormField(
                      initialValue: trafRequest?.qty?.toString() ?? "",
                      makeMultiLinesNull: true,
                      labelText: "Quantity",
                      validator: (value) {
                        if ((value ?? "").isEmpty) return "Mandatory";
                        return null;
                      },
                      backgroundColor: AppColor.fieldBgColor(context),
                      labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                      showShadow: false,
                      textInputType: TextInputType.number,
                      onChange: (value) {
                        trafRequest?.qty = int.parse(value);
                      },
                    ),
                  ],
                  if (requestType?.value == 2) ...[
                    12.height,
                    AssetPicker(
                      overWriteStyle: true,
                      device: asset,
                      editable: false,
                      showLoading: false,
                      borderColor: AppColor.black20,
                      backgroundColor: AppColor.white936,
                      onPick: (asset) async {
                        this.asset = asset;
                        trafRequest?.assetId = asset.id?.toInt();
                        // trafRequest?.qty = 1;
                        setState(() {});
                        // pendingAssetServiceRequest = null;
                        // _serviceRequest.device = asset;
                        // await checkAssetForPendingServiceRequest(asset.id!.toInt());
                        // if (pendingAssetServiceRequest != null && pendingAssetServiceRequest!.details!.isNotEmpty) {
                        //   showPendingRequestBottomSheet();
                        // }
                      },
                    ),
                  ],
                  12.height,
                  Text(
                    "Request Details",
                    style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50, fontWeight: FontWeight.w600),
                  ),
                  12.height,
                  SingleItemDropDownMenu<TrafCustomer, CustomerLookupProvider>(
                    context: context,
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.neutral100,
                    showShadow: false,
                    title: "Site",
                    requestById: int.tryParse(context.userProvider.user?.userID ?? ''),
                    initialValue: selectedSite,
                    onSelect: (value) {
                      selectedSite = value;
                      trafRequest?.siteId = value?.customerId;
                      // Reset department when site changes
                      selectedDepartment = null;
                      trafRequest?.departmentId = null;

                      // Reset and fetch department data based on selected site
                      Provider.of<DepartmentLookupProvider>(context, listen: false).reset();
                      if (selectedSite != null && selectedSite!.customerId != null) {
                        // Fetch departments for the selected site
                        Provider.of<DepartmentLookupProvider>(context, listen: false).getData(id: selectedSite!.customerId);
                        siteDepartmentNode.requestFocus();
                      }
                      setState(() {});
                    },
                  ),
                  12.height,
                  SingleItemDropDownMenu<TrafDepartment, DepartmentLookupProvider>(
                    context: context,
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.neutral100,
                    showShadow: false,
                    title: "Department",
                    requestById: null,
                    // initialValue: selectedDepartment,
                    enabled: selectedSite != null,
                    onSelect: (value) {
                      selectedDepartment = value;
                      trafRequest?.departmentId = value?.id?.toString();
                      setState(() {});
                    },
                  ),
                  12.height,
                  AppTextFormField(
                    initialValue: "",
                    labelText: "How would the requested technology solve the current situation and/or serve the purpose?",
                    validator: (value) {
                      if ((value ?? "").isEmpty) return "Mandatory";
                      return null;
                    },
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    floatingLabelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    showShadow: false,
                    makeMultiLinesNull: true,
                    onChange: (value) {
                      trafRequest?.purposeAnswer = value;
                    },
                  ),
                  12.height,
                  AppTextFormField(
                    initialValue: "",
                    labelText: "What is the current practice?",
                    validator: (value) {
                      if ((value ?? "").isEmpty) return "Mandatory";
                      return null;
                    },
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    showShadow: false,
                    makeMultiLinesNull: true,
                    onChange: (value) {
                      trafRequest?.currentPractise = value;
                    },
                  ),
                  12.height,
                  AppTextFormField(
                    initialValue: "",
                    makeMultiLinesNull: true,
                    labelText: "Census Q1",
                    validator: (value) {
                      if ((value ?? "").isEmpty) return "Mandatory";
                      return null;
                    },
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    showShadow: false,
                    textInputType: TextInputType.text,
                    onChange: (value) {
                      trafRequest?.censusQ1 = value;
                    },
                  ),
                  12.height,
                  AppTextFormField(
                    initialValue: "",
                    makeMultiLinesNull: true,
                    labelText: "Census Q2",
                    validator: (value) {
                      if ((value ?? "").isEmpty) return "Mandatory";
                      return null;
                    },
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    showShadow: false,
                    textInputType: TextInputType.text,
                    onChange: (value) {
                      trafRequest?.censusQ2 = value;
                    },
                  ),
                  12.height,
                  AppTextFormField(
                    initialValue: "",
                    makeMultiLinesNull: true,
                    labelText: "Census Q3",
                    validator: (value) {
                      if ((value ?? "").isEmpty) return "Mandatory";
                      return null;
                    },
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    showShadow: false,
                    textInputType: TextInputType.text,
                    onChange: (value) {
                      trafRequest?.censusQ3 = value;
                    },
                  ),
                  12.height,
                  AppTextFormField(
                    initialValue: "",
                    makeMultiLinesNull: true,
                    labelText: "Census Q4",
                    validator: (value) {
                      if ((value ?? "").isEmpty) return "Mandatory";
                      return null;
                    },
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    showShadow: false,
                    textInputType: TextInputType.text,
                    onChange: (value) {
                      trafRequest?.censusQ4 = value;
                    },
                  ),
                  12.height,
                  SearchUserAutoCompleteField(
                    clearAfterPick: true,
                    byName: true,
                    initialValue: "",
                    onPick: (user) {
                      userBasedOnSearch.add(user);
                      FocusScope.of(context).unfocus();
                      // model.partCatalogItem = PartCatalogItem(id: part.sparePart?.id, partNumber: part.sparePart?.partNo, partName: part.sparePart?.partName, oracleCode: part.sparePart?.oracleCode);
                      setState(() {});
                    },
                  ),
                  if (userBasedOnSearch.isNotEmpty) ...[
                    // 12.height,
                    ListView.separated(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        padding: const EdgeInsets.only(left: 12, right: 12),
                        itemBuilder: (cxt, index) => Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                ListTile(
                                  dense: true,
                                  contentPadding: EdgeInsets.zero,
                                  title: Text("Name: ${userBasedOnSearch[index].userName ?? ""}"),
                                  subtitle: Text(
                                      "Position: ${userBasedOnSearch[index].position ?? "-"}\nEmail: ${userBasedOnSearch[index].email ?? ""}\nPhone: ${userBasedOnSearch[index].phoneNumber ?? ""}"),
                                  trailing: "delete".toSvgAsset().onPress(() {
                                    userBasedOnSearch.removeAt(index);
                                    setState(() {});
                                  }),
                                ),
                              ],
                            ),
                        separatorBuilder: (cxt, index) => const Divider().defaultStyle(context),
                        itemCount: userBasedOnSearch.length)
                  ],
                  12.height,
                  SingleItemDropDownMenu<Lookup, YesNoLookupProvider>(
                    context: context,
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.neutral100,
                    showShadow: false,
                    height: 80,
                    title: "Is the requesting department going to use the technology solely or shared with other departments?",
                    initialValue: isUsedSolelyOrShared,
                    onSelect: (value) {
                      isUsedSolelyOrShared = value;
                      trafRequest?.usingSolelyOrSharedId = value?.id;
                      if (isUsedSolelyOrShared?.value != 1) {
                        departments = [];
                        trafRequest?.trafDepartments = [];
                        Provider.of<DepartmentLookupProvider>(context, listen: false).reset();
                        FocusScope.of(context).unfocus();
                      } else {
                        departmentNode.requestFocus();
                      }
                      setState(() {});
                    },
                  ),
                  if (isUsedSolelyOrShared?.value == 1) ...[
                    12.height,
                    Focus(
                      focusNode: departmentNode,
                      child: MultipleItemDropDownMenu<TrafDepartment, DepartmentLookupProvider>(
                        context: context,
                        showAsBottomSheet: true,
                        backgroundColor: AppColor.neutral100,
                        showShadow: false,
                        showCancel: true,
                        requestById: context.userProvider.user?.clientId,
                        title: "Please specify departments and relations",
                        initialValue: departments,
                        onSelect: (value) {
                          departments = value ?? [];
                          trafRequest?.trafDepartments = departments.map((element) => Departments(id: 0, trafId: 0, departmentId: element.id!.toInt())).toList();
                        },
                      ),
                    ),
                  ],
                  12.height,
                  SingleItemDropDownMenu<Lookup, YesNoLookupProvider>(
                    context: context,
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.neutral100,
                    showShadow: false,
                    height: 80,
                    title: "Would other services be effected by acquiring the new equipment?",
                    initialValue: otherServicesEffects,
                    onSelect: (value) {
                      otherServicesEffects = value;
                      trafRequest?.isEffectedId = value?.id;
                      if (otherServicesEffects?.value != 1) {
                        trafRequest?.effectedServices = null;
                        FocusScope.of(context).unfocus();
                      } else {
                        otherServicesEffectsNode.requestFocus();
                      }
                      setState(() {});
                    },
                  ),
                  if (otherServicesEffects?.value == 1) ...[
                    12.height,
                    AppTextFormField(
                      initialValue: "",
                      // makeMultiLinesNull: true,
                      textInputType: TextInputType.multiline,
                      alignLabelWithHint: true,
                      node: otherServicesEffectsNode,
                      validator: (value) {
                        if ((value ?? "").isEmpty) return "Mandatory";
                        return null;
                      },
                      labelText: "List down these services and stat how would it be effected",
                      backgroundColor: AppColor.fieldBgColor(context),
                      labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                      showShadow: false,
                      onChange: (value) {
                        trafRequest?.effectedServices = value;
                      },
                    ),
                  ],
                  12.height,
                  SingleItemDropDownMenu<Lookup, YesNoLookupProvider>(
                    context: context,
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.neutral100,
                    showShadow: false,
                    height: 80,
                    title: "Is the equipment going to be used with combination of other equipment to accomplish a specific procedure?",
                    initialValue: useInCombination,
                    onSelect: (value) {
                      useInCombination = value;
                      trafRequest?.isCombinationId = value?.id;
                      if (useInCombination?.value != 1) {
                        trafRequest?.usedWithCombination = null;
                        FocusScope.of(context).unfocus();
                      } else {
                        useInCombinationNode.requestFocus();
                      }
                      setState(() {});
                    },
                  ),
                  if (useInCombination?.value == 1) ...[
                    12.height,
                    AppTextFormField(
                      initialValue: "",
                      textInputType: TextInputType.multiline,
                      alignLabelWithHint: true,
                      node: useInCombinationNode,
                      validator: (value) {
                        if ((value ?? "").isEmpty) return "Mandatory";
                        return null;
                      },
                      labelText: "kindly describe in detail",
                      backgroundColor: AppColor.fieldBgColor(context),
                      labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                      showShadow: false,
                      onChange: (value) {
                        trafRequest?.usedWithCombination = value;
                      },
                    ),
                  ],
                  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, padding: 12, borderRadius: 20),
              16.height,
              Row(
                children: [
                  Checkbox(
                      value: _acknowledgement,
                      side: BorderSide(color: AppColor.loadingColor(context), width: 1.0),
                      visualDensity: const VisualDensity(horizontal: -4.0, vertical: -4.0),
                      activeColor: AppColor.blueStatus(context),
                      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      onChanged: (value) {
                        setState(() {
                          _acknowledgement = value!;
                        });
                      }),
                  12.width,
                  "I acknowledge the information filled above is correct".addTranslation.bodyText(context).custom(color: context.isDark ? AppColor.primary50 : AppColor.neutral120).expanded,
                ],
              ),
            ]).expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(
                buttonColor: AppColor.primary10,
                label: context.translation.submitRequest,
                disableButton: !_acknowledgement,
                onPressed: _verifyAndSubmit,
                // buttonColor: AppColor.primary10,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _verifyAndSubmit() async {
    if (requestType == null) {
      "Select request type".showToast;
      return;
    } else if (requestType?.value == 1 && trafRequest?.assetNDId == null) {
      "Oracle Code missing".showToast;
      return;
    } else if (requestType?.value == 2 && trafRequest?.assetId == null) {
      "Pick asset".showToast;
      return;
    }

    // Validate site and department selection
    if (selectedSite == null) {
      "Please select a site".showToast;
      return;
    }

    if (selectedDepartment == null) {
      "Please select a department".showToast;
      return;
    }

    if (!_formKey.currentState!.validate()) return;

    trafRequest?.employeeId = context.userProvider.user?.userID;
    // Set site and department IDs from selected dropdowns
    trafRequest?.siteId = selectedSite?.customerId;
    trafRequest?.departmentId = selectedDepartment?.id;

    trafRequest?.trafContacts = [];
    trafRequest?.trafContacts = userBasedOnSearch.map((item) => TrafContacts(id: 0, trafId: 0, name: item.userName, userId: item.userId)).toList();

    if ((trafRequest?.trafContacts ?? []).isEmpty) {
      "Please specify users going to use technology".showToast;
      return;
    }
    if (isUsedSolelyOrShared == null) {
      "Please specify technology solely or shared".showToast;
      return;
    }
    if (isUsedSolelyOrShared?.value == 1 && (trafRequest?.trafDepartments ?? []).isEmpty) {
      "Please specify departments and relations".showToast;
      return;
    }

    if (otherServicesEffects == null) {
      "Please specify other services will be effected or not".showToast;
      return;
    }

    if (useInCombination == null) {
      "Please specify equipment used in combination or not".showToast;
      return;
    }

    // Process attachments similar to CreateCMRequest
    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: 0, moduleReferenceId: 0, name: fileName, documentType: item.documentType),
      );
    }

    Utils.showLoading(context);
    bool isSuccess = await Provider.of<TrafRequestProvider>(context, listen: false).addTraf(trafRequest!.toJsonNew());
    Utils.hideLoading(context);
    if (isSuccess) {
      Navigator.pop(context);
    }
  }
}
