import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:gen_service/Notifiers/HelpAndComplaintProvider.dart';
import 'package:gen_service/Screens/HelpAndComplaintScreens/SelectOrderHelpScreen.dart';
import 'package:gen_service/Screens/ProfileScreen.dart';
import 'package:provider/provider.dart';
import '../../Utility/AppColors.dart';

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

  const ComplaintListScreen({
    Key? key,
    required this.accId,
    required this.sessionId,
  }) : super(key: key);

  @override
  State<ComplaintListScreen> createState() => _ComplaintListScreenState();
}

class _ComplaintListScreenState extends State<ComplaintListScreen> {
  bool _stretch = true;

  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      final provider =
      Provider.of<HelpAndComplaintProvider>(context, listen: false);
      provider.fetchComplaintsList(
        accId: widget.accId,
        sessionId: widget.sessionId,
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<HelpAndComplaintProvider>(context);

    final isLoading = provider.isLoading;
    final error = provider.errorMessage;
    final data = provider.complaintListResponse;

    if (isLoading) {
      return const Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: Center(
          child: CircularProgressIndicator(color: AppColors.buttonColor),
        ),
      );
    }

    if (error != null) {
      return Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: Center(
          child: Text(
            error,
            style: const TextStyle(color: Colors.red, fontSize: 16),
          ),
        ),
      );
    }

    if (data == null) {
      return const Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: Center(
          child: Text("No data found."),
        ),
      );
    }

    //  Separate open and closed complaints
    final openComplaints = data.complaintList!
        .where((c) => c.openStatus?.toLowerCase() == "open")
        .toList();
    final closedComplaints = data.complaintList!
        .where((c) => c.openStatus?.toLowerCase() == "closed")
        .toList();

    return RefreshIndicator.adaptive(
      color: AppColors.amountText,
      onRefresh: () async {
        await provider.fetchComplaintsList(
          accId: widget.accId,
          sessionId: widget.sessionId,
        );
      },
      child: Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: CustomScrollView(
          physics: const ClampingScrollPhysics(),
          slivers: <Widget>[
            SliverAppBar(
              leading: Container(),
              stretch: _stretch,
              backgroundColor: const Color(0xFF4076FF),
              onStretchTrigger: () async {
                await provider.fetchComplaintsList(
                  accId: widget.accId,
                  sessionId: widget.sessionId,
                );
              },
              stretchTriggerOffset: 300.0,
              // expandedHeight: 60.0,
              flexibleSpace: FlexibleSpaceBar(
                stretchModes: const [
                  StretchMode.zoomBackground,
                  StretchMode.blurBackground,
                ],
                background: Container(
                  decoration:
                  const BoxDecoration(color: AppColors.primary),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        InkResponse(
                          onTap: () => Navigator.pop(context, true),
                          child: SvgPicture.asset(
                            color: Colors.white,
                            "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.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),

            /// Main body container
            SliverToBoxAdapter(
              child: Container(
                padding: const EdgeInsets.only(top: 1),
                color: AppColors.primary,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
                  decoration: const BoxDecoration(
                    color: AppColors.backgroundRegular,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(30),
                      topRight: Radius.circular(30),
                    ),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      /// Top Tile
                      InkResponse(
                        onTap: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context)=> SelectOrderHelpScreen(accId: widget.accId, sessionId: widget.sessionId))
                          ).then((_) async {
                            await provider.fetchComplaintsList(
                              accId: widget.accId,
                              sessionId: widget.sessionId,
                            );
                          });
                        },
                        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",
                                  fit: BoxFit.contain,
                                ),
                              ),
                              const SizedBox(width: 12),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: const [
                                    Text(
                                      "Get help for an order",
                                      style: TextStyle(
                                        fontFamily: "Poppins",
                                        fontSize: 14,
                                        fontWeight: FontWeight.w400,
                                        color: Colors.black,
                                      ),
                                    ),
                                    SizedBox(height: 4),
                                    Text(
                                      "Select a Generator",
                                      style: TextStyle(
                                        fontFamily: "Poppins",
                                        fontSize: 12,
                                        fontWeight: FontWeight.w400,
                                        color: Colors.grey,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              SvgPicture.asset(
                                "assets/svg/continue_ic.svg",
                                color: Colors.black,
                                height: 32,
                              ),
                            ],
                          ),
                        ),
                      ),

                      const SizedBox(height: 25),

                      /// Raised Complaints
                      if (openComplaints.isNotEmpty)
                        const Text(
                          "Raised Complaints",
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                            color: Colors.black87,
                          ),
                        ),

                      const SizedBox(height: 8),
                      ...openComplaints.map(
                            (c) => ComplaintCard(
                          title: c.complaintName ?? "-",
                          id: c.id ?? "-",
                          product: c.productName ?? "",
                          status: c.openStatus ?? "Open",
                          date: c.registredDate ?? "",
                          engModel: c.modelName ?? "-",
                        ),
                      ),

                      const SizedBox(height: 25),

                      /// Resolved Complaints
                      if (closedComplaints.isNotEmpty)
                        const Text(
                          "Resolved Complaints",
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                            color: Colors.black87,
                          ),
                        ),

                      const SizedBox(height: 8),
                      ...closedComplaints.map(
                            (c) => ComplaintCard(
                          title: c.complaintName ?? "-",
                          id: c.id ?? "",
                          product: c.productName ?? "",
                          status: c.openStatus ?? "Closed",
                          date: c.registredDate ?? "",
                          engModel: c.modelName ?? "",
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// Reusable Complaint Item Card
class ComplaintCard extends StatelessWidget {

  final String title;
  final String id;
  final String product;
  final String status;
  final String date;
  final String engModel;

  const ComplaintCard({
    super.key,
    required this.title,
    required this.id,
    required this.product,
    required this.status,
    required this.date,
    required this.engModel,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 6),
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade200),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.shade200,
            blurRadius: 4,
            offset: const Offset(0, 2),
          )
        ],
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(
                        "#${id} | ",
                        style: TextStyle(
                          fontFamily: "Poppins",
                          fontSize: 14,
                          fontWeight: FontWeight.w400,
                          color: AppColors.amountText,
                        ),
                      ),
                      Text(
                        title,
                        style: TextStyle(
                          fontFamily: "Poppins",
                          fontSize: 14,
                          fontWeight: FontWeight.w400,
                          color: AppColors.amountText,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Text(
                    "Date: $date",
                    style: TextStyle(
                      fontFamily: "Poppins",
                      fontSize: 12,
                      fontWeight: FontWeight.w400,
                      color: AppColors.subtitleText,
                    ),
                  ),
                  const SizedBox(height: 2),

                ],
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 15, vertical: 7),
                decoration: BoxDecoration(
                  color: status == "Open" ? AppColors.successBG : AppColors.yellowBG,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Text(
                  status,
                  style: TextStyle(
                    fontFamily: "Poppins",
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                    color: status == "Open" ? AppColors.success : AppColors.normalText,
                  ),
                ),
              ),
            ],
          ),
          Divider(),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                flex: 6,
                child: Text(
                  product,
                  maxLines: 2,
                  style: TextStyle(
                    fontFamily: "Poppins",
                    fontSize: 12,
                    fontWeight: FontWeight.w400,
                    color: Colors.black87,
                  ),
                ),
              ),
              Text(
                "#${id} | Engine :$engModel",
                style: TextStyle(
                  fontFamily: "Poppins",
                  fontSize: 12,
                  fontWeight: FontWeight.w400,
                  color: AppColors.subtitleText,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
