import 'dart:io';

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';
import 'AddComplaintScreen.dart';
import 'ComplaintDetailsScreen.dart';

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


  const ComplaintListScreen({
    Key? key,
    required this.accId,
    required this.sessionId,
    required this.genId,
  }) : 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,
        genId: widget.genId
      );
    });
  }

  @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: Padding(
            padding: const EdgeInsets.all(24.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Error Icon
                Container(
                  width: 120,
                  height: 120,
                  decoration: BoxDecoration(
                    color: Colors.red.withOpacity(0.1),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    Icons.error_outline_rounded,
                    size: 60,
                    color: Colors.red,
                  ),
                ),

                const SizedBox(height: 24),

                // Error Title
                const Text(
                  "Oops! Something went wrong",
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                    fontFamily: "Poppins",
                  ),
                ),

                const SizedBox(height: 12),

                // Error Message
                Text(
                  error,
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                    fontSize: 14,
                    color: Colors.grey,
                    fontFamily: "Poppins",
                    height: 1.4,
                  ),
                ),

                const SizedBox(height: 32),

                // Retry Button
                ElevatedButton.icon(
                  onPressed: () async {
                    // Show loading state
                    setState(() {});

                    await Future.delayed(const Duration(milliseconds: 300));

                    // Retry fetching data
                    final provider = Provider.of<HelpAndComplaintProvider>(
                      context,
                      listen: false,
                    );
                    provider.fetchComplaintsList(
                      accId: widget.accId,
                      sessionId: widget.sessionId,
                      genId: widget.genId
                    );
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.buttonColor,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(
                      horizontal: 24,
                      vertical: 12,
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25),
                    ),
                    elevation: 2,
                  ),
                  icon: const Icon(Icons.refresh_rounded, size: 20),
                  label: const Text(
                    "Try Again",
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      fontFamily: "Poppins",
                    ),
                  ),
                ),

                const SizedBox(height: 16),

                // Alternative Action
                TextButton(
                  onPressed: () {
                    // Go back or navigate to home
                    Navigator.pop(context);
                  },
                  child: const Text(
                    "Go Back",
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey,
                      fontFamily: "Poppins",
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }
    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,
          genId: widget.genId
        );
      },
      child: SafeArea(
        top: false,
        bottom: Platform.isIOS?false:true,
        maintainBottomViewPadding: true,
        child: Scaffold(
          resizeToAvoidBottomInset: true,
          backgroundColor: AppColors.backgroundRegular,
          body: CustomScrollView(
            physics: const ClampingScrollPhysics(),
            slivers: <Widget>[
              SliverAppBar(
                automaticallyImplyLeading: false,
                stretch: _stretch,
                backgroundColor: const Color(0xFF4076FF),
                onStretchTrigger: () async {
                  await provider.fetchComplaintsList(
                    accId: widget.accId,
                    sessionId: widget.sessionId,
                    genId: widget.genId
                  );
                },
                stretchTriggerOffset: 300.0,
                // expandedHeight: 60.0,
                flexibleSpace: FlexibleSpaceBar(
                  stretchModes: const [
                    StretchMode.zoomBackground,
                    StretchMode.blurBackground,
                  ],
                  background: Container(
                    decoration: const BoxDecoration(gradient: AppColors.commonAppBarGradient),
                    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.backgroundBottom,
                  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: () {
                            if (widget.genId == "") {
                              Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => SelectOrderHelpScreen(
                                      accId: widget.accId,
                                      sessionId: widget.sessionId,
                                    ),
                              ),
                            ).then((_) async {
                              await provider.fetchComplaintsList(
                                accId: widget.accId,
                                sessionId: widget.sessionId,
                                genId: widget.genId
                              );
                            });
                            }

                            if (widget.genId != "") {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder:
                                      (context) => AddComplaintScreen(
                                        accId: widget.accId,
                                        sessionId: widget.sessionId,
                                        product: data.prodName.toString(),
                                        hashId: widget.genId.toString(),
                                      ),
                                ),
                              ).then((_) async {
                                await provider.fetchComplaintsList(
                                    accId: widget.accId,
                                    sessionId: widget.sessionId,
                                    genId: widget.genId
                                );
                              });
                            }
                          },
                          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: Stack(
                                    children: [
                                      if (widget.genId != "")
                                      Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          const Text(
                                            "Get help for this order",
                                            style: TextStyle(
                                              fontFamily: "Poppins",
                                              fontSize: 14,
                                              fontWeight: FontWeight.w400,
                                              color: Colors.black,
                                            ),
                                          ),
                                          const SizedBox(height: 4),
                                          Text(
                                            data.prodName!,
                                            style: const TextStyle(
                                              fontFamily: "Poppins",
                                              fontSize: 12,
                                              fontWeight: FontWeight.w400,
                                              color: Colors.grey,
                                            ),
                                          ),
                                        ],
                                      ),
                                      if (widget.genId == "")
                                      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: 4),

                        /// 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(
                            accId: widget.accId,
                            sessionId: widget.sessionId,
                            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(
                            accId: widget.accId,
                            sessionId: widget.sessionId,
                            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 accId;
  final String sessionId;
  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,
    required this.accId,
    required this.sessionId,
  });

  @override
  Widget build(BuildContext context) {
    return InkResponse(
      onTap: () async {
        await Navigator.push(
          context,
          MaterialPageRoute(
            builder:
                (context) => ComplaintDetailsScreen(
                  accId: accId,
                  sessionId: sessionId,
                  complaintId: id,
                ),
          ),
        );
      },
      child: 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: status == "Open" ? AppColors.amountText : AppColors.normalText,
                          ),
                        ),
                        Text(
                          title,
                          style: TextStyle(
                            fontFamily: "Poppins",
                            fontSize: 14,
                            fontWeight: FontWeight.w400,
                            color: status == "Open" ? AppColors.amountText : AppColors.normalText,
                          ),
                        ),
                      ],
                    ),
                    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,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
