import 'dart:io';

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: 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.fetchGeneratorList(
                      accId: widget.accId,
                      sessionId: widget.sessionId,
                    );
                  },
                  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 (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: SafeArea(
        top: false,
        bottom: Platform.isIOS?false:true,
        maintainBottomViewPadding: true,
        child: Scaffold(
          resizeToAvoidBottomInset: true,
          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(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(
                              "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.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: [
                        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.id.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.start,
                      children: [
                        // Status Badge with checkmark for AMC Protected
                        if (amc == "1" || amc == "2")
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 5,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              gradient:
                              amc == "1"
                                  ? AppColors.greenStripGradient
                                  : AppColors.fadeGradient,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Row(
                                  children: [
                                    SvgPicture.asset(
                                      "assets/svg/tick_ic.svg",
                                      height: 14,
                                      color:
                                      amc == "1"
                                          ? AppColors.greenICBg
                                          : AppColors.subtitleText,
                                    ),
                                    const SizedBox(width: 2),
                                    Text(
                                      "AMC ",
                                      style: TextStyle(
                                        fontSize: 11,
                                        fontFamily: "HemiHead",
                                        fontStyle: FontStyle.italic,
                                        fontWeight: FontWeight.w700,
                                        color:
                                        amc == "1"
                                            ? AppColors.greenICBg
                                            : AppColors.subtitleText,
                                      ),
                                    ),
                                    Text(
                                      "Protected",
                                      style: TextStyle(
                                        fontSize: 11,
                                        fontFamily: "HemiHead",
                                        fontStyle: FontStyle.italic,
                                        fontWeight: FontWeight.w700,
                                        color:
                                        amc == "1"
                                            ? AppColors.normalText
                                            : AppColors.subtitleText,
                                      ),
                                    ),
                                    SizedBox(width: 4),
                                    if (amc == "2")
                                      const Icon(
                                        Icons.error_outline,
                                        color: Colors.red,
                                        size: 12,
                                      ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        if (amc == "1" || amc == "2") SizedBox(width: 10),
                        // for warranty
                        if (warranty == "1" || warranty == "2")
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 6,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              gradient:
                              warranty == "1"
                                  ? AppColors.yellowStripGradient
                                  : AppColors.fadeGradient,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Row(
                                  children: [
                                    SvgPicture.asset(
                                      height: 14,
                                      warranty == "1"
                                          ? "assets/svg/tick2_ic.svg"
                                          : "assets/svg/tick3_ic.svg",
                                    ),
                                    const SizedBox(width: 1),
                                    Text(
                                      "Warranty",
                                      style: TextStyle(
                                        fontSize: 11,
                                        fontFamily: "HemiHead",
                                        fontStyle: FontStyle.italic,
                                        fontWeight: FontWeight.w700,
                                        color:
                                        warranty == "1"
                                            ? AppColors.normalText
                                            : AppColors.subtitleText,
                                      ),
                                    ),
                                    SizedBox(width: 2),
                                    if (warranty == "2")
                                      const Icon(
                                        Icons.error_outline,
                                        color: Colors.red,
                                        size: 12,
                                      ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                      ],
                    ),
                  ],
                ),
              ),

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