import 'dart:io';

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:generp/Models/commonModels/DistrictsResponse.dart';
import 'package:generp/Models/commonModels/SubLocationsResponse.dart';
import 'package:generp/Utils/dropdownTheme.dart';
import 'package:provider/provider.dart';
import 'package:generp/Models/ordersModels/ordersDetailsEditOrderViewResponse.dart';

import '../../Notifiers/ordersProvider/editOrderProvider.dart';
import '../../Utils/app_colors.dart';
import '../../Utils/commonWidgets.dart';

class Editorderaccountdetails extends StatefulWidget {
  final pageTitleName;
  final mode;
  final orderID;

  const Editorderaccountdetails({super.key,required this.pageTitleName,required this.mode,required this.orderID});

  @override
  State<Editorderaccountdetails> createState() => _EditorderaccountdetailsState();
}

class _EditorderaccountdetailsState extends State<Editorderaccountdetails> {
  FocusNode focusNode = FocusNode();
  FocusNode focusNodetpc = FocusNode();
  List<FocusNode> focusNodes = List.generate(5, (index) => FocusNode(),);
  Dropdowntheme ddtheme = Dropdowntheme();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var provider = Provider.of<Editorderprovider>(context, listen: false);

      provider.ordersEditOrderAPIViewFunction(context, widget.orderID);
    });
  }

  @override
  void dispose() {
    focusNodes.map((e)=>e.dispose());
    super.dispose();
  }

  Future<bool> _onBackPressed(BuildContext context) async {
    Navigator.pop(context, true);
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<Editorderprovider>(
      builder: (context, provider, child) {
        return WillPopScope(
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS?false:true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              backgroundColor: AppColors.white,
              appBar: appbar2(
                context,
                "${widget.pageTitleName}",
                provider.resetForm,
                SizedBox(width: 0),
              ),
              body: Container(
                padding: EdgeInsets.symmetric(horizontal: 10),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [

                      TextWidget(context, "Dispatch State"),
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<States>(
                                isExpanded: true,
                                hint: Text(
                                  "Select State",
                                  style: TextStyle(fontSize: 14),
                                  overflow: TextOverflow.ellipsis,
                                ),
                                items:
                                provider.dispatchStates
                                    .map(
                                      (e) => DropdownMenuItem<States>(
                                    value: e,
                                    child: Text(
                                      e.name!,
                                      style: const TextStyle(
                                        fontSize: 14,
                                      ),
                                    ),
                                  ),
                                )
                                    .toList(),
                                value: provider.selecetdDispatchStates,
                                onChanged: (States? value) {
                                  if (provider.dispatchStates.isNotEmpty) {
                                    provider.selecetdDispatchStates = value;
                                    provider.selectedDispatchStateID = value!.id!;
                                    provider.selectedDispatchStateName =
                                    value!.name!;
                                    if (provider.dispatchDistricts.isNotEmpty) {
                                      provider.dispatchDistricts.clear();
                                      // provider.selectedDispatchDistricts = null;
                                      provider.selectedDispatchDistrictId = null;
                                      provider.selectedDispatchDistrictValue = "";
                                    }
                                    provider.getDispatchDistrictAPI(
                                      context,
                                      provider.selectedDispatchStateID,
                                    );
                                  }
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),
                      //dd
                      TextWidget(context, "Dispatch District"),
                      //dd
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<Districts>(
                                isExpanded: true,
                                hint: Text(
                                  "Select District",
                                  style: const TextStyle(fontSize: 14),
                                ),
                                items:
                                provider.dispatchDistricts
                                    .map(
                                      (e) => DropdownMenuItem<Districts>(
                                    value: e,
                                    child: Text(
                                      e.district!,
                                      style: const TextStyle(
                                        fontSize: 14,
                                      ),
                                    ),
                                  ),
                                )
                                    .toList(),
                                value: provider.selectedDispatchDistricts,
                                onChanged: (Districts? value) {
                                  if (provider.dispatchDistricts.isNotEmpty) {
                                    provider.selectedDispatchDistricts = value;
                                    provider.selectedDispatchDistrictId =
                                    value!.id!;
                                    provider.selectedDispatchDistrictValue =
                                    value!.district!;
                                    if (provider
                                        .dispatchSubLocations
                                        .isNotEmpty) {
                                      provider.dispatchSubLocations.clear();
                                      // provider.selectedDispatchSubLocations =
                                      // null;
                                      provider.selectedDispatchSubLocID = null;
                                      provider.selectedDispatchSubLocValue = "";
                                    }
                                    provider.getDispatchSubLocationAPI(
                                      context,
                                      provider.selectedDispatchDistrictId,
                                    );
                                  }
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),
                      TextWidget(context, "Dispatch Sub Location"),
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<SubLocations>(
                                hint: Text(
                                  "Select Sub Locality",
                                  style: const TextStyle(fontSize: 14),
                                ),
                                items:
                                provider.dispatchSubLocations
                                    .map(
                                      (e) => DropdownMenuItem<SubLocations>(
                                    value: e,
                                    child: Text(
                                      e.subLocality!,
                                      style: const TextStyle(
                                        fontSize: 14,
                                      ),
                                    ),
                                  ),
                                )
                                    .toList(),
                                value: provider.selectedDispatchSubLocations,
                                onChanged: (SubLocations? value) {
                                  if (provider.dispatchSubLocations.isNotEmpty) {
                                    provider.selectedDispatchSubLocations = value;
                                    provider.selectedDispatchSubLocID =
                                    value!.id!;
                                    provider.selectedDispatchSubLocValue =
                                    value!.subLocality!;
                                  }
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),
                      //dd
                      textControllerWidget(
                        context,
                        provider.dispatchAddressController,
                        "Dispatch Address",
                        "Enter Dispatch Address",
                        provider.onChangedDispatchAddress,
                        TextInputType.text,
                        false,
                        null,
                        focusNodes[0],focusNodes[1],TextInputAction.next
                      ),
                      errorWidget(context, provider.dispatchAddressError),

                      textControllerWidget(
                        context,
                        provider.dispatchPincodeController,
                        "Dispatch Pin code",
                        "Enter Dispatch Pin code",
                        provider.onChangedDispatchPincode,
                        TextInputType.number,
                        false,
                        FilteringTextInputFormatter.digitsOnly,
                          focusNodes[1],focusNodes[2],TextInputAction.next
                      ),
                      errorWidget(context, provider.dispatchPincodeError),
                      textControllerWidget(
                        context,
                        provider.noteController,
                        "Note",
                        "Enter Note",
                        provider.onChangedNote,
                        TextInputType.text,
                        false,
                        null,
                          focusNodes[2],focusNodes[3],TextInputAction.done
                      ),
                      errorWidget(context, provider.noteError),



                      InkResponse(
                        onTap: () {
                          _showAttachmentSheet(context);
                        },
                        child: Container(
                          margin: EdgeInsets.symmetric(vertical: 10),
                          height: 45,
                          width: MediaQuery.of(context).size.width,
                          decoration: BoxDecoration(
                            color: Color(0xFFE6F6FF),
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(
                              color: AppColors.app_blue,
                              width: 0.5,
                            ),
                          ),
                          child: Center(
                            child: Text(
                              "Upload Purchase Order",
                              style: TextStyle(
                                fontFamily: "JakartaMedium",
                                color: AppColors.app_blue,
                              ),
                            ),
                          ),
                        ),
                      ),
                      if (provider.imagePicked == 1 &&
                          provider.imagePath != null) ...[
                        Padding(
                          padding: const EdgeInsets.symmetric(vertical: 4.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "${provider.imagePath}",
                                style: TextStyle(
                                  color: AppColors.semi_black,
                                  fontSize: 11,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                              InkResponse(
                                onTap: () {
                                  provider.imagePicked = 0;
                                  provider.imagePath = null;
                                  provider.imageFilePath = null;
                                },
                                child: SvgPicture.asset(
                                  "assets/svg/ic_close.svg",
                                  width: 15,
                                  height: 15,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],

                      TextWidget(context, "Unloading Scope"),
                      //dd
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<String>(
                                hint: Text(
                                  "Select Unloading Scope",
                                  style: const TextStyle(fontSize: 14),
                                ),
                                items:
                                provider.unloadingScope
                                    .map(
                                      (e) => DropdownMenuItem<String>(
                                    value: e!,
                                    child: Text(
                                      e,
                                      style: const TextStyle(
                                        fontSize: 14,
                                      ),
                                    ),
                                  ),
                                )
                                    .toList(),
                                value: provider.selectedUnloadingScope,
                                onChanged: (String? value) {
                                  if (provider.unloadingScope.isNotEmpty) {
                                    provider.selectedUnloadingScope = value;
                                  }
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),
                      TextWidget(context, "Freight Scope"),
                      //dd
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<String>(
                                hint: Text(
                                  "Select Freight Scope",
                                  style: const TextStyle(fontSize: 14),
                                ),
                                items:
                                provider.freightScope
                                    .map(
                                      (e) => DropdownMenuItem<String>(
                                    value: e!,
                                    child: Text(
                                      e,
                                      style: const TextStyle(
                                        fontSize: 14,
                                      ),
                                    ),
                                  ),
                                )
                                    .toList(),
                                value:provider.selectedFreightScope,
                                onChanged: (String? value) {
                                  if (provider.freightScope.isNotEmpty) {
                                    provider.selectedFreightScope = value;
                                  }
                                },
                                buttonStyleData: ButtonStyleData(
                                  height: 50,
                                  width: 160,
                                  padding: const EdgeInsets.only(
                                    left: 14,
                                    right: 14,
                                  ),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(14),
                                    color: AppColors.text_field_color,
                                  ),
                                ),
                                iconStyleData: IconStyleData(
                                  icon: SvgPicture.asset(
                                    "assets/svg/arrow_dropdown.svg",
                                    height: 25,
                                    width: 20,
                                  ),
                                  iconSize: 12,
                                  iconEnabledColor: Color(0xFF2D2D2D),
                                  iconDisabledColor: Colors.grey,
                                ),
                                dropdownStyleData: DropdownStyleData(
                                  maxHeight: 200,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(14),
                                    color: AppColors.text_field_color,
                                  ),
                                  scrollbarTheme: ScrollbarThemeData(
                                    radius: const Radius.circular(15),
                                    thickness: MaterialStateProperty.all<double>(
                                      6,
                                    ),
                                    thumbVisibility:
                                    MaterialStateProperty.all<bool>(true),
                                  ),
                                ),
                                menuItemStyleData: const MenuItemStyleData(
                                  height: 40,
                                  padding: EdgeInsets.only(left: 14, right: 14),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      TextWidget(context, "Erection Scope"),
                      //dd
                      DropdownButtonHideUnderline(
                        child: Row(
                          children: [
                            Expanded(
                              child: DropdownButton2<String>(
                                hint: Text(
                                  "Select Erection Scope",
                                  style: const TextStyle(fontSize: 14),
                                ),
                                items:
                                provider.erectionScope
                                    .map(
                                      (e) => DropdownMenuItem<String>(
                                    value: e!,
                                    child: Text(
                                      e,
                                      style: const TextStyle(
                                        fontSize: 14,
                                      ),
                                    ),
                                  ),
                                )
                                    .toList(),
                                value:provider.selectedErectionScope,
                                onChanged: (String? value) {
                                  if (provider.erectionScope.isNotEmpty) {
                                    provider.selectedErectionScope = value;
                                  }
                                },
                                buttonStyleData: ddtheme.buttonStyleData,
                                iconStyleData: ddtheme.iconStyleData,
                                menuItemStyleData: ddtheme.menuItemStyleData,
                                dropdownStyleData: ddtheme.dropdownStyleData,
                              ),
                            ),
                          ],
                        ),
                      ),

                    ],
                  ),
                ),
              ),
              floatingActionButtonLocation:
              FloatingActionButtonLocation.centerFloat,
              bottomNavigationBar: InkResponse(
                onTap:
                provider.submitClicked
                    ? null
                    : () {
                  provider.submitClicked = true;
                  provider.ordersEditOrderAPISubmitFunction(context, widget.orderID, provider.selectedDispatchStateID, provider.selectedDispatchDistrictId, provider.selectedDispatchSubLocID,
                      provider.selectedUnloadingScope, provider.selectedFreightScope, provider.selectedErectionScope);
                },
                child: Container(
                  height: 45,
                  alignment: Alignment.center,
                  margin: EdgeInsets.symmetric(horizontal: 10, vertical: 15),
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  decoration: BoxDecoration(
                    color: AppColors.app_blue,
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child:
                  provider.submitClicked
                      ? CircularProgressIndicator.adaptive(
                    valueColor: AlwaysStoppedAnimation<Color>(
                      AppColors.white,
                    ),
                  )
                      : Text(
                    "Submit",
                    style: TextStyle(
                      fontSize: 15,
                      fontFamily: "JakartaMedium",
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
          ),
          onWillPop: () async {
            provider.resetForm();
            return _onBackPressed(context);
          },
        );
      },
    );
  }

  Future<void> _showAttachmentSheet(BuildContext context) {
    return showModalBottomSheet(
      useSafeArea: true,
      isDismissible: true,
      isScrollControlled: true,
      showDragHandle: true,
      backgroundColor: Colors.white,
      enableDrag: true,
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return SafeArea(
              child: Consumer<Editorderprovider>(
                builder: (context, provider, child) {
                  return Padding(
                    padding: EdgeInsets.only(
                      bottom:
                      MediaQuery.of(
                        context,
                      ).viewInsets.bottom, // This handles keyboard
                    ),
                    child: Container(
                      margin: EdgeInsets.only(
                        bottom: 15,
                        left: 15,
                        right: 15,
                        top: 10,
                      ),

                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Align(
                              alignment: Alignment.center,
                              child: Text(
                                "Select Source",
                                style: TextStyle(
                                  color: AppColors.app_blue,
                                  fontFamily: "JakrtaMedium",
                                  fontSize: 16,
                                ),
                              ),
                            ),
                            SizedBox(height: 15),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                provider.imgFromGallery(context);
                              },
                              child: Container(
                                height: 35,
                                child: Text("Select photo from gallery"),
                              ),
                            ),
                            SizedBox(height: 10),
                            InkWell(
                              onTap: () {
                                Navigator.of(context).pop(false);
                                provider.imgFromCamera(context);
                              },
                              child: Container(
                                height: 35,
                                child: Text("Capture photo from camera"),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}



