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/route_extensions.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/water_monitor/models/water_cup_model.dart';
import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.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/common_bottom_sheet.dart';
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';

/// Bottom sheet to switch between existing cups or add new custom cup
void showSwitchCupBottomSheet(BuildContext context) {
  final isArabic = getIt.get<AppState>().isArabic();

  return showCommonBottomSheetWithoutHeight(
    context,
    titleWidget: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        (isArabic ? "تبديل الأكواب" : "Switch Cups").toText20(isBold: true),
        (isArabic ? "اختر حجم الكوب المفضل لديك" : "Select your preferred cup size").toText16(isBold: true, color: AppColors.greyTextColor),
      ],
    ),
    child: SwitchCupBottomSheet(),
    callBackFunc: () {},
  );
}

class SwitchCupBottomSheet extends StatelessWidget {
  const SwitchCupBottomSheet({super.key});

  @override
  Widget build(BuildContext context) {
    final viewModel = context.watch<WaterMonitorViewModel>();
    final selectedId = viewModel.selectedCup?.id;

    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4,
            crossAxisSpacing: 16.w,
            childAspectRatio: 0.85,
          ),
          itemCount: viewModel.cups.length + 1,
          itemBuilder: (context, index) {
            if (index == viewModel.cups.length) {
              return _buildAddCupItem(context);
            }

            final cup = viewModel.cups[index];
            final isSelected = selectedId == cup.id;

            return _buildCupItem(
              cup: cup,
              isSelected: isSelected,
              onTap: () {
                viewModel.selectCup(cup.id);
                context.pop();
              },
            );
          },
        ),
      ],
    );
  }

  Widget _buildCupItem({required WaterCupModel cup, required bool isSelected, required VoidCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Stack(
            clipBehavior: Clip.none,
            children: [
              Container(
                width: 60.w,
                height: 60.w,
                decoration: BoxDecoration(
                  color: isSelected ? AppColors.primaryRedColor.withOpacity(0.08) : Colors.transparent,
                  borderRadius: BorderRadius.circular(12.r),
                  border: Border.all(
                    color: isSelected ? AppColors.primaryRedColor : AppColors.bgScaffoldColor,
                    width: 1,
                  ),
                ),
                child: Center(
                  child: Utils.buildSvgWithAssets(
                    icon: cup.iconPath,
                    height: 30.h,
                    width: 42.w,
                    iconColor: isSelected ? AppColors.primaryRedColor : null,
                  ),
                ),
              ),
              // Red badge for custom cups (delete)
              if (!cup.isDefault)
                Positioned(
                  top: -6.h,
                  right: -6.w,
                  child: Builder(builder: (ctx) {
                    return InkWell(
                      onTap: () {
                        // call viewmodel remove
                        final vm = ctx.read<WaterMonitorViewModel>();
                        vm.removeCup(cup.id);
                      },
                      child: Container(
                        color: AppColors.whiteColor,
                        child: Utils.buildSvgWithAssets(icon: AppAssets.minimizeIcon, height: 20.w, width: 20.w),
                      ),
                    );
                  }),
                ),
            ],
          ),
          SizedBox(height: 2.h),
          '${cup.capacityMl}ml'.toText10(isBold: true),
        ],
      ),
    );
  }

  Widget _buildAddCupItem(BuildContext context) {
    return GestureDetector(
      onTap: () {
        showCustomizeCupBottomSheet(context);
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: 60.w,
            height: 60.w,
            child: Center(child: Utils.buildSvgWithAssets(icon: AppAssets.cupAdd, height: 30.h, width: 42.w)),
          ),
          SizedBox(height: 4.h),
        LocaleKeys.add.tr(context: context).toText10(isBold: true),
        ],
      ),
    );
  }
}

/// Bottom sheet to customize cup capacity with slider
void showCustomizeCupBottomSheet(BuildContext context, {WaterCupModel? cupToEdit}) {
  return showCommonBottomSheetWithoutHeight(
    context,
    titleWidget: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        LocaleKeys.customizeDrinkCup.tr(context: context).toText20(isBold: true),
      ],
    ),
    child: CustomizeCupBottomSheet(cupToEdit: cupToEdit),
    callBackFunc: () {},
  );
}

