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

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

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

  @override
  State<SelectOrderHelpScreen> createState() => _SelectOrderHelpScreenState();
}

class _SelectOrderHelpScreenState extends State<SelectOrderHelpScreen> {
  bool _stretch = true;

  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      final provider = Provider.of<HelpAndComplaintProvider>(
        context,
        listen: false,
      );
      provider.fetchGeneratorList(
        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 generatorData = provider.generatorListResponse;

    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 (generatorData == null ||
        generatorData.orders == null ||
        generatorData.orders!.isEmpty) {
      return const Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: Center(child: Text("No Generators Found.")),
      );
    }

    final genList = generatorData.orders!;

    return RefreshIndicator.adaptive(
      color: AppColors.amountText,
      onRefresh: () async {
        await provider.fetchGeneratorList(
          accId: widget.accId,
          sessionId: widget.sessionId,
        );
      },
      child: Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: CustomScrollView(
          physics: const ClampingScrollPhysics(),
          slivers: <Widget>[
            /// App bar section
            SliverAppBar(
              leading: Container(),
              stretch: _stretch,
              backgroundColor: const Color(0xFF4076FF),
              onStretchTrigger: () async {
                await provider.fetchGeneratorList(
                  accId: widget.accId,
                  sessionId: widget.sessionId,
                );
              },
              stretchTriggerOffset: 300.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(
                            "assets/svg/continue_left_ic.svg",
                            height: 30,
                            color: Colors.white,
                          ),
                        ),
                        const SizedBox(width: 10),
                        const Text(
                          "Help?",
                          style: TextStyle(
                            fontSize: 16,
                            fontFamily: "Poppins",
                            fontWeight: FontWeight.w400,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),

            /// Main content
            SliverToBoxAdapter(
              child: Container(
                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: [
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: const Text(
                          "Select the Generator you are\n having issues with",
                          style: TextStyle(
                            fontSize: 16,
                            fontFamily: "PoppinsMedium",
                            fontWeight: FontWeight.w500,
                            color: Colors.black87,
                          ),
                        ),
                      ),
                      const SizedBox(height: 16),

                      ///  Generator List from Provider
                      ...genList.map((order) {
                        return Column(
                          children: [
                            InkResponse(
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder:
                                        (context) => AddComplaintScreen(
                                          accId: widget.accId,
                                          sessionId: widget.sessionId,
                                          product: order.prodName.toString(),
                                          hashId: order.hashId.toString(),
                                          modolNo: order.engine.toString(),
                                        ),
                                  ),
                                ).then((_) async {
                                  await provider.fetchGeneratorList(
                                    accId: widget.accId,
                                    sessionId: widget.sessionId,
                                  );
                                });
                              },
                              child: _buildOrderItem(
                                assetId:
                                    "#${order.hashId ?? ''} | Engine : ${order.engine ?? ''}",
                                description: order.prodName ?? '',
                                amc: order.amc ?? '',
                                warranty: order.warranty ?? '',
                                pImage: order.productImage ?? '',
                                date:
                                    order.schedule?.isNotEmpty == true
                                        ? order.schedule!.first
                                        : null,
                                serviceText:
                                    order.schedule?.isNotEmpty == true
                                        ? 'Upcoming Service Scheduled'
                                        : null,
                              ),
                            ),
                            const SizedBox(height: 12),
                          ],
                        );
                      }).toList(),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 🔹 Reusable generator list tile
  Widget _buildOrderItem({
    required String assetId,
    required String description,
    required String amc,
    required String warranty,
    required String pImage,
    String? date,
    String? serviceText,
  }) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          /// Row with details and image
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              /// Text Info
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      assetId,
                      style: const TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w400,
                        color: AppColors.amountText,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      description,
                      style: const TextStyle(
                        fontSize: 14,
                        color: AppColors.normalText,
                        height: 1.4,
                      ),
                    ),
                    const SizedBox(height: 8),

                    /// AMC & Warranty tags
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        if (amc == "1" || amc == "2")
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              gradient:
                                  amc == "1"
                                      ? AppColors.greenStripGradient
                                      : AppColors.fadeGradient,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                SvgPicture.asset(
                                  "assets/svg/tick_ic.svg",
                                  height: 14,
                                  color:
                                      amc == "1"
                                          ? AppColors.greenICBg
                                          : AppColors.subtitleText,
                                ),
                                const SizedBox(width: 4),
                                Text(
                                  "AMC Protected",
                                  style: TextStyle(
                                    fontSize: 11,
                                    fontFamily: "PoppinsBold",
                                    fontStyle: FontStyle.italic,
                                    fontWeight: FontWeight.w700,
                                    color:
                                        amc == "1"
                                            ? AppColors.greenICBg
                                            : AppColors.subtitleText,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        if (warranty == "1" || warranty == "2")
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              gradient:
                                  warranty == "1"
                                      ? AppColors.yellowStripGradient
                                      : AppColors.fadeGradient,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                SvgPicture.asset(
                                  "assets/svg/tick2_ic.svg",
                                  height: 14,
                                  color:
                                      warranty == "1"
                                          ? AppColors.warning
                                          : AppColors.subtitleText,
                                ),
                                const SizedBox(width: 4),
                                Text(
                                  "Warranty",
                                  style: TextStyle(
                                    fontSize: 11,
                                    fontFamily: "PoppinsBold",
                                    fontStyle: FontStyle.italic,
                                    fontWeight: FontWeight.w700,
                                    color:
                                        warranty == "1"
                                            ? AppColors.normalText
                                            : AppColors.subtitleText,
                                  ),
                                ),
                              ],
                            ),
                          ),
                      ],
                    ),
                  ],
                ),
              ),

              /// Product Image
              const SizedBox(width: 12),
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: const Color(0xffF2F2F2),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Image.network(
                  pImage.isNotEmpty
                      ? pImage
                      : "https://erp.gengroup.in/assets/upload/inventory_add_genesis_product_pic/_1761047459_6425.png",
                  height: 50,
                  width: 50,
                  fit: BoxFit.contain,
                  errorBuilder:
                      (context, error, stack) => Image.asset(
                        'assets/images/dashboard_gen.png',
                        height: 40,
                        width: 40,
                      ),
                ),
              ),
            ],
          ),

          /// Service info (optional)
          // if (date != null && serviceText != null) ...[
          //   const SizedBox(height: 12),
          //   Container(
          //     padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
          //     decoration: BoxDecoration(
          //       color: const Color(0xffF2F2F2),
          //       borderRadius: BorderRadius.circular(16),
          //     ),
          //     child: Row(
          //       mainAxisAlignment: MainAxisAlignment.start,
          //       children: [
          //         SvgPicture.asset(
          //           "assets/svg/checked_ic.svg",
          //           height: 30,
          //           fit: BoxFit.contain,
          //         ),
          //         const SizedBox(width: 10),
          //         Column(
          //           crossAxisAlignment: CrossAxisAlignment.start,
          //           children: [
          //             Text(
          //               date,
          //               style: const TextStyle(
          //                 fontSize: 12,
          //                 color: AppColors.normalText,
          //                 fontWeight: FontWeight.w500,
          //               ),
          //             ),
          //             Text(
          //               serviceText,
          //               style: const TextStyle(
          //                 fontSize: 12,
          //                 color: AppColors.subtitleText,
          //                 fontWeight: FontWeight.w500,
          //               ),
          //             ),
          //           ],
          //         ),
          //       ],
          //     ),
          //   ),
          // ],
        ],
      ),
    );
  }
}
