import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:gen_service/Notifiers/generatorDetailsProvider.dart';
import 'package:provider/provider.dart';

import '../Utility/AppColors.dart';

class ScheduleListScreen extends StatefulWidget {
  final accId;
  final sessionId;
  final genId;

  const ScheduleListScreen({
    super.key,
    required this.accId,
    required this.sessionId,
    required this.genId,
  });

  @override
  State<ScheduleListScreen> createState() => _ScheduleListScreenState();
}

class _ScheduleListScreenState extends State<ScheduleListScreen> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      final provider = Provider.of<Generatordetailsprovider>(
        context,
        listen: false,
      );
      provider.fetchScheduleList(widget.accId, widget.sessionId,widget.genId);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<Generatordetailsprovider>(
      builder: (context, provider, child) {
        final isLoading = provider.isLoading;
        final error = provider.errorMessage;
        final response = provider.scheduleResponse;

        final data = response?.allScheduleServices??[];

        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<Generatordetailsprovider>(
                          context,
                          listen: false,
                        );
                        await provider.fetchScheduleList(widget.accId, widget.sessionId,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.maybePop(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.")),
          );
        }
        return RefreshIndicator.adaptive(
          color: AppColors.amountText,
          onRefresh: () async {
            await Future.delayed(const Duration(milliseconds: 600));
          },

          child: Scaffold(
            backgroundColor: AppColors.backgroundRegular,
            body: CustomScrollView(
              physics: const BouncingScrollPhysics(),
              slivers: [
                SliverAppBar(
                  stretch: true,
                  pinned: true,
                  expandedHeight: 75,
                  backgroundColor: AppColors.backgroundRegular,
                  elevation: 0,
                  // Remove shadow
                  automaticallyImplyLeading: false,
                  toolbarHeight: 0,
                  // Remove toolbar space
                  collapsedHeight: 0,
                  // Completely collapse to 0 height
                  flexibleSpace: FlexibleSpaceBar(
                    stretchModes: const [StretchMode.fadeTitle],
                    background: Container(
                      decoration: BoxDecoration(
                        gradient: AppColors.balanceBarGradientA,
                      ),
                      child: SafeArea(
                        child: Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 20,
                          ),
                          child: SizedBox(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                InkResponse(
                                  onTap: () {
                                    HapticFeedback.selectionClick();

                                    Navigator.pop(context, true);
                                  },
                                  child: SvgPicture.asset(
                                    "assets/svg/appbar_back.svg",
                                    height: 25,
                                  ),
                                ),
                                SizedBox(width: 10),
                                Expanded(
                                  flex: 4,
                                  child: InkResponse(
                                    onTap: () {
                                      HapticFeedback.selectionClick();

                                      Navigator.pop(context, true);
                                    },
                                    child: Text(
                                      "Schedule List",
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 1,
                                      style: TextStyle(
                                        fontSize: 16,
                                        color: Colors.white,
                                        height: 1.1,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),

                SliverToBoxAdapter(
                  child: Container(
                    color: Color(0xFF4076FF),
                    child: Container(
                      decoration: const BoxDecoration(
                        color: AppColors.backgroundRegular,
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(30),
                          topRight: Radius.circular(30),
                        ),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 4),

                          ListView.builder(
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            itemCount: data!.length,
                            itemBuilder: (context, j) {
                              return Container(
                                margin: const EdgeInsets.symmetric(
                                  vertical: 5,
                                  horizontal: 10,
                                ),
                                decoration: BoxDecoration(
                                  color:
                                      data[j].status == "Scheduled"
                                          ? Color(0xFFD7F0FF)
                                          : Color(0xFFE0E0E0),
                                  borderRadius: BorderRadius.circular(14),
                                ),
                                child: Column(
                                  children: [
                                    Container(
                                      padding: const EdgeInsets.symmetric(
                                        vertical: 10,
                                        horizontal: 10,
                                      ),

                                      decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.circular(14),
                                        border: Border.all(
                                          color:
                                              data[j].status == "Scheduled"
                                                  ? AppColors.buttonColor
                                                  : Colors.white,
                                        ),
                                      ),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.start,
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              if (data[j].status ==
                                                  "Scheduled") ...[
                                                SvgPicture.asset(
                                                  "assets/svg/calendar_ic.svg",
                                                ),
                                                SizedBox(width: 8),
                                              ],
                                              SizedBox(
                                                child: Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: [
                                                    if (data[j].status ==
                                                        "Completed") ...[
                                                      Text(
                                                        data[j].complaintType ??
                                                            "-",
                                                        style: TextStyle(
                                                          fontSize: 14,
                                                          color:
                                                              AppColors
                                                                  .nearDarkText,
                                                        ),
                                                      ),
                                                    ],
                                                    Text(
                                                      data[j].dueDate ?? "-",
                                                      style: TextStyle(
                                                        fontSize:
                                                            data[j].status ==
                                                                    "Scheduled"
                                                                ? 14
                                                                : 12,
                                                        color:
                                                            data[j].status ==
                                                                    "Scheduled"
                                                                ? AppColors
                                                                    .nearDarkText
                                                                : Color(
                                                                  0xFF777777,
                                                                ),
                                                      ),
                                                    ),
                                                    if (data[j].amc != "0") ...[
                                                      SizedBox(height: 5,),
                                                      Container(
                                                        padding: const EdgeInsets.symmetric(
                                                          horizontal: 5,
                                                          vertical: 4,
                                                        ),
                                                        decoration: BoxDecoration(
                                                          gradient:
                                                          data[j].amc == "1"
                                                              ? AppColors.greenStripGradient
                                                              : AppColors.fadeGradient,
                                                          borderRadius: BorderRadius.circular(12),
                                                        ),
                                                        child: Row(
                                                          mainAxisSize: MainAxisSize.min,
                                                          children: [
                                                            SvgPicture.asset(
                                                              "assets/svg/tick_ic.svg",
                                                              height: 15,
                                                              color:
                                                              data[j].amc == "1"
                                                                  ? AppColors.greenICBg
                                                                  : AppColors.subtitleText,
                                                            ),
                                                            const SizedBox(width: 4),
                                                            Text(
                                                              "AMC ",
                                                              style: TextStyle(
                                                                fontSize: 12,
                                                                fontFamily: "HemiHead",
                                                                fontStyle: FontStyle.italic,
                                                                fontWeight: FontWeight.w700,
                                                                color:
                                                                data[j].amc == "1"
                                                                    ? AppColors.greenICBg
                                                                    : AppColors.subtitleText,
                                                              ),
                                                            ),
                                                            Text(
                                                              "Protected",
                                                              style: TextStyle(
                                                                fontSize: 12,
                                                                fontFamily: "HemiHead",
                                                                fontStyle: FontStyle.italic,
                                                                fontWeight: FontWeight.w700,
                                                                color:
                                                                data[j].amc == "1"
                                                                    ? AppColors.normalText
                                                                    : AppColors.subtitleText,
                                                              ),
                                                            ),
                                                            const SizedBox(width: 4),
                                                            if (data[j].amc == "2")
                                                              const Icon(
                                                                Icons.error_outline,
                                                                color: Colors.red,
                                                                size: 15,
                                                              ),
                                                          ],
                                                        ),
                                                      ),
                                                    ],
                                                    if (data[j].warranty != "0") ...[
                                                      SizedBox(height: 5,),
                                                      Container(
                                                        padding: const EdgeInsets.symmetric(
                                                          horizontal: 8,
                                                          vertical: 4,
                                                        ),
                                                        decoration: BoxDecoration(
                                                          gradient:
                                                          data[j].warranty == "1"
                                                              ? AppColors.yellowStripGradient
                                                              : AppColors.fadeGradient,
                                                          borderRadius: BorderRadius.circular(12),
                                                        ),
                                                        child: Row(
                                                          mainAxisSize: MainAxisSize.min,
                                                          children: [
                                                            Row(
                                                              children: [
                                                                SvgPicture.asset(
                                                                  data[j].warranty == "1"
                                                                      ? "assets/svg/tick2_ic.svg":
                                                                  "assets/svg/tick3_ic.svg",
                                                                  height: 15,
                                                                ),
                                                                const SizedBox(width: 6),
                                                                Text(
                                                                  "Warranty",
                                                                  style: TextStyle(
                                                                    fontSize: 12,
                                                                    fontFamily: "HemiHead",
                                                                    fontStyle: FontStyle.italic,
                                                                    fontWeight: FontWeight.w700,
                                                                    color:
                                                                    data[j].warranty == "1"
                                                                        ? AppColors.normalText
                                                                        : Color(0xFF969696),
                                                                  ),
                                                                ),
                                                                SizedBox(width: 6),
                                                                if (data[j].warranty == "2")
                                                                  const Icon(
                                                                    Icons.error_outline,
                                                                    color: Colors.red,
                                                                    size: 15,
                                                                  ),
                                                              ],
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ],
                                                  ],
                                                ),
                                              ),
                                              Spacer(),
                                              Container(
                                                padding: EdgeInsets.symmetric(
                                                  vertical: 5,
                                                  horizontal: 8,
                                                ),
                                                decoration: BoxDecoration(
                                                  borderRadius:
                                                      BorderRadius.circular(8),
                                                  color:
                                                      data[j].status == "Scheduled"
                                                          ? AppColors.successBG
                                                          : Color(0xFFFFF8D2),
                                                ),
                                                child: Center(
                                                  child: Text(
                                                    data[j].status ?? "-",
                                                    style: TextStyle(
                                                      fontSize: 14,
                                                      color:
                                                          data[j].status ==
                                                                  "Scheduled"
                                                              ? AppColors
                                                                  .success
                                                              : AppColors.nearDarkText,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                    if (data[j].status == "Scheduled") ...[
                                      Container(
                                        padding: EdgeInsets.symmetric(
                                          vertical: 10,
                                          horizontal: 10,
                                        ),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            Text(
                                              "Upcoming Service Scheduled",
                                              style: TextStyle(
                                                fontSize: 12,
                                                color: AppColors.buttonColor,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ],
                                ),
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
