import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';

class CustomCountryDropdown extends StatefulWidget {
  final List<CountryEnum> countryList;
  final Function(CountryEnum)? onCountryChange;
  final Function(String)? onPhoneNumberChanged;
  final bool isFromBottomSheet;
  final bool isEnableTextField;
  final Widget? textField;

  const CustomCountryDropdown({
    super.key,
    required this.countryList,
    this.onCountryChange,
    this.onPhoneNumberChanged,
    this.isFromBottomSheet = false,
    this.isEnableTextField = false,
    this.textField,
  });

  @override
  CustomCountryDropdownState createState() => CustomCountryDropdownState();
}

class CustomCountryDropdownState extends State<CustomCountryDropdown> {
  CountryEnum? selectedCountry;
  OverlayEntry? _overlayEntry;
  Timer? _showDropdownTimer;
  Timer? _refocusTimer;
  bool _isDropdownOpen = false;
  FocusNode textFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    selectedCountry = CountryEnum.saudiArabia;

    if (widget.isEnableTextField && widget.isFromBottomSheet) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted && textFocusNode.canRequestFocus) {
          FocusScope.of(context).requestFocus(textFocusNode);
        }
      });
    }
  }

  @override
  void dispose() {
    _showDropdownTimer?.cancel();
    _refocusTimer?.cancel();
    _removeOverlayEntry();
    textFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();
    return Row(
      children: [
        GestureDetector(
          onTap: () {
            if (_isDropdownOpen) {
              _closeDropdown();
            } else {
              _openDropdown();
            }
          },
          child: Row(
            children: [
              Utils.buildSvgWithAssets(
                  icon: selectedCountry != null
                      ? selectedCountry!.iconPath
                      : AppAssets.ksa,
                  width: 40.h,
                  height: 40.h,
                  applyThemeColor: false),
              SizedBox(width: 8.h),
              Utils.buildSvgWithAssets(
                  icon: _isDropdownOpen
                      ? AppAssets.dropdow_icon
                      : AppAssets.dropdow_icon),
            ],
          ),
        ),
        SizedBox(width: 4.h),
        if (widget.isFromBottomSheet)
          GestureDetector(
            onTap: () {
              if (widget.isEnableTextField && textFocusNode.canRequestFocus) {
                FocusScope.of(context).requestFocus(textFocusNode);
              }
            },
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  LocaleKeys.phoneNumber.tr(),
                  style: TextStyle(
                      fontSize: 12.f,
                      height: 1.5,
                      fontWeight: FontWeight.w600,
                      letterSpacing: -1),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    if (selectedCountry != CountryEnum.others)
                      Text(
                        selectedCountry!.countryCode,
                        style: TextStyle(
                            fontSize: 12.f,
                            fontWeight: FontWeight.w600,
                            letterSpacing: -0.4,
                            height: 1.5,
                            fontFamily: "Poppins"),
                      ),
                    if (selectedCountry != CountryEnum.others)
                      SizedBox(width: 4.h),
                    if (widget.isEnableTextField)
                      SizedBox(
                        height: 20.h,
                        width: 200.h,
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: TextField(
                            focusNode: textFocusNode,
                            style: TextStyle(
                                fontSize: 12.f,
                                fontWeight: FontWeight.w600,
                                letterSpacing: -0.4,
                                height: 1.5,
                                fontFamily: "Poppins"),
                            decoration: InputDecoration(
                              hintText: selectedCountry == CountryEnum.others
                                  ? "001*******"
                                  : "",
                              isDense: true,
                              border: InputBorder.none,
                              contentPadding: EdgeInsets.zero,
                            ),
                            keyboardType: TextInputType.phone,
                            onChanged: widget.onPhoneNumberChanged,
                          ),
                        ),
                      ),
                  ],
                )
              ],
            ),
          ),
        if (!widget.isFromBottomSheet)
          Text(
            selectedCountry != null
                ? appState.getLanguageCode() == "ar"
                ? selectedCountry!.nameArabic
                : selectedCountry!.displayName
                : LocaleKeys.selectCountry.tr(),
            style: TextStyle(
                fontSize: 14.f,
                height: 21 / 14,
                fontWeight: FontWeight.w600,
                letterSpacing: -0.2),
          ),
      ],
    );
  }

  void _openDropdown() {
    if (!mounted || _isDropdownOpen || _overlayEntry != null) return;

    _showDropdownTimer?.cancel();
    if (textFocusNode.hasFocus) {
      textFocusNode.unfocus();
      // Wait for keyboard to close before calculating position
      _showDropdownTimer = Timer(const Duration(milliseconds: 300), () {
        _showDropdownTimer = null;
        if (mounted) {
          _showDropdown();
        }
      });
    } else {
      _showDropdown();
    }
  }

  void _showDropdown() {
    if (!mounted || _isDropdownOpen || _overlayEntry != null) return;

    AppState appState = getIt.get<AppState>();
    final renderObject = context.findRenderObject();
    final overlay = Overlay.maybeOf(context);
    if (renderObject is! RenderBox ||
        !renderObject.attached ||
        overlay == null) {
      return;
    }

    final renderBox = renderObject;
    Offset offset = renderBox.localToGlobal(Offset.zero);
    bool isRtl = appState.getLanguageCode() == "ar";
    double leftPosition;
    if (isRtl) {
      leftPosition = offset.dx;
    } else {
      leftPosition = offset.dx;
    }

    final overlayEntry = OverlayEntry(
      builder: (context) => Stack(
        children: [
          Positioned.fill(
            child: GestureDetector(
              onTap: _closeDropdown,
              behavior: HitTestBehavior.translucent,
              child: Container(),
            ),
          ),
          Positioned(
            top: offset.dy + renderBox.size.height,
            left: leftPosition,
            width: !widget.isFromBottomSheet ? renderBox.size.width : 60.h,
            child: Material(
              child: Container(
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: Colors.white, borderRadius: 12),
                child: Column(
                  children: widget.countryList
                      .map(
                        (country) => GestureDetector(
                        onTap: () => _selectCountry(country),
                        child: Container(
                          padding: EdgeInsets.symmetric(
                              vertical: 8.h, horizontal: 8.h),
                          decoration: RoundedRectangleBorder()
                              .toSmoothCornerDecoration(borderRadius: 16.h),
                          child: Row(
                            children: [
                              Utils.buildSvgWithAssets(
                                  icon: country.iconPath,
                                  width: 38.h,
                                  height: 38.h,
                                  applyThemeColor: false),
                              if (!widget.isFromBottomSheet)
                                SizedBox(width: 12.h),
                              if (!widget.isFromBottomSheet)
                                Text(
                                    appState.getLanguageCode() == "ar"
                                        ? country.nameArabic
                                        : country.displayName,
                                    style: TextStyle(
                                        fontSize: 14.f,
                                        height: 21 / 14,
                                        fontWeight: FontWeight.w600,
                                        letterSpacing: -0.2)),
                            ],
                          ),
                        )),
                  )
                      .toList(),
                ),
              ),
            ),
          ),
        ],
      ),
    );

    overlay.insert(overlayEntry);
    _overlayEntry = overlayEntry;
    setState(() {
      _isDropdownOpen = true;
    });
  }

  // void _openDropdown() {
  //   if (textFocusNode.hasFocus) {
  //     textFocusNode.unfocus();
  //   }
  //   AppState appState = getIt.get<AppState>();
  //   RenderBox renderBox = context.findRenderObject() as RenderBox;
  //   Offset offset = renderBox.localToGlobal(Offset.zero);
  //
  //   _overlayEntry = OverlayEntry(
  //     builder: (context) => Stack(
  //       children: [
  //         Positioned.fill(
  //           child: GestureDetector(
  //             onTap: _closeDropdown,
  //             behavior: HitTestBehavior.translucent,
  //             child: Container(),
  //           ),
  //         ),
  //         Positioned(
  //           top: offset.dy + renderBox.size.height,
  //           left: offset.dx,
  //           width: !widget.isFromBottomSheet ? renderBox.size.width : 60.h,
  //           child: Material(
  //             child: Container(
  //               decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: Colors.white, borderRadius: 12),
  //               child: Column(
  //                 children: widget.countryList
  //                     .map(
  //                       (country) => GestureDetector(
  //                           onTap: () {
  //                             setState(() {
  //                               selectedCountry = country;
  //                             });
  //                             widget.onCountryChange?.call(country);
  //                             _closeDropdown();
  //                           },
  //                           child: Container(
  //                             padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 8.h),
  //                             decoration: RoundedRectangleBorder().toSmoothCornerDecoration(borderRadius: 16.h),
  //                             child: Row(
  //                               children: [
  //                                 Utils.buildSvgWithAssets(icon: country.iconPath, width: 38.h, height: 38.h),
  //                                 if (!widget.isFromBottomSheet) SizedBox(width: 12.h),
  //                                 if (!widget.isFromBottomSheet)
  //                                   Text(appState.getLanguageCode() == "ar" ? country.nameArabic : country.displayName,
  //                                       style: TextStyle(fontSize: 14.fSize, height: 21 / 14, isBold: true, letterSpacing: -0.2)),
  //                               ],
  //                             ),
  //                           )),
  //                     )
  //                     .toList(),
  //               ),
  //             ),
  //           ),
  //         ),
  //       ],
  //     ),
  //   );
  //
  //   Overlay.of(context)?.insert(_overlayEntry);
  //   setState(() {
  //     _isDropdownOpen = true;
  //   });
  // }

  void _selectCountry(CountryEnum country) {
    if (!mounted) {
      _removeOverlayEntry();
      return;
    }

    _removeOverlayEntry();
    setState(() {
      selectedCountry = country;
      _isDropdownOpen = false;
    });

    // Notify the parent only after this widget has finished updating and
    // removing its overlay. The callback may synchronously close the parent.
    widget.onCountryChange?.call(country);
    _scheduleTextFieldRefocus();
  }

  void _closeDropdown() {
    _showDropdownTimer?.cancel();
    _showDropdownTimer = null;
    _removeOverlayEntry();

    if (!mounted) {
      _isDropdownOpen = false;
      return;
    }

    if (_isDropdownOpen) {
      setState(() {
        _isDropdownOpen = false;
      });
    }

    _scheduleTextFieldRefocus();
  }

  void _removeOverlayEntry() {
    final overlayEntry = _overlayEntry;
    _overlayEntry = null;
    if (overlayEntry == null) return;

    overlayEntry.remove();
    overlayEntry.dispose();
  }

  void _scheduleTextFieldRefocus() {
    _refocusTimer?.cancel();
    if (widget.isEnableTextField && widget.isFromBottomSheet) {
      _refocusTimer = Timer(const Duration(milliseconds: 100), () {
        _refocusTimer = null;
        if (mounted && textFocusNode.canRequestFocus) {
          FocusScope.of(context).requestFocus(textFocusNode);
        }
      });
    }
  }
}