import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:gen_rentals/Screens/BillScreens/BillDetailListScreen.dart';
import 'package:gen_rentals/Utility/Reusablewidgets.dart';
import 'package:provider/provider.dart';
import '../Models/SubscribeOrderDetailsResponse.dart';
import '../Notifier/SubscribeOrderDetailsProvider.dart';
import '../Utility/AppColors.dart';
import 'HelpScreens/CreateTicketScreen.dart';

class ProductsDetailScreen extends StatefulWidget {
  final String sessionId;
  final String orderId;
  final String accId;

  const ProductsDetailScreen({
    super.key,
    required this.sessionId,
    required this.orderId,
    required this.accId,
  });

  @override
  State<ProductsDetailScreen> createState() => _ProductsDetailScreenState();
}

class _ProductsDetailScreenState extends State<ProductsDetailScreen> {
  final List<Map<String, dynamic>> createNewTickets = [
    {
      'title': 'Payment Issues',
      'description': 'Get help with payment related problems',
      'icon': "assets/svg/rupee_coin_ic.svg",
      'color': Color(0xFFFFEFBE),
    },
    {
      'title': 'Bill Related Issues',
      'description': 'Resolve bill and invoice matters',
      'icon': "assets/svg/know_pay.svg",
      'color': Color(0xFFCEF9FF),
    },
    {
      'title': 'Other Issues',
      'description': 'Any other support you need',
      'icon': "assets/svg/help_ic.svg",
      'color': Color(0xFFE4E5FF),
    },
  ];

