import 'package:bookmywages/consts_widgets/app_assets.dart';
import 'package:bookmywages/model/package_model.dart';
import 'package:bookmywages/model/plan_sucess_model.dart';
import 'package:bookmywages/routers/consts_router.dart';
import 'package:bookmywages/view/vendor_main_screens/vendor_maincontoller.dart';
import 'package:bookmywages/viewmodel/api_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

import 'package:shared_preferences/shared_preferences.dart';

class VendorPackagePage extends ConsumerStatefulWidget {
  const VendorPackagePage({super.key});

  @override
  ConsumerState<VendorPackagePage> createState() => _VendorPackagePageState();
}

class _VendorPackagePageState extends ConsumerState<VendorPackagePage> {
  bool isLoading = false;
  @override
  Widget build(BuildContext context) {
    final packageAsyncValue = ref.watch(pacakgeProvider);
    final indexController = InheritedVendorIndexController.of(context);
    // Get screen size for responsive calculations
    final screenSize = MediaQuery.of(context).size;
    final isSmallScreen = screenSize.width < 360;

    return PopScope(
      onPopInvoked: (didPop) {
        if (didPop) {
          // Reset main controller index to 0 when going back
          final indexController = InheritedVendorIndexController.of(context);
          indexController?.changeIndex(0);
        }
      },
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,

          centerTitle: true,
          title: Text(
            "Subscription Plan",
            style: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.bold,
              fontSize: isSmallScreen ? 16 : 18,
            ),
          ),
        ),
        extendBodyBehindAppBar: true,
        body: Container(
          height: double.infinity,
          width: double.infinity,
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage(AppAssets.background),
              fit: BoxFit.cover,
            ),
          ),
          child: SafeArea(
            // Added SafeArea to ensure content doesn't overlap with system UI
            child: Padding(
              padding: EdgeInsets.symmetric(
                horizontal:
                    screenSize.width * 0.04, // Responsive horizontal padding
                vertical:
                    screenSize.height * 0.02, // Responsive vertical padding
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  // Responsive spacing based on screen height
                  SizedBox(height: screenSize.height * 0.05),
                  Text(
                    "Choose your right plan",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontFamily: 'Gilroy-Bold',
                      fontWeight: FontWeight.w400,
                      fontSize: isSmallScreen
                          ? 24
                          : 32, // Smaller font for small screens
                      height: 1.0,
                      letterSpacing: 0.32,
                      color: Colors.black,
                    ),
                  ),
                  SizedBox(height: screenSize.height * 0.01),
                  Text(
                    "Make upgrade your plan and get more advantages of services",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontFamily: 'Gilroy-Bold',
                      fontWeight: FontWeight.w700,
                      fontSize: isSmallScreen
                          ? 13
                          : 15, // Smaller font for small screens
                      height: 1.71,
                      letterSpacing: 0.15,
                      color: Colors.black,
                    ),
                  ),
                  SizedBox(height: screenSize.height * 0.02),
                  packageAsyncValue.when(
                    data: (packages) {
                      final filteredPackages = packages
                          .where((pkg) => pkg.type == 2)
                          .toList();

                      // Responsive container height based on screen size
                      return SizedBox(
                        height:
                            screenSize.height *
                            0.3, // 35% of screen height instead of fixed 250
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: filteredPackages.length,
                          itemBuilder: (context, index) {
                            final PackageModel package =
                                filteredPackages[index];

                            // Calculate responsive card width (based on screen width)
                            final cardWidth = screenSize.width * 0.75 > 250
                                ? 250.0
                                : screenSize.width * 0.75;

                            return Container(
                              width: cardWidth,
                              margin: EdgeInsets.symmetric(
                                horizontal: screenSize.width * 0.02,
                                vertical: screenSize.height * 0.01,
                              ),
                              decoration: BoxDecoration(
                                color: const Color(0xFF334E95),
                                borderRadius: BorderRadius.circular(30),
                                border: Border.all(
                                  color: const Color(0xFF334E95),
                                  width: 1,
                                ),
                                boxShadow: const [
                                  BoxShadow(
                                    color: Color(0x40828282),
                                    offset: Offset(0, 5),
                                    blurRadius: 4,
                                  ),
                                ],
                              ),
                              child: Padding(
                                padding: EdgeInsets.all(
                                  screenSize.width * 0.04,
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Center(
                                      child: Text(
                                        package.name,
                                        style: TextStyle(
                                          fontFamily: 'Gilroy-Bold',
                                          fontWeight: FontWeight.w700,
                                          fontSize: isSmallScreen
                                              ? 16
                                              : 18, // Smaller font for small screens
                                          height: 1.0,
                                          letterSpacing: 0.32,
                                          color: Colors.white,
                                        ),
                                      ),
                                    ),
                                    SizedBox(height: screenSize.height * 0.01),
                                    _buildFeatureRow(
                                      package.description,
                                      isSmallScreen,
                                    ),
                                    SizedBox(height: screenSize.height * 0.02),
                                    _buildFeatureRow(
                                      getFormattedDuration(package.duration),
                                      isSmallScreen,
                                    ),
                                    SizedBox(height: screenSize.height * 0.02),
                                    _buildFeatureRow(
                                      '${package.noOfService} book service',
                                      isSmallScreen,
                                    ),
                                    const Divider(color: Colors.white),
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          package.price,
                                          style: TextStyle(
                                            fontSize: isSmallScreen ? 14 : 16,
                                            color: Colors.white,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                        GestureDetector(
                                          onTap: () => _subscribeToPlan(
                                            package,
                                            indexController,
                                          ),
                                          child: Container(
                                            width: 30,
                                            height: 30,
                                            decoration: const BoxDecoration(
                                              color: Colors.white,
                                              shape: BoxShape.circle,
                                            ),
                                            child: const Icon(
                                              Icons.arrow_forward,
                                              color: Colors.black,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
                      );
                    },
                    loading: () =>
                        const Center(child: CircularProgressIndicator()),
                    error: (error, stack) => Center(
                      child: Text(
                        'Error loading packages: $error',
                        style: const TextStyle(color: Colors.red),
                      ),
                    ),
                  ),
                  SizedBox(height: screenSize.height * 0.01),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  // Extracted feature row widget for better code organization
  Widget _buildFeatureRow(String text, bool isSmallScreen) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const CircleAvatar(radius: 8, backgroundColor: Color(0xFFF9E369)),
        const SizedBox(width: 6),
        Expanded(
          child: Text(
            text,
            style: TextStyle(
              fontSize: isSmallScreen ? 12 : 14,
              color: Colors.white,
            ),
          ),
        ),
      ],
    );
  }

  Future<void> _subscribeToPlan(
    PackageModel package,
    InheritedVendorIndexController? indexController,
  ) async {
    setState(() {
      isLoading = true;
    });

    try {
      final prefs = await SharedPreferences.getInstance();
      final userId = prefs.getString('vendor_id') ?? '';

      final model = PlanSuccessModel(
        userId: userId,
        planId: package.id.toString(),
        duration: package.duration,
        type: package.type,
      );

      final result = await ref
          .read(planSuccessProvider(model).future)
          .catchError((e) {
            Fluttertoast.showToast(
              msg: 'Error: ${e.toString()}',
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
            );
            return false;
          });

      if (result) {
        if (mounted) {
          // Show success popup
          showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: const Text('Success'),
                content: const Text('Plan subscribed successfully!'),
                actions: <Widget>[
                  TextButton(
                    child: const Text('OK'),
                    onPressed: () {
                      Navigator.of(context).pop();

                      Get.offNamed(RouterConts.vendorcategory, arguments: 2);
                    },
                  ),
                ],
              );
            },
          );
        }
      } else {
        if (mounted) {
          // Show error popup
          showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: const Text('Error'),
                content: const Text('Failed to subscribe to plan'),
                actions: <Widget>[
                  TextButton(
                    child: const Text('OK'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            },
          );
        }
      }
    } catch (error) {
      if (mounted) {
        // Show error popup
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('Error'),
              content: Text('Failed to subscribe: ${error.toString()}'),
              actions: <Widget>[
                TextButton(
                  child: const Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  String getFormattedDuration(int duration) {
    if (duration < 30) {
      return '$duration month';
    } else {
      int months = duration ~/ 30;
      return '$months month';
    }
  }
}
