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) {
    double screenHeight = MediaQuery.of(context).size.height;
    double bottomPadding = MediaQuery.of(context).padding.bottom;

    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: 30,
                    ),
                  ),
                  const SizedBox(width: 10),
                  const Text(
                    "Bill List",
                    style: TextStyle(
                      fontSize: 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, screenHeight, bottomPadding),
            ),
            bottomNavigationBar: Container(
              height: 80,
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
              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: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(28),
                  ),
                  elevation: 0,
                ),
                child: const Text(
                  "View Bill",
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                    fontStyle: FontStyle.normal,
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }


  Widget _buildBody(SubscribeOrderDetailsProvider provider, double screenHeight, double bottomPadding) {
    if (provider.isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

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

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

    final order = provider.orderDetails!;

    return Container(
      color: AppColors.backgroundRegular,
      height: screenHeight,
      child: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(height: 1,),
            // Order header (not in card)
            Padding(
              padding: const EdgeInsets.all(14),
              child: Container(
                width: double.infinity,
                margin: const EdgeInsets.all(0),
                padding: EdgeInsets.symmetric(horizontal: 0, vertical: 16),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(22),
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                      colors: [
                        Color(0xFFFFFFFF),
                        Color(0xAAFFFFFF),
                        Color(0xFFFFFFFF),

                      ]
                  )
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 2,),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                            begin: Alignment.topLeft,
                            end: Alignment.topRight,
                            colors: [
                              Color(0xffD4EFFF),
                              // Color(0xFFFFFFFF),
                              Color(0xFFFFFFFF),
                            ]
                        )
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            children: [
                              Text(
                                "Order ID #${order.orderNum ?? order.orderid ?? 'N/A'}",
                                style: TextStyle(
                                  fontSize: 14,
                                  fontFamily: "Poppins",
                                  fontWeight: FontWeight.w400,
                                  color: AppColors.amountText,
                                ),
                              ),

                              SizedBox(height: 4,),
                              Text(
                                "${order.fromDate} - ${order.toDate ?? 'Duration unavailable'}",
                                style: TextStyle(
                                  fontSize: 12,
                                  fontFamily: "Poppins",
                                  fontWeight: FontWeight.w400,
                                  color: AppColors.normalText,
                                ),
                              ),
                            ],
                          ),
                          Container(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 10, vertical: 6),
                            decoration: BoxDecoration(
                              gradient: _getGradientByColor(order.expiringInColor),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(
                              order.expiringText ?? 'Expiring info not available',
                              style: const TextStyle(
                                fontSize: 12,
                                fontFamily: "Poppins",
                                fontWeight: FontWeight.w400,
                                color: Colors.black87,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 12),
                    //
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 14, vertical: 4),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "Address",
                            style: TextStyle(
                              fontSize: 12,
                              fontFamily: "Poppins",
                              fontWeight: FontWeight.w400,
                              color: AppColors.normalText,
                            ),
                          ),
                          const SizedBox(height: 8),
                          //
                          Text(
                            order.accName ?? ' A/c not available',
                            style: TextStyle(
                              fontSize: 14,
                              fontFamily: "Poppins",
                              fontWeight: FontWeight.w500,
                              color: Colors.black87,
                            ),
                          ),
                          const SizedBox(height: 10),
                          Text(
                            order.adress ?? "Address unavailable",
                            style: TextStyle(
                              fontSize: 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: const EdgeInsets.symmetric(horizontal: 2),
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SectionHeading(
                        title: "Rental Items",
                      textStyle: TextStyle(
                        fontSize: 14,
                        fontFamily: "Poppins",
                        fontWeight: FontWeight.w500,
                        color: Colors.black87,
                      ),
                    ),
                    const SizedBox(height: 12),

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

                    const SizedBox(height: 24),
                    SectionHeading(
                      title: "Purchased Items",
                      textStyle: TextStyle(
                        fontSize: 14,
                        fontFamily: "Poppins",
                        fontWeight: FontWeight.w500,
                        color: Colors.black87,
                      ),
                    ),

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


                    // Divider
                    // const Divider(
                    //   color: Color(0xFFE5E5E5),
                    //   thickness: 1,
                    // ),
                    const SizedBox(height: 16),

                    // Help section
                    InkResponse(
                      onTap: () => _showReasonBottomSheet(order.orderid.toString()),
                      child: Row(
                        children: [
                          SvgPicture.asset(
                            "assets/svg/have_compaints.svg",
                            height: 30,
                            width: 30,
                          ),
                          SizedBox(width: 8,),
                          Text(
                            "Need help with this order?",
                            style: TextStyle(
                              fontSize: 14,
                              fontFamily: "Poppins",
                              fontWeight: FontWeight.w400,
                              color: AppColors.amountText,
                            ),
                          ),

                        ],
                      ),
                    ),
                    const SizedBox(height: 16),

                    // View Bill button

                  ],
                ),
              )
            else
              const Padding(
                padding: EdgeInsets.all(16.0),
                child: Text(
                  'No products found',
                  style: TextStyle(
                    fontSize: 16,
                    fontFamily: "Poppins",
                    color: Colors.grey,
                  ),
                ),
              ),
            SizedBox(height: bottomPadding + 20),
          ],
        ),
      ),
    );
  }

  Widget _buildProductItem(Products product) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
        // border: Border.all(
        //   color: const Color(0xFFE5E5E5),
        //   width: 1,
        // ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Product ID and Name
          Text(
            "#${product.idName}",
            style: TextStyle(
              fontSize: 14,
              fontFamily: "Poppins",
              fontWeight: FontWeight.w400,
              color: AppColors.amountText,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            product.prodName ?? 'Product name not available',
            style: const TextStyle(
              fontSize: 14,
              fontFamily: "Poppins",
              fontWeight: FontWeight.w400,
              fontStyle: FontStyle.normal,
              color: Colors.black87,
            ),
          ),
          const SizedBox(height: 12),

          // Table-like layout for dates and price
          Table(
            columnWidths: const {
              0: FlexColumnWidth(2),
              1: FlexColumnWidth(1),
            },
            children: [
              TableRow(
                children: [
                  TableCell(
                    child: Text(
                      product.dispatchDate != null ?
                      "Dispatched On ${product.dispatchDate!}" :
                      "Dispatch date not available",
                      style: TextStyle(
                        fontSize: 12,
                        fontFamily: "Poppins",
                        fontWeight: FontWeight.w400,
                        color: AppColors.subtitleText,
                      ),
                    ),
                  ),
                  const TableCell(
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: Text(
                        "Plan",
                        style: TextStyle(
                          fontSize: 12,
                          fontFamily: "Poppins",
                          fontWeight: FontWeight.w400,
                          color: Colors.black54,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              TableRow(
                children: [
                  TableCell(
                    child: Text(
                      product.receivedDate != null ?
                      "Received On ${product.receivedDate!}" :
                      "Receive date not available",
                      style: const TextStyle(
                        fontSize: 12,
                        fontFamily: "Poppins",
                        fontWeight: FontWeight.w400,
                        color: Colors.grey,
                      ),
                    ),
                  ),
                  TableCell(
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: Text(
                        product.totalPrice != null ?
                        "${product.totalPrice!}${product.per ?? 'mo'}" :
                        'Price not available',
                        style: const TextStyle(
                          fontSize: 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) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
        // border: Border.all(
        //   color: const Color(0xFFE5E5E5),
        //   width: 1,
        // ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Product Name
          const SizedBox(height: 2),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                product.prodName ?? 'Unavailable',
                style: const TextStyle(
                  fontSize: 14,
                  fontFamily: "Poppins",
                  fontWeight: FontWeight.w400,
                  color: Colors.black87,
                ),
              ),

              Text(
                "Qty. ${product.qty ?? 'Unavailable'}",
                style: TextStyle(
                  fontSize: 12,
                  fontFamily: "Poppins",
                  fontStyle: FontStyle.normal,
                  fontWeight: FontWeight.w400,
                  color: AppColors.subtitleText,
                ),
              ),

              Text(
                "₹${product.totalPrice ?? 'Unavailable'}",
                style: const TextStyle(
                  fontSize: 14,
                  fontStyle: FontStyle.normal,
                  fontFamily: "Poppins",
                  fontWeight: FontWeight.w400,
                  color: AppColors.cardAmountText,
                ),
              ),

            ],
          ),
          const SizedBox(height: 2),
        ],
      ),
    );
  }

  void _showReasonBottomSheet(String orderId) {
    // Your existing bottom sheet implementation
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      builder: (context) {
        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Center(
                child: Container(
                  width: 50,
                  height: 2.5,
                  decoration: BoxDecoration(
                    color: AppColors.subtitleText,
                    borderRadius: BorderRadius.circular(14),
                  ),
                ),
              ),
              SizedBox(height: 12,),
              SectionHeading(
                  title: "Select Your Reason",
                textStyle: TextStyle(
                  fontSize: 16,
                  fontFamily: "Poppins",
                  fontWeight: FontWeight.w500,
                  color: AppColors.normalText,
                ),
              ),
              const SizedBox(height: 22),

            GridView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                crossAxisSpacing: 12,
                mainAxisSpacing: 12,
                childAspectRatio: 0.99,
              ),
              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,
                );
              },
            ),
              const SizedBox(height: 24),
            ],
          ),
        );
      },
    );
  }

  Widget _buildFeatureCard({
    required String title,
    required String description,
    required String orderId,
    required String icon,
    required Color color,
  }) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => HelpTicketScreen(
              reason: title,
              sessionId: widget.sessionId,
              accId: widget.accId,
              orderId: orderId,
            ))
        );
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 2, vertical: 1),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // Icon container
            Container(
              width: 88,
              height: 88,
              decoration: BoxDecoration(
                color: color.withOpacity(0.7),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Center(
                child: SizedBox(
                  height: 40,
                  width: 40,
                  child: SvgPicture.asset(
                    icon,
                    fit: BoxFit.fitWidth,
                  ),
                ),
              ),
            ),
            const SizedBox(height: 8),
            // Title
            SizedBox(
              child: Text(
                title,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: AppColors.nearDarkText,
                  fontSize: 14,
                  fontStyle: FontStyle.normal,
                  fontWeight: FontWeight.w400,
                  fontFamily: "Plus Jakarta Sans",
                ),
              ),
            ),
            const SizedBox(height: 4),
          ],
        ),
      ),
    );
  }
}