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


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

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

  @override
  State<HelpScreen> createState() => _HelpScreenState();
}

class _HelpScreenState extends State<HelpScreen> {
  @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) {
    return SafeArea(
      top: false,
      child: RefreshIndicator.adaptive(
        color: AppColors.amountText,
        onRefresh: () async {
          await Future.delayed(const Duration(milliseconds: 600));
          final provider = Provider.of<HelpAndEnquiryProvider>(context, listen: false);
          await provider.fetchTicketList(
            sessionId: widget.sessionId,
            accId: widget.accId,
          );
        },

        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: 30,
                  ),
                ),
                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: 'Create New Ticket',
                      textStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                      padding: EdgeInsets.symmetric(horizontal: 2, vertical: 4),
                    ),
                    const SizedBox(height: 12),
                    _buildCreateNewTicketSection(),
                    const SizedBox(height: 12),

                    // Processing Tickets Section
                    SectionHeading(
                      title: 'Processing Tickets',
                      textStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                      padding: EdgeInsets.symmetric(horizontal: 2, vertical: 4),
                    ),
                    const SizedBox(height: 2),
                    _buildProcessingTicketsSection(processingTickets),
                    const SizedBox(height: 10),

                    // Closed Tickets Section
                    SectionHeading(
                      title: 'Closed Tickets',
                      textStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                      padding: EdgeInsets.symmetric(horizontal: 2, vertical: 4),
                    ),

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

  Widget _buildCreateNewTicketSection() {
    return InkResponse(
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => OrderHelpScreen(sessionId: widget.sessionId, accId: widget.accId))
        ).then((_) {
          final provider = Provider.of<HelpAndEnquiryProvider>(context, listen: false);
          provider.fetchTicketList(
            sessionId: widget.sessionId,
            accId: widget.accId,
          );
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 14),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(14),
        ),
        child: Row(
          children: [
            SizedBox(
              height: 42,
              width: 42,
              child: SvgPicture.asset(
                "assets/svg/help_ic.svg",
                height: 30,
                width: 30,
                fit: BoxFit.contain,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "Get help for an order",
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontFamily: "Poppins",
                      fontSize: 14,
                      fontStyle: FontStyle.normal,
                      fontWeight: FontWeight.w400,
                      color: Colors.black,
                    ),
                  ),
                  SizedBox(height: 4),
                  Text(
                    "Select an order",
                    style: TextStyle(
                      fontFamily: "Poppins",
                      fontSize: 12,
                      fontStyle: FontStyle.normal,
                      fontWeight: FontWeight.w400,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 30,
              width: 30,
              child: SvgPicture.asset(
                "assets/svg/continue_ic.svg",
                color: Color(0xFF000000),
                height: 18,
                width: 18,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// ✅ Processing tickets from provider
  Widget _buildProcessingTicketsSection(List<dynamic> tickets) {
    if (tickets.isEmpty) {
      return const Center(child: Text("No processing tickets"));
    }

    return Container(
      padding: const EdgeInsets.all(4),
      child: Column(
        children: tickets.map((ticket) {
          return Padding(
            padding: const EdgeInsets.only(bottom: 4),
            child: CommonListItem(
              orderId: ticket.ticketNumber ?? '',
              title: ticket.type ?? 'Untitled',
              date: ticket.date ?? '',
              status: 'In Process',
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => TicketChatScreen(
                      sessionId: widget.sessionId,
                      accId: widget.accId,
                      ticketId: ticket.id,
                      status: "In Process",
                    ),
                  ),
                );
              },
            ),
          );
        }).toList(),
      ),
    );
  }

  /// ✅ Closed tickets from provider
  Widget _buildClosedTicketsSection(List<dynamic> tickets) {
    if (tickets.isEmpty) {
      return const Center(child: Text("No closed tickets"));
    }

    return Container(
      padding: const EdgeInsets.all(4),
      child: Column(
        children: tickets.map((ticket) {
          return Padding(
            padding: const EdgeInsets.only(bottom: 4),
            child: CommonListItem(
              orderId: ticket.ticketNumber ?? '',
              title: ticket.type ?? 'Untitled',
              date: ticket.date ?? '',
              status: "",
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => TicketChatScreen(
                      sessionId: widget.sessionId,
                      accId: widget.accId,
                      ticketId: ticket.id,
                      status: "Closed",
                    ),
                  ),
                ).then((_) {
                  final provider = Provider.of<HelpAndEnquiryProvider>(context, listen: false);
                  provider.fetchTicketList(
                    sessionId: widget.sessionId,
                    accId: widget.accId,
                  );
                });
              },
            ),
          );
        }).toList(),
      ),
    );
  }
}


class CommonListItem extends StatelessWidget {
  final String orderId;
  final String title;
  final String date;
  final String status;
  final VoidCallback? onTap;

  const CommonListItem({
    Key? key,
    required this.orderId,
    required this.title,
    required this.date,
    required this.status,
    this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const SizedBox(height: 6),
        Material(
          color: Colors.transparent,
          child: InkWell(
            borderRadius: BorderRadius.circular(12),
            onTap: onTap,
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
              ),
              padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 17),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(width: 10,),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          "#${orderId}",
                          style: TextStyle(
                            fontSize: 12,
                            fontStyle: FontStyle.normal,
                            fontWeight: FontWeight.w400,
                            color: AppColors.subtitleText,
                          ),
                        ),
                        Text(
                          title,
                          style: TextStyle(
                            fontSize: 14,
                            fontStyle: FontStyle.normal,
                            fontWeight: FontWeight.w400,
                            color: Colors.black87,
                          ),
                        ),
                        const SizedBox(height: 4),
                        if(status.isNotEmpty)
                        Text(
                          date,
                          style: TextStyle(
                            fontSize: 12,
                            fontStyle: FontStyle.normal,
                            fontFamily: "Poppins",
                            fontWeight: FontWeight.w400,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                  ),
                  if (status.isNotEmpty)
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      decoration: BoxDecoration(
                        color: Color(0xFFD7FFD2),
                        borderRadius: BorderRadius.circular(6),
                      ),
                      child: Text(
                        status,
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w400,
                          fontStyle: FontStyle.normal,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                  if(status.isEmpty)
                    Text(
                      date,
                      style: TextStyle(
                        fontSize: 12,
                        fontStyle: FontStyle.normal,
                        fontWeight: FontWeight.w400,
                        color: Colors.grey[600],
                      ),
                    ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}