  @override
  void initState() {
    super.initState();
    // Fetch order details when screen loads
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadOrderDetails();
    });
  }

  void _loadOrderDetails() {
    final provider = Provider.of<SubscribeOrderDetailsProvider>(context, listen: false);
    provider.fetchSubscribeOrderDetails(
      widget.sessionId,
      widget.orderId,
      widget.accId,
    );
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final screenHeight = MediaQuery.of(context).size.height;
    final isSmallScreen = screenWidth < 360;
    final isLargeScreen = screenWidth > 400;

    return Consumer<SubscribeOrderDetailsProvider>(
      builder: (context, provider, child) {
        return SafeArea(
          top: false,
          child: Scaffold(
            appBar: AppBar(
              automaticallyImplyLeading: false,
              backgroundColor: Colors.white,
              title: Row(
                children: [
                  InkResponse(
                    onTap: () => Navigator.pop(context, true),
                    child: SvgPicture.asset(
                      "assets/svg/continue_left_ic.svg",
                      height: screenWidth * 0.075, // Responsive icon size
                    ),
                  ),
                  SizedBox(width: screenWidth * 0.025),
                  Text(
                    "Order Details",
                    style: TextStyle(
                      fontFamily: "Poppins",
                      fontSize: isSmallScreen ? 14 : 16,
                      fontWeight: FontWeight.w400,
                      color: Colors.black87,
                    ),
                  ),
                ],
              ),
            ),
            backgroundColor: AppColors.backgroundRegular,
            body: RefreshIndicator.adaptive(
              color: AppColors.subtitleText,
              onRefresh: () async {
                final provider = Provider.of<SubscribeOrderDetailsProvider>(context, listen: false);
                await provider.fetchSubscribeOrderDetails(
                  widget.sessionId,
                  widget.orderId,
                  widget.accId,
                );
              },
              child: _buildBody(provider, screenWidth, screenHeight),
            ),
            bottomNavigationBar: Container(
              height: screenHeight * 0.085, // Responsive height
              padding: EdgeInsets.symmetric(
                horizontal: screenWidth * 0.048,
                vertical: screenHeight * 0.012,
              ),
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () {
                  final order = provider.orderDetails!;
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => BillDetailListScreen(
                        sessionId: widget.sessionId,
                        orderId: order.orderid.toString(),
                        accId: widget.accId,
                      ),
                    ),
                  );
                  FocusScope.of(context).unfocus();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.buttonColor,
                  foregroundColor: Colors.white,
                  padding: EdgeInsets.symmetric(vertical: screenHeight * 0.018),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(screenWidth * 0.07),
                  ),
                  elevation: 0,
                ),
                child: Text(
                  "View Bill",
                  style: TextStyle(
                    fontFamily: "Poppins",
                    fontSize: isSmallScreen ? 13 : 14,
                    fontWeight: FontWeight.w500,
                    fontStyle: FontStyle.normal,
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildBody(SubscribeOrderDetailsProvider provider, double screenWidth, double screenHeight) {
    final isSmallScreen = screenWidth < 360;
    final bottomPadding = MediaQuery.of(context).padding.bottom;

    if (provider.isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (provider.errorMessage.isNotEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              provider.errorMessage,
              style: TextStyle(
                fontSize: isSmallScreen ? 14 : 16,
                fontFamily: "Poppins",
                color: Colors.red,
              ),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: screenHeight * 0.02),
            ElevatedButton(
              onPressed: _loadOrderDetails,
              child: const Text('Retry'),
            ),
          ],
        ),
      );
    }

    if (provider.orderDetails == null) {
      return Center(
        child: Text(
          'No order details found',
          style: TextStyle(
            fontSize: isSmallScreen ? 14 : 16,
            fontFamily: "Poppins",
            color: Colors.grey,
          ),
        ),
      );
    }

    final order = provider.orderDetails!;

    return Container(
      color: AppColors.backgroundRegular,
      height: screenHeight,
      child: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(height: screenHeight * 0.001),
            // Order header (not in card)
            Padding(
              padding: EdgeInsets.all(screenWidth * 0.035),
              child: Container(
                width: double.infinity,
                margin: const EdgeInsets.all(0),
                padding: EdgeInsets.symmetric(
                  horizontal: 0,
                  vertical: screenHeight * 0.02,
                ),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(screenWidth * 0.06),
                  gradient: const LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0xFFFFFFFF),
                      Color(0xAAFFFFFF),
                      Color(0xFFFFFFFF),
                    ],
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: screenHeight * 0.002),
                    Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: screenWidth * 0.035,
                        vertical: screenHeight * 0.007,
                      ),
                      decoration: const BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.topRight,
                          colors: [
                            Color(0xffD4EFFF),
                            Color(0xFFFFFFFF),
                          ],
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                "Order ID #${order.orderNum ?? order.orderid ?? 'N/A'}",
                                style: TextStyle(
                                  fontSize: isSmallScreen ? 12 : 14,
                                  fontFamily: "Poppins",
                                  fontWeight: FontWeight.w400,
                                  color: AppColors.amountText,
                                ),
                              ),
                              SizedBox(height: screenHeight * 0.005),
                              Text(
                                "${order.fromDate} - ${order.toDate ?? 'Duration unavailable'}",
                                style: TextStyle(
                                  fontSize: isSmallScreen ? 10 : 12,
                                  fontFamily: "Poppins",
                                  fontWeight: FontWeight.w400,
                                  color: AppColors.normalText,
                                ),
                              ),
                            ],
                          ),
                          Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: screenWidth * 0.025,
                              vertical: screenHeight * 0.007,
                            ),
                            decoration: BoxDecoration(
                              gradient: _getGradientByColor(order.expiringInColor),
                              borderRadius: BorderRadius.circular(screenWidth * 0.02),
                            ),
                            child: Text(
                              order.expiringText ?? 'Expiring info not available',
                              style: TextStyle(
                                fontSize: isSmallScreen ? 10 : 12,
                                fontFamily: "Poppins",
                                fontWeight: FontWeight.w400,
                                color: Colors.black87,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: screenHeight * 0.015),
                    Padding(
                      padding: EdgeInsets.symmetric(
                        horizontal: screenWidth * 0.035,
                        vertical: screenHeight * 0.005,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "Address",
                            style: TextStyle(
                              fontSize: isSmallScreen ? 11 : 12,
                              fontFamily: "Poppins",
                              fontWeight: FontWeight.w400,
                              color: AppColors.normalText,
                            ),
                          ),
                          SizedBox(height: screenHeight * 0.01),
                          Text(
                            order.accName ?? ' A/c not available',
                            style: TextStyle(
                              fontSize: isSmallScreen ? 13 : 14,
                              fontFamily: "Poppins",
                              fontWeight: FontWeight.w500,
                              color: Colors.black87,
                            ),
                          ),
                          SizedBox(height: screenHeight * 0.012),
                          Text(
                            order.adress ?? "Address unavailable",
                            style: TextStyle(
                              fontSize: isSmallScreen ? 11 : 12,
                              fontFamily: "Poppins",
                              fontWeight: FontWeight.w400,
                              color: AppColors.subtitleText,
                            ),
                            textAlign: TextAlign.start,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // Products section
            if (order.products != null && order.products!.isNotEmpty)
              Container(
                width: double.infinity,
                margin: EdgeInsets.symmetric(horizontal: screenWidth * 0.005),
                padding: EdgeInsets.all(screenWidth * 0.04),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SectionHeading(
                      title: "Rental Items",
                      textStyle: TextStyle(
                        fontSize: isSmallScreen ? 13 : 14,
                        fontFamily: "Poppins",
                        fontWeight: FontWeight.w500,
                        color: Colors.black87,
                      ),
                    ),
                    SizedBox(height: screenHeight * 0.015),

                    // Product list using ListView.builder
                    ListView.separated(
                      physics: const NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemCount: order.products!.length,
                      separatorBuilder: (context, index) =>
                          SizedBox(height: screenHeight * 0.02),
                      itemBuilder: (context, index) {
                        return _buildProductItem(order.products![index], screenWidth, screenHeight);
                      },
                    ),

                    SizedBox(height: screenHeight * 0.03),
                    SectionHeading(
                      title: "Purchased Items",
                      textStyle: TextStyle(
                        fontSize: isSmallScreen ? 13 : 14,
                        fontFamily: "Poppins",
                        fontWeight: FontWeight.w500,
                        color: Colors.black87,
                      ),
                    ),

                    SizedBox(height: screenHeight * 0.015),
                    // Product list using ListView.builder
                    ListView.separated(
                      physics: const NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemCount: order.purchasedItm!.length,
                      separatorBuilder: (context, index) =>
                          SizedBox(height: screenHeight * 0.02),
                      itemBuilder: (context, index) {
                        return _buildPurchasedItem(order.purchasedItm![index], screenWidth, screenHeight);
                      },
                    ),
                    SizedBox(height: screenHeight * 0.017),

                    // Help section
                    InkResponse(
                      onTap: () => _showReasonBottomSheet(order.orderid.toString(), screenWidth, screenHeight),
                      child: Row(
                        children: [
                          SvgPicture.asset(
                            "assets/svg/have_compaints.svg",
                            height: screenWidth * 0.075,
                            width: screenWidth * 0.075,
                          ),
                          SizedBox(width: screenWidth * 0.02),
                          Text(
                            "Need help with this order?",
                            style: TextStyle(
                              fontSize: isSmallScreen ? 13 : 14,
                              fontFamily: "Poppins",
                              fontWeight: FontWeight.w400,
                              color: AppColors.amountText,
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: screenHeight * 0.02),
                  ],
                ),
              )
            else
              Padding(
                padding: EdgeInsets.all(screenWidth * 0.04),
                child: Text(
                  'No products found',
                  style: TextStyle(
                    fontSize: isSmallScreen ? 14 : 16,
                    fontFamily: "Poppins",
                    color: Colors.grey,
                  ),
                ),
              ),
            SizedBox(height: bottomPadding + screenHeight * 0.025),
          ],
        ),
      ),
    );
  }

  Widget _buildProductItem(Products product, double screenWidth, double screenHeight) {
    final isSmallScreen = screenWidth < 360;

    return Container(
      padding: EdgeInsets.all(screenWidth * 0.04),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(screenWidth * 0.045),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Product ID and Name
          Text(
            "#${product.idName}",
            style: TextStyle(
              fontSize: isSmallScreen ? 12 : 14,
              fontFamily: "Poppins",
              fontWeight: FontWeight.w400,
              color: AppColors.amountText,
            ),
          ),
          SizedBox(height: screenHeight * 0.005),
          Text(
            product.prodName ?? 'Product name not available',
            style: TextStyle(
              fontSize: isSmallScreen ? 13 : 14,
              fontFamily: "Poppins",
              fontWeight: FontWeight.w400,
              fontStyle: FontStyle.normal,
              color: Colors.black87,
            ),
          ),
          SizedBox(height: screenHeight * 0.015),

          // Table-like layout for dates and price
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                flex: 8,
                child: Text(
                  product.dispatchDate != null
                      ? "Dispatched On ${product.dispatchDate!}"
                      : "Dispatch date not available",
                  style: TextStyle(
                    fontSize: isSmallScreen ? 10 : 12,
                    fontFamily: "Poppins",
                    fontWeight: FontWeight.w400,
                    color: AppColors.subtitleText,
                  ),
                ),
              ),
              Expanded(
                child: Text(
                  "Plan",
                  style: TextStyle(
                    fontSize: isSmallScreen ? 10 : 12,
                    fontFamily: "Poppins",
                    fontWeight: FontWeight.w400,
                    color: Colors.black54,
                  ),
                ),
              ),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                flex: 7,
                child: Text(
                  product.receivedDate != null
                      ? "Received On ${product.receivedDate!}"
                      : "Receive date not available",
                  style: TextStyle(
                    fontSize: isSmallScreen ? 10 : 12,
                    fontFamily: "Poppins",
                    fontWeight: FontWeight.w400,
                    color: Colors.grey,
                  ),
                ),
              ),
              Text(
                product.totalPrice != null
                    ? "₹${product.totalPrice!}${product.per ?? 'mo'}"
                    : 'Price not available',
                style: TextStyle(
                  fontSize: isSmallScreen ? 12 : 14,
                  fontFamily: "Poppins",
                  fontStyle: FontStyle.normal,
                  fontWeight: FontWeight.w400,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  LinearGradient _getGradientByColor(String? color) {
    switch (color) {
      case "Red":
        return const LinearGradient(
          colors: [Color(0xFFFFEBEB), Color(0xFFFFEBEB)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        );
      case "Green":
      default:
        return const LinearGradient(
          colors: [Color(0xFFE5FFE2), Color(0xFFE5FFE2)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        );
    }
  }

  Widget _buildPurchasedItem(PurchasedItm product, double screenWidth, double screenHeight) {
    final isSmallScreen = screenWidth < 360;

    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: screenWidth * 0.045,
        vertical: screenHeight * 0.018,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(screenWidth * 0.045),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: screenHeight * 0.002),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                flex: 3,
                child: Text(
                  product.prodName ?? 'Unavailable',
                  style: TextStyle(
                    fontSize: isSmallScreen ? 12 : 14,
                    fontFamily: "Poppins",
                    fontWeight: FontWeight.w400,
                    color: Colors.black87,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Expanded(
                flex: 2,
                child: Text(
                  "Qty. ${product.qty ?? 'Unavailable'}",
                  style: TextStyle(
                    fontSize: isSmallScreen ? 10 : 12,
                    fontFamily: "Poppins",
                    fontStyle: FontStyle.normal,
                    fontWeight: FontWeight.w400,
                    color: AppColors.subtitleText,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
              Expanded(
                flex: 2,
                child: Text(
                  "₹${product.totalPrice ?? 'Unavailable'}",
                  style: TextStyle(
                    fontSize: isSmallScreen ? 12 : 14,
                    fontStyle: FontStyle.normal,
                    fontFamily: "Poppins",
                    fontWeight: FontWeight.w400,
                    color: AppColors.cardAmountText,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
            ],
          ),
          SizedBox(height: screenHeight * 0.002),
        ],
      ),
    );
  }

  void _showReasonBottomSheet(String orderId, double screenWidth, double screenHeight) {
    final isSmallScreen = screenWidth < 360;

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      builder: (context) {
        return SafeArea(
          child: Container(
            height: 226,
            padding: EdgeInsets.symmetric(
              horizontal: screenWidth * 0.035,
              vertical: screenHeight * 0.016,
            ),
            constraints: BoxConstraints(
              maxHeight: screenHeight * 0.7,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Center(
                  child: Container(
                    width: screenWidth * 0.12,
                    height: screenHeight * 0.003,
                    decoration: BoxDecoration(
                      color: AppColors.subtitleText,
                      borderRadius: BorderRadius.circular(screenWidth * 0.035),
                    ),
                  ),
                ),
                SizedBox(height: screenHeight * 0.014),
                SectionHeading(
                  title: "Select Your Reason",
                  textStyle: TextStyle(
                    fontSize: isSmallScreen ? 14 : 16,
                    fontFamily: "Poppins",
                    fontWeight: FontWeight.w500,
                    color: AppColors.normalText,
                  ),
                ),
                SizedBox(height: screenHeight * 0.025),
                Expanded(
                  child: GridView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      crossAxisSpacing: screenWidth * 0.03,
                      mainAxisSpacing: screenWidth * 0.03,
                      childAspectRatio: 0.85,
                    ),
                    itemCount: createNewTickets.length,
                    itemBuilder: (context, index) {
                      final ticket = createNewTickets[index];
                      final String title = ticket['title'] ?? 'Unknown';
                      final String description = ticket['description'] ?? '';
                      final String icon = ticket['icon'] ?? 'assets/svg/help_ic.svg';
                      final Color color = ticket['color'] ?? Colors.grey;

                      return _buildFeatureCard(
                        title: title,
                        description: description,
                        orderId: orderId,
                        icon: icon,
                        color: color,
                        screenWidth: screenWidth,
                        bottomSheetContext: context, // Pass bottom sheet context
                      );
                    },
                  ),
                ),
                SizedBox(height: screenHeight * 0.001),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildFeatureCard({
    required String title,
    required String description,
    required String orderId,
    required String icon,
    required Color color,
    required double screenWidth,
    required BuildContext bottomSheetContext, // Add this parameter
  }) {
    final isSmallScreen = screenWidth < 360;
    final iconSize = screenWidth * 0.20;
    final imageSize = screenWidth * 0.09;

    return GestureDetector(
      onTap: () {
        // Close the bottom sheet first
        Navigator.pop(bottomSheetContext);

        // Then navigate to HelpTicketScreen after a small delay for smooth transition
        Future.delayed(Duration(milliseconds: 300), () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HelpTicketScreen(
                reason: title,
                sessionId: widget.sessionId,
                accId: widget.accId,
                orderId: orderId,
              ),
            ),
          );
        });
      },
      child: Container(
        padding: EdgeInsets.symmetric(
            horizontal: screenWidth * 0.005,
            vertical: screenWidth * 0.002
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // Icon container
            Container(
              width: iconSize,
              height: iconSize,
              decoration: BoxDecoration(
                color: color.withOpacity(0.7),
                borderRadius: BorderRadius.circular(screenWidth * 0.03),
              ),
              child: Center(
                child: SizedBox(
                  height: imageSize,
                  width: imageSize,
                  child: SvgPicture.asset(
                    icon,
                    fit: BoxFit.fitWidth,
                  ),
                ),
              ),
            ),
            SizedBox(height: screenWidth * 0.015),
            // Title
            SizedBox(
              width: iconSize,
              child: Text(
                title,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: AppColors.nearDarkText,
                  fontFamily: "Poppins",
                  fontSize: isSmallScreen ? 11 : 13,
                  fontStyle: FontStyle.normal,
                  fontWeight: FontWeight.w400,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            SizedBox(height: screenWidth * 0.005),
          ],
        ),
      ),
    );
  }

}