class CustomizeCupBottomSheet extends StatefulWidget {
  final WaterCupModel? cupToEdit;

  const CustomizeCupBottomSheet({super.key, this.cupToEdit});

  @override
  State<CustomizeCupBottomSheet> createState() => _CustomizeCupBottomSheetState();
}

class _CustomizeCupBottomSheetState extends State<CustomizeCupBottomSheet> {
  static const int minCapacity = 50;
  static const int maxCapacity = 500;

  late double _currentCapacity;

  @override
  void initState() {
    super.initState();
    _currentCapacity = (widget.cupToEdit?.capacityMl ?? 150).toDouble();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Cup icon with fill level visualization
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              width: 60.w,
              height: 80.h,
              child: Stack(
                alignment: Alignment.bottomCenter,
                children: [
                  // Cup image with dynamic fill
                  SizedBox(
                    width: 60.w,
                    height: 80.h,
                    child: Center(
                      child: Utils.buildSvgWithAssets(
                        icon: AppAssets.cupEmpty,
                        width: 60.w,
                        height: 80.h,
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                  ClipRect(
                    child: Align(
                        alignment: Alignment.bottomCenter,
                        heightFactor: (_currentCapacity / maxCapacity).clamp(0.0, 1.0),
                        child: Utils.buildSvgWithAssets(
                          icon: AppAssets.cupFilled,
                          width: 60.w,
                          height: 80.h,
                          fit: BoxFit.contain,
                        )),
                  ),
                ],
              ),
            ),

            SizedBox(width: 12.w),

            // Slider and labels
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Current value
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      '${_currentCapacity.round()}'.toText32(isBold: true),
                      SizedBox(width: 4.w),
                      Padding(
                        padding: EdgeInsets.only(bottom: 4.h),
                        child: Text(
                          'ml',
                          style: TextStyle(
                            fontSize: 16.f,
                            fontWeight: FontWeight.w600,
                            color: AppColors.greyTextColor,
                            height: 1.0,
                          ),
                        ),
                      ),
                    ],
                  ).paddingOnly(left: 12.w),

                  SizedBox(height: 16.h),

                  // Slider
                  SliderTheme(
                    data: SliderTheme.of(context).copyWith(
                      activeTrackColor: AppColors.primaryRedColor,
                      inactiveTrackColor: AppColors.primaryRedColor.withOpacity(0.2),
                      thumbColor: AppColors.primaryRedColor,
                      overlayColor: AppColors.primaryRedColor.withOpacity(0.2),
                      trackHeight: 4.h,
                      thumbShape: RoundSliderThumbShape(enabledThumbRadius: 10.w),
                    ),
                    child: Slider(
                      value: _currentCapacity,
                      min: minCapacity.toDouble(),
                      max: maxCapacity.toDouble(),
                      divisions: (maxCapacity - minCapacity) ~/ 10,
                      onChanged: (value) => setState(() => _currentCapacity = value),
                    ),
                  ),

                  Align(
                    alignment: Alignment.centerRight,
                    child: 'Max:  $maxCapacity ml'.toText14(
                      color: AppColors.greyTextColor,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),

        SizedBox(height: 24.h),
        CustomButton(
          text: LocaleKeys.select.tr(context: context),
          onPressed: () {
            final newCup = WaterCupModel(
              id: widget.cupToEdit?.id ?? Uuid().v4(),
              name: '${_currentCapacity.round()}ml',
              capacityMl: _currentCapacity.round(),
              iconPath: AppAssets.cupEmpty,
              isDefault: false,
            );

            final viewModel = context.read<WaterMonitorViewModel>();
            if (widget.cupToEdit != null) {
              viewModel.updateCup(newCup);
            } else {
              viewModel.addCup(newCup);
            }
            viewModel.selectCup(newCup.id);

            Navigator.pop(context);
            Navigator.pop(context);
          },
          backgroundColor: AppColors.primaryRedColor,
          textColor: AppColors.whiteColor,
          fontSize: 16.f,
        ),
      ],
    );
  }
}
