import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:generp/Utils/app_colors.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import '../Notifiers/CheckInProvider.dart';
import '../Utils/commonServices.dart';
import 'FrontCameraCapture.dart';

class CheckInOutScreen extends StatefulWidget {
  final int getAttendanceStatus;
  const CheckInOutScreen({super.key,required this.getAttendanceStatus});

  @override
  State<CheckInOutScreen> createState() => _CheckInOutScreenState();
}

class _CheckInOutScreenState extends State<CheckInOutScreen> {
  Map _source = {ConnectivityResult.mobile: true};
  final MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    },);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      var prov = Provider.of<CheckInOutProvider>(context, listen: false);
      prov.getLocationPermission(context);
      prov.getCurrentLocation();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _connectivity.disposeStream();
  }



  @override
  Widget build(BuildContext context) {
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.mobile:
        connection = 'Online';
        break;
      case ConnectivityResult.wifi:
        connection = 'Online';
        break;
      case ConnectivityResult.none:
      default:
        connection = 'Offline';
    }
    Size size = MediaQuery.of(context).size;
    double screenWidth = MediaQuery.of(context).size.width;

    return (connection=='Online')?Consumer<CheckInOutProvider>(
      builder: (context, provider, child) {
        return WillPopScope(
          onWillPop: () {
            provider.dispose();
            return onBackPressed(context);},
          child: SafeArea(
            top: false,
            bottom: Platform.isIOS?false:true,
            child: Scaffold(
              resizeToAvoidBottomInset: true,
              appBar: appbar2(context, widget.getAttendanceStatus==0? "Check In":"Check Out", provider.dispose,SizedBox(width: 0,)),
              body:Container(
                child: SafeArea(
                  child: Column(
                    children: [
                      Expanded(
                        child: Stack(
                          children: [
                            GoogleMap(
                              myLocationEnabled: true,
                              zoomGesturesEnabled: true,
                              scrollGesturesEnabled: false,
                              initialCameraPosition: CameraPosition(
                                target: provider.currentLocationLatLng ??
                                    provider.startLocation,
                                zoom: 20.0,
                              ),
                              markers: provider.markers.toSet(),
                              myLocationButtonEnabled: true,
                              mapType: MapType.normal,
                              onMapCreated: (controller) {
                                provider.mapController = controller;
                                provider.getCurrentLocation();
                                provider.getLocationPermission(context);
                              },
                              onCameraMove: (position) {
                                provider.onCameraMove(position,context);
                              },
                            ),
                            Positioned(
                              left: 0,
                              right: 0,
                              bottom: 0,
                              child: Container(
                                height: size.height * 0.3,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(30.0),
                                    topRight: Radius.circular(30.0),
                                  ),
                                ),
                                child: Column(
                                  crossAxisAlignment:
                                  CrossAxisAlignment.start,
                                  children: [
                                    SizedBox(height: 25),

                                    Padding(
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 20.0),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            "Share Your Details",
                                            style: TextStyle(
                                              color: AppColors.app_blue,
                                              fontFamily: "JakartaSemiBold"
                                            ),
                                          ),
                                          SizedBox(height: 10,),
                                          Text(
                                            "Location",
                                            style: TextStyle(
                                              fontFamily: "JakartaMedium",
                                              color: AppColors.semi_black,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    SizedBox(height: 5),
                                    Padding(
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 20.0),
                                      child: Container(
                                        height: 50,

                                        alignment: Alignment.center,
                                        decoration: BoxDecoration(
                                          color: AppColors.text_field_color,
                                          borderRadius:
                                          BorderRadius.circular(14),
                                        ),
                                        child: Padding(
                                          padding:
                                          const EdgeInsets.fromLTRB(
                                              10.0, 0.0, 10, 0),
                                          child: TextFormField(
                                            controller:
                                            provider.locationController,
                                            keyboardType:
                                            TextInputType.text,
                                            onChanged: (value) {
                                              provider.validateLocation = "";
                                              provider.notifyListeners();
                                            },
                                            decoration: InputDecoration(

                                              hintText:
                                              "Enter Check ${widget.getAttendanceStatus==0?"In":"Out"} Location",
                                              hintStyle: TextStyle(
                                                  fontWeight: FontWeight.w400,
                                                  fontSize: 14,
                                                color: Color(0xFF818181)
                                              ),
                                              enabledBorder:
                                              InputBorder.none,
                                              focusedBorder:
                                              InputBorder.none,
                                            ),

                                          ),
                                        ),
                                      ),
                                    ),
                                    if (provider.validateLocation != null)
                                      Padding(
                                        padding:
                                        const EdgeInsets.symmetric(
                                            horizontal: 20.0),
                                        child: Container(
                                          alignment: Alignment.topLeft,
                                          margin: EdgeInsets.only(
                                              top: 2.5,
                                              bottom: 2.5,
                                              left: 25),
                                          child: Text(
                                            provider.validateLocation!,
                                            textAlign: TextAlign.start,
                                            style: TextStyle(
                                              color: Colors.red,
                                            ),
                                          ),
                                        ),
                                      )
                                    else
                                      SizedBox(height: 5.0),
                                    SizedBox(height: 20),
                                    Padding(
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 20.0),
                                      child: InkWell(
                                        onTap: () async {
                                          if (provider
                                              .locationController
                                              .text
                                              .isEmpty) {
                                            provider.validateLocation =
                                            "Please Enter location";
                                            provider.notifyListeners();
                                          } else {
                                            provider.validateLocation = "";
                                            if (Platform.isAndroid) {
                                              provider.image = await Navigator.push(
                                                  context,
                                                  MaterialPageRoute(
                                                      builder: (context) =>
                                                          FrontCameraCapture()));
                                              print("${provider.image}");
                                              if(provider.image!=null){
                                                provider.imagePicked = 1;
                                              }
                                              var file = await FlutterImageCompress.compressWithFile(
                                                provider.image!.path,
                                              );
                                              if (file != null) {
                                                if (widget.getAttendanceStatus == 0) {
                                                  provider.checkIn(context);
                                                } else if (widget.getAttendanceStatus == 1) {
                                                  provider.checkOut(context);
                                                }
                                              }

                                            } else if (Platform.isIOS) {
                                              // BackgroundLocation.stopLocationService();
                                              provider.imgFromCamera(
                                                  context,widget.getAttendanceStatus);
                                              // setState(() {
                                              //   isLoading = true;
                                              //   image_picked = 0;
                                              //   CheckIn();
                                              // });
                                            }


                                          }
                                        },
                                        child: Container(
                                          alignment: Alignment.center,
                                          height: 45,
                                          width: screenWidth,

                                          decoration: BoxDecoration(
                                            color: AppColors.app_blue,
                                            borderRadius:
                                            BorderRadius.circular(15.0),
                                          ),
                                          child: Text(
                                           widget.getAttendanceStatus==0? "Check In":"Check Out",
                                            style: TextStyle(
                                              fontFamily: "JakartaMedium",
                                              fontSize: 16,
                                              color: Colors.white
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    ):NoNetwork(context);
  }
}


