import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:gen_rentals/Screens/HelpScreens/TicketChatScreen.dart';
import 'package:gen_rentals/Utility/Reusablewidgets.dart';
import '../../Models/DashboardResponse.dart';
import '../../Notifier/DashboardProvider.dart';
import '../../Notifier/HelpAndEnquiryProvider.dart';
import '../../Utility/AppColors.dart';
import 'package:provider/provider.dart';

import '../ProductsDetailScreen.dart';
import 'CreateTicketScreen.dart';


class OrderHelpScreen extends StatefulWidget {
  final String sessionId;
  final String accId;

  OrderHelpScreen({
    super.key,
    required this.sessionId,
    required this.accId,
  });

  @override
  State<OrderHelpScreen> createState() => _OrderHelpScreenState();
}

class _OrderHelpScreenState extends State<OrderHelpScreen> {
  @override
  void initState() {
    super.initState();

    /// ✅ Fetch ticket list on screen load
    Future.microtask(() async {
      final provider = Provider.of<HelpAndEnquiryProvider>(context, listen: false);
      await provider.fetchTicketList(
        sessionId: widget.sessionId,
        accId: widget.accId,
      );
    });
  }

  // ✅ (unchanged)
  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
  Widget build(BuildContext context) {
    final dashboardProvider = Provider.of<DashboardProvider>(context);
    final dashboardData = dashboardProvider.dashboardData;

    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;
    double bottomPadding = MediaQuery.of(context).padding.bottom;
    return SafeArea(
      top: false,
      child: Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        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: 25,
                ),
              ),
              const SizedBox(width: 10),
              const Text(
                "Help?",
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: "Poppins",
                  fontWeight: FontWeight.w400,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
        ),

        // ✅ Provider Consumer used here
        body: Consumer<HelpAndEnquiryProvider>(
          builder: (context, provider, _) {
            if (provider.isLoading) {
              return const Center(child: CircularProgressIndicator());
            }

            if (provider.errorMessage != null) {
              return Center(
                child: Text(provider.errorMessage!,
                    style: const TextStyle(color: Colors.red)),
              );
            }

            final ticketData = provider.ticketListResponse?.tickets;
            final processingTickets = ticketData?.inProgress ?? [];
            final closedTickets = ticketData?.closed ?? [];

            return SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Create New Ticket Section
                  SectionHeading(
                    title: 'Select the order you are having issues with',
                    textStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                    padding: EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                  ),

                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(horizontal: 2, vertical: 4),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Section Title
                        // Text(
                        //   "Subscribed Orders",
                        //   style: TextStyle(
                        //     fontFamily: "Poppins",
                        //     color: Colors.grey.shade800,
                        //     fontSize: 18,
                        //     fontWeight: FontWeight.w600,
                        //   ),
                        // ),
                        const SizedBox(height: 6),

                        // Show loading or products list
                        if (dashboardProvider.isLoading && dashboardData == null)
                          const Center(
                            child: CircularProgressIndicator(),
                          )
                        else if (dashboardData?.orders == null || dashboardData!.orders!.isEmpty)
                          const Text(
                            "No products subscribed",
                            style: TextStyle(
                              fontFamily: "Poppins",
                              color: Colors.grey,
                              fontSize: 14,
                            ),
                          )
                        else
                        // List of subscribed products from API
                          Column(
                            children: dashboardData!.orders!.map((product) {
                              return Column(
                                children: [
                                  InkResponse(
                                    onTap: () =>_showReasonBottomSheet(product),
                                    child: _buildProductItemFromApi(product),
                                  ),
                                  const SizedBox(height: 16),
                                ],
                              );
                            }).toList(),
                          ),
                      ],
                    ),
                  ),

                ],
              ),
            );
          },
        ),
      ),
    );
  }




  // Helper widget for product item from API data
  Widget _buildProductItemFromApi(Orders product) {
    final bool hasPending = product.hasPendingPayment == true;
    final productList = product.products ?? [];

    return Container(
      margin: const EdgeInsets.symmetric(vertical: 6),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.15),
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Stack(
        children: [
          // ===== Red Strip (Behind Card) =====
          if (hasPending)
            Positioned.fill(
              top: null,
              child: Align(
                alignment: Alignment.bottomCenter,
                child: Container(
                  height: 45,
                  decoration: const BoxDecoration(
                    color: Color(0xFFFFE2E0),
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(15),
                      bottomRight: Radius.circular(15),
                    ),
                  ),
                  child: Row(
                    children: [
                      const SizedBox(width: 12),
                      const Icon(Icons.info_outline, color: Colors.red, size: 18),
                      const SizedBox(width: 6),
                      Expanded(
                        child: Text(
                          product.pendingPaymentText ??
                              "Payment Pending. Please Pay before incurring fines.",
                          style: const TextStyle(
                            fontFamily: "Poppins",
                            color: Colors.red,
                            fontSize: 12,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                      const SizedBox(width: 12),
                    ],
                  ),
                ),
              ),
            ),

          // ===== Main White Card =====
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(15),
            ),
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                /// Header Row (image, order id, date, badge)
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(8.5),
                          decoration: BoxDecoration(
                            color: const Color(0xffF2F2F2),
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: Image.network(
                            product.productImage ?? "",
                            height: 42,
                            width: 42,
                            fit: BoxFit.contain,
                            errorBuilder: (context, error, stack) =>
                                Image.asset('assets/images/gene_png.png',
                                    height: 40, width: 40),
                          ),
                        ),
                        const SizedBox(width: 8),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              "#${product.orderid ?? "0"}",
                              style: const TextStyle(
                                fontFamily: "Poppins",
                                color: Color(0xFF008CDE),
                                fontSize: 14,
                                fontWeight: FontWeight.w400,
                                height: 1.2,
                              ),
                            ),
                            SizedBox(height: 2,),
                            Text(
                              product.rentedDate ?? "Rented date not available",
                              style: TextStyle(
                                fontFamily: "Poppins",
                                fontWeight: FontWeight.w400,
                                color: Colors.grey.shade600,
                                fontSize: 14,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),

                    // ✅ Gradient expiry badge
                    if (product.expiringText != null &&
                        product.expiringText!.isNotEmpty)
                      Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 10, vertical: 6),
                        decoration: BoxDecoration(
                          gradient: _getGradientByColor(product.expiringInColor),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Text(
                          product.expiringText!,
                          style: const TextStyle(
                            color: Colors.black87,
                            fontSize: 12,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                  ],
                ),

                const SizedBox(height: 6),
                const Divider(),

                /// ===== Product List (with +3 More on same line) =====
                Builder(
                  builder: (context) {
                    final visibleItems = productList.take(2).toList();
                    final remaining = productList.length - visibleItems.length;

                    return Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // Left side → Product list (bulleted)
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              for (int i = 0; i < visibleItems.length; i++)
                                Padding(
                                  padding: const EdgeInsets.only(bottom: 4),
                                  child: Row(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      const SizedBox(width: 8),
                                      const Text(
                                        "• ",
                                        style: TextStyle(color: Colors.black, fontSize: 16),
                                      ),
                                      Expanded(
                                        child: Text(
                                          visibleItems[i],
                                          style: const TextStyle(
                                            color: Colors.black,
                                            fontSize: 14,
                                            fontWeight: FontWeight.w400,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                            ],
                          ),
                        ),

                        // Right side → +x More (vertically centered)
                        if (remaining > 0)
                          Padding(
                            padding: const EdgeInsets.only(left: 8, right: 4),
                            child: Align(
                              alignment: Alignment.center,
                              child: Text(
                                "+$remaining More",
                                style: const TextStyle(
                                  fontFamily: "Poppins",
                                  color: Color(0xFF008CDE),
                                  fontSize: 14,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                          ),
                      ],
                    );
                  },
                ),

              ],
            ),
          ),
        ],
      ),
    );
  }

