import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:flutter_svg/svg.dart';
import 'package:gen_service/Notifiers/technicianTrackingProvider.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

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

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

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

  @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,
      );
      final mapProvider = Provider.of<Techniciantrackingprovider>(
        context,
        listen: false,
      );
      mapProvider.getLocationPermission(context);
      mapProvider.polylinePoints = PolylinePoints(
        apiKey: "AIzaSyAA2ukvrb1kWQZ2dttsNIMynLJqVCYYrhw",
      );
    });
  }

  @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: [
                                    if (data[j]?.openStatus == "Open") ...[
                                      Container(
                                        height: 220,
                                        margin: const EdgeInsets.symmetric(
                                          horizontal: 5,
                                          vertical: 10,
                                        ),
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(
                                            18,
                                          ),
                                        ),
                                        child: ClipRRect(
                                          borderRadius: BorderRadius.circular(
                                            18,
                                          ),
                                          child: Consumer<
                                            Techniciantrackingprovider
                                          >(
                                            builder: (
                                              context,
                                              mapProvider,
                                              child,
                                            ) {
                                              return Stack(
                                                clipBehavior: Clip.none,
                                                children: [
                                                  GoogleMap(
                                                    initialCameraPosition: CameraPosition(
                                                      target:
                                                          mapProvider.currentLocation !=
                                                                  null
                                                              ? LatLng(
                                                                mapProvider
                                                                    .currentLocation!
                                                                    .latitude!,
                                                                mapProvider
                                                                    .currentLocation!
                                                                    .longitude!,
                                                              )
                                                              : mapProvider
                                                                  .startLocation,
                                                      zoom: 15,
                                                    ),
                                                    myLocationEnabled: true,
                                                    myLocationButtonEnabled:
                                                        false,
                                                    zoomControlsEnabled: false,
                                                    mapType: MapType.normal,
                                                    markers:
                                                        mapProvider.markers,
                                                    polylines:
                                                        mapProvider.polylines,
                                                    onMapCreated: (
                                                      GoogleMapController
                                                      controller,
                                                    ) {
                                                      mapProvider
                                                              .mapController =
                                                          controller;
                                                      mapProvider.setMapStyle(
                                                        controller,
                                                      );

                                                      final double? techLat1 = 17.4484769;
                                                      final double? techLng1 = 78.3710461;

                                                      final double? techLat = double.tryParse(
                                                        data[j]?.lat?.trim() ?? '${techLat1}',
                                                      )??techLat1;
                                                      final double? techLng = double.tryParse(
                                                        data[j]?.lng?.trim() ?? '${techLng1}',
                                                      )??techLng1;

                                                      if (techLat != null &&
                                                          techLng != null &&
                                                          techLat != 0 &&
                                                          techLng != 0) {
                                                        mapProvider
                                                            .updateTechnicianLocation(
                                                              techLat,
                                                              techLng,
                                                            );
                                                      }
                                                    },
                                                  ),
                                                  Positioned(
                                                    bottom: 0,
                                                    left: 0,
                                                    right: 0,
                                                    child: Align(
                                                      alignment:
                                                          Alignment
                                                              .bottomCenter,
                                                      child: Container(
                                                        decoration: BoxDecoration(
                                                          gradient: LinearGradient(
                                                            colors: [
                                                              Color(
                                                                0xFFFFFFFF,
                                                              ).withOpacity(
                                                                0.01,
                                                              ),
                                                              Color(0xFFFFFFFF),
                                                              Color(0xFFFFFFFF),
                                                              Color(
                                                                0xFFFFFFFF,
                                                              ).withOpacity(
                                                                0.01,
                                                              ),
                                                            ],
                                                            begin:
                                                                Alignment
                                                                    .bottomCenter,
                                                            end:
                                                                Alignment
                                                                    .topCenter,
                                                          ),
                                                        ),

                                                        child: Column(
                                                          children: [
                                                            InkResponse(
                                                              onTap: () async {
                                                                await Navigator.push(
                                                                  context,
                                                                  MaterialPageRoute(
                                                                    builder:
                                                                        (
                                                                        context,
                                                                        ) => TechnicianTrackingScreen(
                                                                      allDet:
                                                                      data[j],
                                                                          from: "All",
                                                                          complaintData: widget.complaintData,


                                                                    ),
                                                                  ),
                                                                );
                                                              },
                                                              child: Container(
                                                                decoration: BoxDecoration(
                                                                  gradient: LinearGradient(
                                                                    colors: [
                                                                      Color(
                                                                        0xFFFFFFFF,
                                                                      ),
                                                                      Color(
                                                                        0xFFFFFFFF,
                                                                      ),
                                                                      Color(
                                                                        0xFFFFFFFF,
                                                                      ),
                                                                      Color(
                                                                        0xFFFFFFFF,
                                                                      ).withOpacity(
                                                                        0.8,
                                                                      ),
                                                                      Color(
                                                                        0xFFFFFFFF,
                                                                      ).withOpacity(
                                                                        0.5,
                                                                      ),
                                                                      Color(
                                                                        0xFFFFFFFF,
                                                                      ).withOpacity(
                                                                        0.1,
                                                                      ),
                                                                      Color(
                                                                        0xFFFFFFFF,
                                                                      ).withOpacity(
                                                                        0.01,
                                                                      ),
                                                                    ],
                                                                    begin:
                                                                        Alignment
                                                                            .bottomCenter,
                                                                    end:
                                                                        Alignment
                                                                            .topCenter,
                                                                  ),
                                                                ),
                                                                padding:
                                                                    EdgeInsets.symmetric(
                                                                      vertical:
                                                                          10,
                                                                    ),
                                                                child: Center(
                                                                  child: Text(
                                                                    "Tap to Track Engineer",
                                                                    textAlign:
                                                                        TextAlign
                                                                            .center,
                                                                    style: TextStyle(
                                                                      fontSize:
                                                                          14,
                                                                      color:
                                                                          AppColors
                                                                              .buttonColor,
                                                                    ),
                                                                  ),
                                                                ),
                                                              ),
                                                            ),
                                                            Align(
                                                              alignment:
                                                                  Alignment
                                                                      .bottomCenter,
                                                              child: Container(
                                                                height: 60,
                                                                padding:
                                                                    EdgeInsets.symmetric(
                                                                      horizontal:
                                                                          0,
                                                                      vertical:
                                                                          10,
                                                                    ),
                                                                decoration: BoxDecoration(
                                                                  color: Color(
                                                                    0xFFE8F6FF,
                                                                  ),
                                                                  borderRadius:
                                                                      BorderRadius.circular(
                                                                        18,
                                                                      ),
                                                                ),
                                                                child: Row(
                                                                  mainAxisAlignment:
                                                                      MainAxisAlignment
                                                                          .spaceBetween,
                                                                  children: [
                                                                    Expanded(
                                                                      flex: 1,
                                                                      child: CircleAvatar(
                                                                        radius:
                                                                            25,
                                                                        backgroundImage:
                                                                            data[j]?.profileImg ==
                                                                                    "https://erp.gengroup.in/"
                                                                                ? AssetImage(
                                                                                  "assets/images/user_img.png",
                                                                                )
                                                                                : NetworkImage(
                                                                                  "${data[j]?.profileImg}",
                                                                                ),
                                                                      ),
                                                                    ),
                                                                    Expanded(
                                                                      flex: 3,
                                                                      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: 1,
                                                                      child: SizedBox(
                                                                        child: Column(
                                                                          crossAxisAlignment:
                                                                              CrossAxisAlignment.center,
                                                                          mainAxisAlignment:
                                                                              MainAxisAlignment.center,
                                                                          children: [
                                                                            InkResponse(
                                                                              onTap: () async {
                                                                                var url =
                                                                                    "tel:${data[j]?.mobNum}";
                                                                                if (await canLaunch(
                                                                                  url,
                                                                                )) {
                                                                                  await launch(
                                                                                    url,
                                                                                  );
                                                                                } else {
                                                                                  throw 'Could not launch $url';
                                                                                }
                                                                              },
                                                                              child: Image.asset(
                                                                                "assets/images/call_technicain_ic.png",
                                                                                fit:
                                                                                    BoxFit.cover,
                                                                                height:
                                                                                    40,
                                                                                width:
                                                                                    40,
                                                                              ),
                                                                            ),
                                                                          ],
                                                                        ),
                                                                      ),
                                                                    ),
                                                                  ],
                                                                ),
                                                              ),
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              );
                                            },
                                          ),
                                        ),
                                      ),
                                    ] else ...[
                                      ...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]
                                                                              ?.filePath ??
                                                                          "-",
                                                                    ),
                                                              ),
                                                            );
                                                          }
                                                          : 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,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
