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_export.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/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/features/weather/weather_view_model.dart';
import 'package:hmg_patient_app_new/features/weather/models/waether_cities_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/weather/weather_details_page.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

class WeatherWidget extends StatelessWidget {
  final bool showButton;

  const WeatherWidget({super.key, this.showButton = true});

  String _getWeatherIcon(String? categoryValue) {
    if (categoryValue == null) return "assets/images/svg/cloudyweather.svg";

    final lowerValue = categoryValue.toLowerCase();
    if (lowerValue.contains('sunny') || lowerValue.contains('clear')) {
      return "assets/images/svg/morning.svg";
    } else if (lowerValue.contains('cloudy') || lowerValue.contains('cloud')) {
      return "assets/images/svg/cloudyweather.svg";
    } else if (lowerValue.contains('rain')) {
      return "assets/images/svg/cloudyweather.svg";
    }
    return "assets/images/svg/cloudyweather.svg";
  }

  String _formatDateTime(DateTime dateTime) {
    final formatter = DateFormat('MMMM dd, yyyy - EEEE, HH:mm', 'en_US');
    return formatter.format(dateTime);
  }

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt<AppState>();
    return Selector<WeatherMonitorViewModel, ({bool isLoading, bool isLocationAvailable, List<GetCityInfoList> cityInfoList})>(
      selector: (_, vm) => (isLoading: vm.isLoading, isLocationAvailable: vm.isLocationAvailable, cityInfoList: vm.cityInfoList),
      builder: (context, state, child) {
        if (!state.isLocationAvailable) {
          return noWeatherWidget(context).paddingSymmetrical(24.w, 0.w);
        }
        if (state.isLoading) {
          return _buildLoadingState().paddingSymmetrical(24.w, 0.w);
        }


        final currentCity = state.cityInfoList.isNotEmpty ? state.cityInfoList.first : null;
        final now = DateTime.now();
        final temperature = currentCity?.temperature;
        final healthTip = LocaleKeys.healthTipsBasedOnCurrentWeather.tr();

        return Row(
          children: [
            Flexible(
              child: Container(
                padding: EdgeInsets.all(16.w),
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: false),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Utils.buildSvgWithAssets(icon: _getWeatherIcon(currentCity?.categoryValue), width: 64.w, height: 64.w),
                        SizedBox(width: 12.w),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              _formatDateTime(now).toText12(
                                fontWeight: FontWeight.w500,
                                color: AppColors.greyTextColor,
                              ),
                              SizedBox(height: 4.w),
                              "$temperature°C".toText16(
                                isBold: true,
                                weight: FontWeight.w600,
                              ),
                              SizedBox(height: 4.w),
                              healthTip.toText12(
                                color: AppColors.greyTextColor,
                                fontWeight: FontWeight.w500,
                                maxLine: 2,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    if (showButton) ...[
                      SizedBox(height: 16.w),
                      CustomButton(
                        text: appState.isArabic() ?"مؤشرات الطقس الصحية" : "Health weather indicators",
                        onPressed: () {
                          Navigator.of(context).push(
                            CustomPageRoute(
                              page: ChangeNotifierProvider.value(
                                value: context.read<WeatherMonitorViewModel>(),
                                child: const WeatherDetailsPage(),
                              ),
                            ),
                          );
                        },
                        padding: EdgeInsets.zero,
                        backgroundColor: AppColors.infoColor.withValues(alpha: 0.12),
                        borderColor: AppColors.infoColor.withValues(alpha: 0.01),
                        textColor: AppColors.infoColor,
                        fontSize: 14.f,
                        fontWeight: FontWeight.w600,
                        borderRadius: 10.r,
                        height: 40.h,
                      ),
                    ],
                  ],
                ),
              ),
            ),
          ],
        ).paddingSymmetrical(24.w, 0.w);
      },
    );
  }

  Widget noWeatherWidget(BuildContext context) {
    return Container(
        padding: EdgeInsets.all(16.w),
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          color: AppColors.whiteColor,
          borderRadius: 24.r,
          hasShadow: false,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              height: 48.h,
              width: 48.h,
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.greyColor,
                borderRadius: 12.r,
                hasShadow: false,
              ),
              child: Padding(
                padding: EdgeInsets.all(12.h),
                child: Utils.buildSvgWithAssets(icon: AppAssets.location_unavailable_filled, fit: BoxFit.contain, applyThemeColor: false),
              ),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.max,
                children: [
                  _formatDateTime(DateTime.now()).toText12(
                    fontWeight: FontWeight.w500,
                    color: AppColors.greyTextColor,
                  ),
                  SizedBox(height: 4.w),
                  "--".toText16(
                    isBold: true,
                    weight: FontWeight.w600,
                  ),
                  SizedBox(height: 4.w),
                  LocaleKeys.locationServicesDisabled.tr().toText12(
                        color: AppColors.greyTextColor,
                        fontWeight: FontWeight.w500,
                        maxLine: 2,
                      ),
                ],
              ),
            ),
          ],
        )).onPress(() {
      context.read<WeatherMonitorViewModel>().fetchCityInfoList();
    });
  }

  Widget _buildLoadingState() {
    return Column(
      children: [
        Row(
          children: [
            Container(
              width: 64.w,
              height: 64.w,
              decoration: BoxDecoration(
                color: AppColors.lightGrayBGColor,
                borderRadius: BorderRadius.circular(12.r),
              ),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: double.infinity,
                    height: 12.h,
                    decoration: BoxDecoration(
                      color: AppColors.lightGrayBGColor,
                      borderRadius: BorderRadius.circular(6.r),
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Container(
                    width: 100.w,
                    height: 16.h,
                    decoration: BoxDecoration(
                      color: AppColors.lightGrayBGColor,
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Container(
                    width: double.infinity,
                    height: 12.h,
                    decoration: BoxDecoration(
                      color: AppColors.lightGrayBGColor,
                      borderRadius: BorderRadius.circular(6.r),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        SizedBox(height: 16.w),
        Container(
          height: 56.h,
          decoration: BoxDecoration(
            color: AppColors.lightGrayBGColor,
            borderRadius: BorderRadius.circular(10.r),
          ),
        ),
      ],
    );
  }
}
