import 'package:country_code_picker/country_code_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:phone_numbers_parser/phone_numbers_parser.dart';
import 'package:sixam_mart/common/widgets/footer_view.dart';
import 'package:sixam_mart/common/widgets/web_page_title_widget.dart';
import 'package:sixam_mart/features/checkout/controllers/checkout_controller.dart';
import 'package:sixam_mart/features/splash/controllers/splash_controller.dart';
import 'package:sixam_mart/features/profile/controllers/profile_controller.dart';
import 'package:sixam_mart/features/address/controllers/address_controller.dart';
import 'package:sixam_mart/features/address/domain/models/address_model.dart';
import 'package:sixam_mart/features/parcel/controllers/parcel_controller.dart';
import 'package:sixam_mart/features/parcel/domain/models/parcel_category_model.dart';
import 'package:sixam_mart/features/auth/controllers/auth_controller.dart';
import 'package:sixam_mart/helper/address_helper.dart';
import 'package:sixam_mart/helper/auth_helper.dart';
import 'package:sixam_mart/helper/custom_validator.dart';
import 'package:sixam_mart/helper/responsive_helper.dart';
import 'package:sixam_mart/helper/route_helper.dart';
import 'package:sixam_mart/util/dimensions.dart';
import 'package:sixam_mart/util/styles.dart';
import 'package:sixam_mart/common/widgets/custom_app_bar.dart';
import 'package:sixam_mart/common/widgets/custom_button.dart';
import 'package:sixam_mart/common/widgets/custom_snackbar.dart';
import 'package:sixam_mart/common/widgets/menu_drawer.dart';
import 'package:sixam_mart/features/parcel/widgets/parcel_view_widget.dart';

class ParcelLocationScreen extends StatefulWidget {
  final ParcelCategoryModel category;
  const ParcelLocationScreen({super.key, required this.category});

  @override
  State<ParcelLocationScreen> createState() => _ParcelLocationScreenState();
}

class _ParcelLocationScreenState extends State<ParcelLocationScreen> with TickerProviderStateMixin {
   final TextEditingController _senderNameController = TextEditingController();
   final TextEditingController _senderPhoneController = TextEditingController();
   final TextEditingController _receiverNameController = TextEditingController();
   final TextEditingController _receiverPhoneController = TextEditingController();
   final TextEditingController _senderStreetNumberController = TextEditingController();
   final TextEditingController _senderHouseController = TextEditingController();
   final TextEditingController _senderFloorController = TextEditingController();
   final TextEditingController _receiverStreetNumberController = TextEditingController();
   final TextEditingController _receiverHouseController = TextEditingController();
   final TextEditingController _receiverFloorController = TextEditingController();
   final TextEditingController _guestSenderEmailController = TextEditingController();
   final TextEditingController _guestReceiverEmailController = TextEditingController();
   final TextEditingController _senderAddressController = TextEditingController();
   final TextEditingController _receiverAddressController = TextEditingController();

  TabController? _tabController;
  String? _countryDialCode;
  bool firstTime = true;
  int selectedIndex = 0;

  @override
  void initState() {
    super.initState();
    initCall();
  }