// Gradient helper
  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,
        );
    }
  }

  void _showReasonBottomSheet(
      Orders product,
      ) {
    // 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(
          height: 232,
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 14),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Center(
                child: Container(
                  height: 2.5,
                  width: 55,
                  decoration: BoxDecoration(
                    color: AppColors.subtitleText,
                    borderRadius: BorderRadius.circular(20)
                  ),
                ),
              ),
              SizedBox(height: 12,),
              Text(
                "Select Your Reason",
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: "Poppins",
                  fontWeight: FontWeight.w500,
                  color: Colors.black87,
                ),
              ),
              const SizedBox(height: 24),

              GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 12,
                  mainAxisSpacing: 12,
                  childAspectRatio: 0.96,
                ),
                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: product.orderid.toString(),
                    icon: icon,
                    color: color,
                  );
                },
              ),
              const SizedBox(height: 4),
            ],
          ),
        );
      },
    );
  }

  Widget _buildFeatureCard({
    required String title,
    required String description,
    required String icon,
    required String orderId,
    required Color color,
  }) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => HelpTicketScreen(
              reason: title,
              sessionId: widget.sessionId,
              accId: widget.accId,
              orderId: orderId,
            ))
        ).then((_) {
          final provider = Provider.of<HelpAndEnquiryProvider>(context, listen: false);
          provider.fetchTicketList(
            sessionId: widget.sessionId,
            accId: widget.accId,
          );
        });

      },
      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(
              width: 90,
              child: Text(
                title,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: AppColors.nearDarkText,
                  fontSize: 13,
                  height: 1,
                  fontWeight: FontWeight.w400,
                  fontStyle: FontStyle.normal
                ),
              ),
            ),
            const SizedBox(height: 0),
          ],
        ),
      ),
    );
  }


}

