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

import '../../Notifiers/serviceAndJobCardListProvier.dart';
import '../../Utility/AppColors.dart';
import '../FileViewer.dart';

class serviceListScreen extends StatefulWidget {
  final accId;
  final sessionId;
  final complaintId;

  const serviceListScreen({
    super.key,
    required this.accId,
    required this.sessionId,
    required this.complaintId,
  });

  @override
  State<serviceListScreen> createState() => _serviceListScreenState();
}

class _serviceListScreenState extends State<serviceListScreen> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      final provider = Provider.of<ServiceAndJobCardListProvider>(
        context,
        listen: false,
      );
      provider.fetchServiceDetailsAPI(
        widget.accId,
        widget.sessionId,
        widget.complaintId,
      );
    });
  }

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

        final data = response?.allServiceList ?? [];
        List<String> serviceHeadings = [
          "Date",
          "In/Out Time",
          "Running Hrs.",
          "FSR File",
          "FSR Number",
          "Feedback",
        ];

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

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

        if (data == null) {
          return const Scaffold(
            backgroundColor: AppColors.backgroundRegular,
            body: Center(child: Text("No data found.")),
          );
        }
        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(
                                      "Service Details 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) {
                              List<String> serviceSubHeadings = [
                                data[j].date ?? "-",
                                data[j].inOrOutTime ?? "-",
                                data[j].runningHrs ?? "-",
                                data[j].fsrExt ?? "-",
                                data[j].fsrNo ?? "-",
                                data[j].feedback ?? "-",
                              ];
                              return Container(
                                margin: const EdgeInsets.all(5),
                                padding: const EdgeInsets.all(14),
                                decoration: BoxDecoration(
                                  color: const Color(0xFFFFFFFF),
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                child: Column(
                                  children: [
                                    ...List.generate(serviceHeadings.length, (
                                      i,
                                    ) {
                                      return Padding(
                                        padding: const EdgeInsets.symmetric(
                                          vertical: 3,
                                        ),
                                        child: Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Expanded(
                                              child: Text(
                                                serviceHeadings[i] ?? "-",
                                                style: const TextStyle(
                                                  fontSize: 14,
                                                  color: AppColors.subtitleText,
                                                ),
                                              ),
                                            ),
                                            Expanded(
                                              child: InkResponse(
                                                onTap:
                                                    serviceHeadings[i] ==
                                                            "FSR File"
                                                        ? () async {
                                                          await Navigator.push(
                                                            context,
                                                            MaterialPageRoute(
                                                              builder:
                                                                  (
                                                                    context,
                                                                  ) => Fileviewer(
                                                                    fileName:
                                                                        data[j]
                                                                            ?.fsrExt ??
                                                                        "-",
                                                                    fileUrl:
                                                                        data[j]
                                                                            ?.fsrFilePath ??
                                                                        "-",
                                                                  ),
                                                            ),
                                                          );
                                                        }
                                                        : null,
                                                child: Text(
                                                  serviceSubHeadings[i].isEmpty
                                                      ? "-"
                                                      : serviceSubHeadings[i] ??
                                                          "-",
                                                  maxLines: 2,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  textAlign: TextAlign.end,
                                                  style: TextStyle(
                                                    fontSize: 14,
                                                    color:
                                                        (serviceHeadings[i] ==
                                                                "FSR File")
                                                            ? AppColors
                                                                .buttonColor
                                                            : AppColors
                                                                .nearDarkText,
                                                    decoration:
                                                        (serviceHeadings[i] ==
                                                                "FSR File")
                                                            ? TextDecoration
                                                                .underline
                                                            : TextDecoration
                                                                .none,
                                                    decorationColor:
                                                        (serviceHeadings[i] ==
                                                                "FSR File")
                                                            ? AppColors
                                                                .buttonColor
                                                            : AppColors
                                                                .nearDarkText,
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      );
                                    }),
                                    SizedBox(height: 5),
                                    Container(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 0,
                                        vertical: 15,
                                      ),
                                      decoration: BoxDecoration(
                                        color: Color(0xFFE8F6FF),
                                        borderRadius: BorderRadius.circular(16),
                                      ),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Expanded(
                                            flex: 1,
                                            child: CircleAvatar(
                                              backgroundImage:
                                                  data[j].profileImg ==
                                                          "https://erp.gengroup.in/"
                                                      ? AssetImage(
                                                        "assets/images/user_img.png",
                                                      )
                                                      : NetworkImage(
                                                        data[j].profileImg!,
                                                      ),
                                            ),
                                          ),
                                          Expanded(
                                            flex: 2,
                                            child: SizedBox(
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    "${data[j].empName}",
                                                    maxLines: 2,
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                    style: TextStyle(
                                                      color:
                                                          AppColors
                                                              .nearDarkText,
                                                      fontSize: 14,
                                                    ),
                                                  ),
                                                  Text(
                                                    "${data[j].techRoleName}",
                                                    maxLines: 1,
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                    style: TextStyle(
                                                      color:
                                                          AppColors
                                                              .subtitleText,
                                                      fontSize: 12,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                          Expanded(
                                            flex: 2,
                                            child: SizedBox(
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.center,
                                                children: [
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment
                                                            .center,
                                                    children: List.generate(5, (
                                                      index,
                                                    ) {
                                                      final serviceId =
                                                          data[j].id
                                                              ?.toString() ??
                                                          data[j].id.toString();
                                                      final rating = provider
                                                          .getRating(serviceId);
                                                      final starStates =
                                                          provider
                                                              .getStarStates(
                                                                serviceId,
                                                              );
                                                      return InkWell(
                                                        onTap: data[j]?.customerServiceRating !=
                                                            "0"
                                                            ? null
                                                            : () async {
                                                          final newRating =
                                                              index + 1;

                                                          provider.setRating(
                                                            serviceId,
                                                            newRating,
                                                          );

                                                          ScaffoldMessenger.of(
                                                            context,
                                                          ).showSnackBar(
                                                            SnackBar(
                                                              content: Text(
                                                                "Submitting rating...",
                                                              ),
                                                              duration:
                                                                  Duration(
                                                                    seconds: 1,
                                                                  ),
                                                            ),
                                                          );

                                                          await provider
                                                              .updateRatingForTechnician(
                                                                widget.accId,
                                                                widget
                                                                    .sessionId,
                                                                serviceId,
                                                                newRating,
                                                              );
                                                        },
                                                        child: Padding(
                                                          padding:
                                                              const EdgeInsets.symmetric(
                                                                horizontal: 1.7,
                                                              ),
                                                          child: Icon(
                                                            Icons
                                                                .star_rate_rounded,
                                                            color:
                                                                starStates[index]
                                                                    ? const Color(
                                                                      0xffFFB703,
                                                                    )
                                                                    : const Color(
                                                                      0xffCECECE,
                                                                    ),
                                                            size: 22,
                                                          ),
                                                        ),
                                                      );
                                                    }),
                                                  ),
                                                  Text(
                                                    "Your Rating",
                                                    maxLines: 1,
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                    style: TextStyle(
                                                      color:
                                                          AppColors
                                                              .subtitleText,
                                                      fontSize: 12,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