  Future<void> initCall() async {
    _tabController = TabController(length: 2, initialIndex: 0, vsync: this);

    _countryDialCode = Get.find<AuthController>().getUserCountryCode().isNotEmpty ? Get.find<AuthController>().getUserCountryCode()
        : CountryCode.fromCountryCode(Get.find<SplashController>().configModel!.country!).dialCode;

    Get.find<ParcelController>().setPickupAddress(AddressHelper.getUserAddressFromSharedPref(), false);
    Get.find<ParcelController>().setDestinationAddress(AddressHelper.getUserAddressFromSharedPref(), notify: false);
    Get.find<ParcelController>().setIsPickedUp(true, false);
    Get.find<ParcelController>().setIsSender(true, false);
    Get.find<ParcelController>().setCountryCode(_countryDialCode!, true);
    Get.find<ParcelController>().setCountryCode(_countryDialCode!, false);
    if(AuthHelper.isLoggedIn() && Get.find<AddressController>().addressList == null) {
      Get.find<AddressController>().getAddressList();
    }
    if (AuthHelper.isLoggedIn()){
      if(Get.find<ProfileController>().userInfoModel == null){
        await Get.find<ProfileController>().getUserInfo();
        _senderNameController.text = Get.find<ProfileController>().userInfoModel != null ? '${Get.find<ProfileController>().userInfoModel!.fName??''} ${Get.find<ProfileController>().userInfoModel!.lName??''}' : '';
        _countryDialCode = await splitPhoneNumber(Get.find<ProfileController>().userInfoModel != null ? Get.find<ProfileController>().userInfoModel!.phone! : '', true);
        _senderPhoneController.text = await splitPhoneNumber(Get.find<ProfileController>().userInfoModel != null ? Get.find<ProfileController>().userInfoModel!.phone! : '', false);
      }else{
        _senderNameController.text = '${Get.find<ProfileController>().userInfoModel!.fName??''} ${Get.find<ProfileController>().userInfoModel!.lName??''}';
        _countryDialCode = await splitPhoneNumber(Get.find<ProfileController>().userInfoModel != null ? Get.find<ProfileController>().userInfoModel!.phone! : '', true);
        _senderPhoneController.text = await splitPhoneNumber(Get.find<ProfileController>().userInfoModel != null ? Get.find<ProfileController>().userInfoModel!.phone! : '', false);
      }
      Get.find<ParcelController>().setCountryCode(_countryDialCode!, true);
      Get.find<ParcelController>().setCountryCode(_countryDialCode!, false);
      setState(() {});

    }

    if(!ResponsiveHelper.isDesktop(Get.context)) {
      _tabController?.addListener(() {
        Get.find<ParcelController>().setIsPickedUp(_tabController!.index == 0, false);
        Get.find<ParcelController>().setIsSender(_tabController!.index == 0, true);
      });
    }/* else {
      Get.find<ParcelController>().setIsPickedUp(selectedIndex == 0, false);
      Get.find<ParcelController>().setIsSender(selectedIndex == 0, true);
    }*/
  }

   Future<String> splitPhoneNumber(String number, bool returnCountyCode) async {
    String code = '';
    String pNumber = '';
    try {
      PhoneNumber phoneNumber = PhoneNumber.parse(number);
      code = '+${phoneNumber.countryCode}';
      pNumber = phoneNumber.international.substring(_countryDialCode!.length);
    } catch (e) {
      debugPrint('number can\'t parse : $e');
    }
     if(returnCountyCode) {
       return code;
     } else {
       return pNumber;
     }
   }

