import 'dart:io';
import 'dart:ui';
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter/material.dart';
import 'package:gen_service/Models/HelpAndComplaintModels/allServiceListResponse.dart';
import 'package:gen_service/Notifiers/technicianTrackingProvider.dart';
import 'package:gen_service/Services/api_calling.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';

import '../../Models/HelpAndComplaintModels/complaintDetailsResponse.dart';
import '../../Utility/AppColors.dart';

class TechnicianTrackingScreen extends StatefulWidget {
  final ServiceDetails? details;
  final AllServiceList? allDet;
  final String from;
  final ComplaintDetails? complaintData;

  const TechnicianTrackingScreen({
    super.key,
    this.details,
    this.allDet,
    required this.from,
    required this.complaintData,
  });

  @override
  _TechnicianTrackingScreenState createState() =>
      _TechnicianTrackingScreenState();
}

class _TechnicianTrackingScreenState extends State<TechnicianTrackingScreen> {
  var serviceData;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      final mapProvider = Provider.of<Techniciantrackingprovider>(
        context,
        listen: false,
      );
      mapProvider.getLocationPermission(context);
      mapProvider.polylinePoints = PolylinePoints(
        apiKey: "AIzaSyAA2ukvrb1kWQZ2dttsNIMynLJqVCYYrhw",
      );
      if (widget.from == "All") {
        serviceData = widget.allDet;
      } else {
        serviceData = widget.details;
      }
    });

    // InitialPorterFunction();
  }

  @override
  void dispose() {
    // TODO: implement dispose

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;
    return SafeArea(
      top: false,
      bottom: Platform.isIOS ? false : true,
      maintainBottomViewPadding: true,
      child: Scaffold(
        resizeToAvoidBottomInset: true,
        backgroundColor: Color(0xFF4076FF),

        body: Consumer<Techniciantrackingprovider>(
          builder: (context, mapProvider, child) {
            return CustomScrollView(
              slivers: [
                SliverAppBar(
                  automaticallyImplyLeading: false,
                  stretch: true,
                  onStretchTrigger: () async {},
                  stretchTriggerOffset: 300.0,
                  backgroundColor: Color(0xFF4076FF),
                  expandedHeight: screenHeight * 0.15,
                  flexibleSpace: FlexibleSpaceBar(
                    stretchModes: const [
                      StretchMode.zoomBackground,
                      StretchMode.blurBackground,
                    ],
                    background: Container(
                      decoration: const BoxDecoration(
                        gradient: AppColors.commonAppBarGradient,
                      ),
                      child: SafeArea(
                        child: Column(
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                SizedBox(width: 8),
                                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(
                                      "Track Technician",
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 1,
                                      style: TextStyle(
                                        fontSize: 16,
                                        color: Colors.white,
                                        height: 1.1,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),

                            SizedBox(height: 10),
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 10,
                                vertical: 5,
                              ),
                              child: Column(
                                children: [
                                  // Product Info Row
                                  Padding(
                                    padding: const EdgeInsets.symmetric(
                                      vertical: 4.0,
                                    ),
                                    child: Row(
                                      children: [
                                        Expanded(
                                          flex: 5,
                                          child: Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              RichText(
                                                text: TextSpan(
                                                  style: const TextStyle(
                                                    fontFamily: 'Poppins',
                                                    color: Color(0xFF48F3FF),
                                                    fontSize: 12,
                                                  ),
                                                  children: [
                                                    TextSpan(
                                                      text:
                                                          "#${widget.complaintData?.id!}",
                                                    ),
                                                    TextSpan(
                                                      text:
                                                          (widget.complaintData?.complaintName ??
                                                                      "")
                                                                  .isNotEmpty
                                                              ? " | ${widget.complaintData?.complaintName!}"
                                                              : "",
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              Text(
                                                "${widget.complaintData?.registredDate ?? ""}",
                                                maxLines: 2,
                                                style: const TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 14,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                        Expanded(
                                          flex: 2,
                                          child: Container(
                                            padding: EdgeInsets.symmetric(
                                              horizontal: 15,
                                              vertical: 7,
                                            ),
                                            decoration: BoxDecoration(
                                              color:
                                                  widget
                                                              .complaintData
                                                              ?.openStatus ==
                                                          "Open"
                                                      ? AppColors.successBG
                                                      : AppColors.yellowBG,
                                              borderRadius:
                                                  BorderRadius.circular(10),
                                            ),
                                            child: Center(
                                              child: Text(
                                                "${widget.complaintData?.openStatus}",
                                                style: TextStyle(
                                                  fontFamily: "Poppins",
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.w400,
                                                  color:
                                                      widget
                                                                  .complaintData
                                                                  ?.openStatus ==
                                                              "Open"
                                                          ? AppColors.success
                                                          : AppColors
                                                              .normalText,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
                SliverFillRemaining(
                  hasScrollBody: false,
                  child: Container(
                    decoration: const BoxDecoration(
                      color: AppColors.backgroundRegular,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(30),
                        topRight: Radius.circular(30),
                      ),
                    ),
                    padding: const EdgeInsets.symmetric(
                      horizontal: 5,
                      vertical: 0,
                    ),
                    child: Column(
                      children: [
                        Container(
                          margin: const EdgeInsets.symmetric(
                            horizontal: 0,
                            vertical: 5,
                          ),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(18),
                          ),
                          height: screenHeight * 0.8,
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(18),

                            child: GoogleMap(
                              myLocationEnabled: true,
                              zoomGesturesEnabled: true,
                              zoomControlsEnabled: true,
                              scrollGesturesEnabled: false,

                              gestureRecognizers: {
                                Factory<OneSequenceGestureRecognizer>(
                                      () => EagerGestureRecognizer(),
                                ),
                                Factory<PanGestureRecognizer>(
                                      () => PanGestureRecognizer(),
                                ),
                                Factory<ScaleGestureRecognizer>(
                                      () => ScaleGestureRecognizer(),
                                ),
                              },
                              initialCameraPosition: CameraPosition(
                                target:
                                    mapProvider.currentLocation != null
                                        ? LatLng(
                                          mapProvider
                                              .currentLocation!
                                              .latitude!,
                                          mapProvider
                                              .currentLocation!
                                              .longitude!,
                                        )
                                        : mapProvider.startLocation,
                                zoom: 15,
                              ),
                              myLocationButtonEnabled: 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(
                                  serviceData?.lat?.trim() ?? '${techLat1}',
                                )??techLat1;
                                final double? techLng = double.tryParse(
                                  serviceData?.lng?.trim() ?? '${techLng1}',
                                )??techLng1;

                                if (techLat != null &&
                                    techLng != null &&
                                    techLat != 0 &&
                                    techLng != 0) {
                                  mapProvider.updateTechnicianLocation(
                                    techLat,
                                    techLng,
                                  );
                                }
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            );
          },
        ),

        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
        floatingActionButton: Container(
          alignment: Alignment.center,
          height: 80,
          width: screenWidth,
          padding: EdgeInsets.symmetric(horizontal: 0, vertical: 10),
          margin: EdgeInsets.symmetric(horizontal: 10),

          decoration: BoxDecoration(
            color: Color(0xFF008CDE),
            borderRadius: BorderRadius.circular(50),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                flex: 1,
                child: CircleAvatar(
                  radius: 25,
                  backgroundImage:
                      serviceData?.profileImg == "https://erp.gengroup.in/"
                          ? AssetImage("assets/images/user_img.png")
                          : NetworkImage("${serviceData?.profileImg}"),
                ),
              ),
              Expanded(
                flex: 3,
                child: SizedBox(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "${serviceData?.empName}",
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                      ),
                      Text(
                        "${serviceData?.techRoleName}",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: SizedBox(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      InkResponse(
                        onTap: () async {
                          var url = "tel:${serviceData?.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,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