  @override
  void dispose() {
    super.dispose();
    _senderNameController.dispose();
    _senderPhoneController.dispose();
    _receiverNameController.dispose();
    _receiverPhoneController.dispose();
    _senderStreetNumberController.dispose();
    _senderHouseController.dispose();
    _senderFloorController.dispose();
    _receiverStreetNumberController.dispose();
    _receiverHouseController.dispose();
    _receiverFloorController.dispose();
    _guestSenderEmailController.dispose();
    _guestReceiverEmailController.dispose();
    _senderAddressController.dispose();
    _receiverAddressController.dispose();
    _tabController?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(title: 'parcel_location'.tr),
      endDrawer: const MenuDrawer(),
      endDrawerEnableOpenDragGesture: false,
      body: SafeArea(
        child: GetBuilder<ParcelController>(builder: (parcelController) {
          return ResponsiveHelper.isDesktop(context) ? webView(parcelController) : Column(children: [

            Expanded(child: Column(children: [

              Center(
                child: Container(
                  alignment: Alignment.center,
                  width: Dimensions.webMaxWidth,
                  margin: EdgeInsets.all(Dimensions.paddingSizeDefault),
                  padding: const EdgeInsets.all(Dimensions.paddingSizeExtraSmall),
                  decoration: BoxDecoration(
                    color: Theme.of(context).disabledColor.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(Dimensions.radiusDefault),
                  ),
                  child: Column(
                    children: [

                      TabBar(
                        padding: EdgeInsets.zero,
                        labelPadding: EdgeInsets.zero,
                        controller: _tabController,
                        indicatorColor: Colors.transparent,
                        indicatorWeight: 0.1,
                        unselectedLabelColor: Colors.black,
                        onTap: (int index) {
                          if(index == 1) {
                            _validateSender(parcelController);
                          }
                        },
                        unselectedLabelStyle: robotoRegular.copyWith(color: Theme.of(context).disabledColor, fontSize: Dimensions.fontSizeSmall),
                        labelStyle: robotoBold.copyWith(fontSize: Dimensions.fontSizeSmall, color: Theme.of(context).primaryColor),
                        tabs: [
                          Container(
                            padding: EdgeInsets.all(Dimensions.paddingSizeSmall),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: parcelController.isSender ? Theme.of(context).primaryColor : null,
                              borderRadius: BorderRadius.circular(Dimensions.radiusDefault),
                            ),
                            child: Text(
                              'sender_info'.tr,
                              style: robotoMedium.copyWith(fontSize: Dimensions.fontSizeLarge, color: parcelController.isSender ? Theme.of(context).cardColor : Theme.of(context).primaryColor),
                            ),
                          ),

                          Container(
                            padding: EdgeInsets.all(Dimensions.paddingSizeSmall),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: parcelController.isSender ? null : Theme.of(context).primaryColor,
                              borderRadius: BorderRadius.circular(Dimensions.radiusDefault),
                            ),
                            child: Text(
                              'receiver_info'.tr,
                              style: robotoMedium.copyWith(fontSize: Dimensions.fontSizeLarge, color: parcelController.isSender ? Theme.of(context).primaryColor : Theme.of(context).cardColor),
                            ),
                          ),
                        ],
                      ),

                    ],
                  ),
                ),
              ),

              Expanded(child: TabBarView(
                controller: _tabController,
                physics: const NeverScrollableScrollPhysics(),
                children: [
                  ParcelViewWidget(
                    isSender: true, nameController: _senderNameController, phoneController: _senderPhoneController, bottomButton: _bottomButton(),
                    streetController: _senderStreetNumberController, floorController: _senderFloorController, houseController: _senderHouseController,
                    countryCode: parcelController.senderCountryCode, guestEmailController: _guestSenderEmailController,
                    senderAddressController: _senderAddressController, receiverAddressController: _receiverAddressController,
                  ),

                  ParcelViewWidget(
                    isSender: false, nameController: _receiverNameController, phoneController: _receiverPhoneController, bottomButton: _bottomButton(),
                    streetController: _receiverStreetNumberController, floorController: _receiverFloorController, houseController: _receiverHouseController,
                    countryCode: parcelController.receiverCountryCode, guestEmailController: _guestReceiverEmailController,
                    senderAddressController: _senderAddressController, receiverAddressController: _receiverAddressController,
                  ),
                ],
              )),
            ])),

            ResponsiveHelper.isDesktop(context) ? const SizedBox() : _bottomButton(),

          ]);
        }),
      ),
    );
  }

  Widget _bottomButton() {
    return GetBuilder<ParcelController>(builder: (parcelController) {
      return CustomButton(
        margin: ResponsiveHelper.isDesktop(context) ? null : const EdgeInsets.all(Dimensions.paddingSizeSmall),
        width: ResponsiveHelper.isDesktop(context) ? 200 : double.infinity,
        buttonText: parcelController.isSender ? 'continue'.tr : 'save_and_continue'.tr,
        onPressed: () async {
          if( (ResponsiveHelper.isDesktop(context) ? selectedIndex == 0 : _tabController!.index == 0)) {
            _validateSender(parcelController);
          } else{
            if(AddressHelper.getUserAddressFromSharedPref() == null) {
             await AddressHelper.saveUserAddressInSharedPref(parcelController.pickupAddress!);
              // Get.back();
              // Get.find<LocationController>().navigateToLocationScreen('home', canRoute: true);
              // return;
            }
            String numberWithCountryCode = '${parcelController.receiverCountryCode??''}${_receiverPhoneController.text.trim()}';
            PhoneValid phoneValid = await CustomValidator.isPhoneValid(numberWithCountryCode);
            numberWithCountryCode = phoneValid.phone;

            if(parcelController.destinationAddress == null) {
              showCustomSnackBar('select_destination_address'.tr);
            } else if(_receiverNameController.text.isEmpty){
              showCustomSnackBar('enter_receiver_name'.tr);
            } else if(_receiverPhoneController.text.isEmpty){
              showCustomSnackBar('enter_receiver_phone_number'.tr);
            } else if (!phoneValid.isValid) {
              showCustomSnackBar('invalid_phone_number'.tr);
            } else {
              AddressModel destination = AddressModel(
                address: parcelController.destinationAddress!.address,
                additionalAddress: parcelController.destinationAddress!.additionalAddress,
                addressType: parcelController.destinationAddress!.addressType,
                contactPersonName: _receiverNameController.text.trim(),
                contactPersonNumber: numberWithCountryCode,
                latitude: parcelController.destinationAddress!.latitude,
                longitude: parcelController.destinationAddress!.longitude,
                method: parcelController.destinationAddress!.method,
                zoneId: parcelController.destinationAddress!.zoneId,
                zoneIds: parcelController.destinationAddress!.zoneIds,
                id: parcelController.destinationAddress!.id,
                streetNumber: _receiverStreetNumberController.text.trim(),
                house: _receiverHouseController.text.trim(),
                floor: _receiverFloorController.text.trim(),
                email: _guestReceiverEmailController.text.trim(),
                zoneData: parcelController.destinationAddress!.zoneData,
              );

              parcelController.setDestinationAddress(destination);

              Get.toNamed(RouteHelper.getParcelRequestRoute(
                widget.category,
                parcelController.pickupAddress!,
                parcelController.destinationAddress!,
              ));
              Get.find<CheckoutController>().updateFirstTime();
              Get.find<CheckoutController>().updateFirstTimeCodActive();
            }
         }
        },
      );
    });
  }

  Future<void> _validateSender(ParcelController parcelController) async {
    String numberWithCountryCode = '${parcelController.senderCountryCode??''}${_senderPhoneController.text.trim()}';
    PhoneValid phoneValid = await CustomValidator.isPhoneValid(numberWithCountryCode);
    numberWithCountryCode = phoneValid.phone;

    if(parcelController.pickupAddress == null) {
      showCustomSnackBar('select_pickup_address'.tr);
      _switchTab(0);
    } else if(_senderNameController.text.isEmpty){
      showCustomSnackBar('enter_sender_name'.tr);
      _switchTab(0);
    } else if(_senderPhoneController.text.isEmpty){
      showCustomSnackBar('enter_sender_phone_number'.tr);
      _switchTab(0);
    } else if (!phoneValid.isValid) {
      showCustomSnackBar('invalid_phone_number'.tr);
      _switchTab(0);
    }else if(AuthHelper.isGuestLoggedIn() && _guestSenderEmailController.text.isEmpty){
      showCustomSnackBar('please_enter_sender_email'.tr);
      _switchTab(0);
    }else if(AuthHelper.isGuestLoggedIn() && !CustomValidator.isEmailValid(_guestSenderEmailController.text.trim())){
      showCustomSnackBar('enter_valid_email_address'.tr);
      _switchTab(0);
    } else{
      AddressModel pickup = AddressModel(
        address: parcelController.pickupAddress!.address,
        additionalAddress: parcelController.pickupAddress!.additionalAddress,
        addressType: parcelController.pickupAddress!.addressType,
        contactPersonName: _senderNameController.text.trim(),
        contactPersonNumber: numberWithCountryCode,
        latitude: parcelController.pickupAddress!.latitude,
        longitude: parcelController.pickupAddress!.longitude,
        method: parcelController.pickupAddress!.method,
        zoneId: parcelController.pickupAddress!.zoneId,
        id: parcelController.pickupAddress!.id,
        zoneIds: parcelController.pickupAddress!.zoneIds,
        streetNumber: _senderStreetNumberController.text.trim(),
        house: _senderHouseController.text.trim(),
        floor: _senderFloorController.text.trim(),
        email: _guestSenderEmailController.text.trim(),
        zoneData: parcelController.pickupAddress!.zoneData,
      );
      parcelController.setPickupAddress(pickup, true);
      _switchTab(1);
    }
  }

  void _switchTab(int index) {
    if(ResponsiveHelper.isDesktop(context)) {
      setState(() {
        selectedIndex = index;
      });
      Get.find<ParcelController>().setIsPickedUp(index == 0, false);
      Get.find<ParcelController>().setIsSender(index == 0, true);
    } else {
      _tabController!.animateTo(index);
    }
  }

  Widget webView(ParcelController parcelController) {
    return Column(
      children: [

        WebScreenTitleWidget(title: 'parcel_delivery_information'.tr),

        Expanded(
          child: SingleChildScrollView(
            padding: const EdgeInsets.only(top: Dimensions.paddingSizeLarge),
            child: FooterView(
              child: Container(
                width: Dimensions.webMaxWidth,
                decoration: BoxDecoration(
                  color: Theme.of(context).cardColor,
                  borderRadius: BorderRadius.circular(Dimensions.radiusDefault),
                  boxShadow: [BoxShadow(
                    color: Colors.grey.withValues(alpha: 0.2), spreadRadius: 1, blurRadius: 7, offset: const Offset(0, 3), // changes position of shadow
                  )],
                ),
                padding: const EdgeInsets.symmetric(vertical: Dimensions.paddingSizeLarge, horizontal: 200),
                child: Column(children: [

                  Container(
                    decoration: BoxDecoration(
                      color: Theme.of(context).disabledColor.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(Dimensions.radiusDefault),
                    ),
                    padding: const EdgeInsets.all(Dimensions.paddingSizeSmall),
                    child: Row(children: [
                      Expanded(
                        child: InkWell(
                          onTap: () {
                             _switchTab(0);
                          },
                          child: Container(
                            padding: EdgeInsets.all(Dimensions.paddingSizeSmall),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: parcelController.isSender ? Theme.of(context).primaryColor : null,
                              borderRadius: BorderRadius.circular(Dimensions.radiusDefault),
                            ),
                            child: Text(
                              'sender_info'.tr,
                              style: robotoMedium.copyWith(fontSize: Dimensions.fontSizeLarge, color: parcelController.isSender ? Theme.of(context).cardColor : Theme.of(context).primaryColor),
                            ),
                          ),
                        ),
                      ),

                      Expanded(
                        child: InkWell(
                          onTap: () {
                            _validateSender(parcelController);
                          },
                          child: Container(
                            padding: EdgeInsets.all(Dimensions.paddingSizeSmall),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: parcelController.isSender ? null : Theme.of(context).primaryColor,
                              borderRadius: BorderRadius.circular(Dimensions.radiusDefault),
                            ),
                            child: Text(
                              'receiver_info'.tr,
                              style: robotoMedium.copyWith(fontSize: Dimensions.fontSizeLarge, color: parcelController.isSender ? Theme.of(context).primaryColor : Theme.of(context).cardColor),
                            ),
                          ),
                        ),
                      ),
                    ]),
                  ),
                  const SizedBox(height: Dimensions.paddingSizeLarge),

                  selectedIndex == 0 ? ParcelViewWidget(
                    isSender: true, nameController: _senderNameController, phoneController: _senderPhoneController, bottomButton: _bottomButton(),
                    streetController: _senderStreetNumberController, floorController: _senderFloorController, houseController: _senderHouseController,
                    countryCode: parcelController.senderCountryCode, guestEmailController: _guestSenderEmailController,
                    senderAddressController: _senderAddressController, receiverAddressController: _receiverAddressController,
                  ) : ParcelViewWidget(
                      isSender: false, nameController: _receiverNameController, phoneController: _receiverPhoneController, bottomButton: _bottomButton(),
                      streetController: _receiverStreetNumberController, floorController: _receiverFloorController, houseController: _receiverHouseController,
                      countryCode: parcelController.receiverCountryCode, guestEmailController: _guestReceiverEmailController,
                      senderAddressController: _senderAddressController, receiverAddressController: _receiverAddressController,
                    ),
                  // TabBar(
                  //   padding: EdgeInsets.zero,
                  //   labelPadding: EdgeInsets.zero,
                  //   controller: _tabController,
                  //   indicatorColor: Colors.transparent,
                  //   indicatorWeight: 0.1,
                  //   unselectedLabelColor: Colors.black,
                  //   onTap: (int index) {
                  //     if(index == 1) {
                  //       _validateSender(parcelController);
                  //     }
                  //   },
                  //   unselectedLabelStyle: robotoRegular.copyWith(color: Theme.of(context).disabledColor, fontSize: Dimensions.fontSizeSmall),
                  //   labelStyle: robotoBold.copyWith(fontSize: Dimensions.fontSizeSmall, color: Theme.of(context).primaryColor),
                  //   tabs: [
                  //     Container(
                  //       padding: EdgeInsets.all(Dimensions.paddingSizeSmall),
                  //       alignment: Alignment.center,
                  //       decoration: BoxDecoration(
                  //         color: parcelController.isSender ? Theme.of(context).primaryColor : null,
                  //         borderRadius: BorderRadius.circular(Dimensions.radiusDefault),
                  //       ),
                  //       child: Text(
                  //         'sender_info'.tr,
                  //         style: robotoMedium.copyWith(fontSize: Dimensions.fontSizeLarge, color: parcelController.isSender ? Theme.of(context).cardColor : Theme.of(context).primaryColor),
                  //       ),
                  //     ),
                  //
                  //     Container(
                  //       padding: EdgeInsets.all(Dimensions.paddingSizeSmall),
                  //       alignment: Alignment.center,
                  //       decoration: BoxDecoration(
                  //         color: parcelController.isSender ? null : Theme.of(context).primaryColor,
                  //         borderRadius: BorderRadius.circular(Dimensions.radiusDefault),
                  //       ),
                  //       child: Text(
                  //         'receiver_info'.tr,
                  //         style: robotoMedium.copyWith(fontSize: Dimensions.fontSizeLarge, color: parcelController.isSender ? Theme.of(context).primaryColor : Theme.of(context).cardColor),
                  //       ),
                  //     ),
                  //   ],
                  // ),

                  // TabBarView(
                  //   controller: _tabController,
                  //   physics: const NeverScrollableScrollPhysics(),
                  //   children: [
                  //     ParcelViewWidget(
                  //       isSender: true, nameController: _senderNameController, phoneController: _senderPhoneController, bottomButton: _bottomButton(),
                  //       streetController: _senderStreetNumberController, floorController: _senderFloorController, houseController: _senderHouseController,
                  //       countryCode: parcelController.senderCountryCode, guestEmailController: _guestSenderEmailController,
                  //       senderAddressController: _senderAddressController, receiverAddressController: _receiverAddressController,
                  //     ),
                  //
                  //     ParcelViewWidget(
                  //       isSender: false, nameController: _receiverNameController, phoneController: _receiverPhoneController, bottomButton: _bottomButton(),
                  //       streetController: _receiverStreetNumberController, floorController: _receiverFloorController, houseController: _receiverHouseController,
                  //       countryCode: parcelController.receiverCountryCode, guestEmailController: _guestReceiverEmailController,
                  //       senderAddressController: _senderAddressController, receiverAddressController: _receiverAddressController,
                  //     ),
                  //   ],
                  // ),

                ]),
              ),
            ),
          ),
        ),
      ],
    );
  }

}
