import 'package:excelso_attendance/api/api.dart';
import 'package:excelso_attendance/api/base_api.dart';
import 'package:excelso_attendance/helper/arguments/error_args.dart';
import 'package:excelso_attendance/helper/arguments/route_args.dart';
import 'package:excelso_attendance/helper/pref.dart';
import 'package:excelso_attendance/helper/widget_responsive.dart';
import 'package:excelso_attendance/main.dart';
import 'package:excelso_attendance/models/branch.dart';
import 'package:excelso_attendance/models/shift.dart';
import 'package:excelso_attendance/resource/assets.dart';
import 'package:excelso_attendance/resource/colors.dart';
import 'package:excelso_attendance/resource/font.dart';
import 'package:excelso_attendance/resource/routes.dart';
import 'package:excelso_attendance/resource/size.dart';
import 'package:excelso_attendance/resource/strings.dart';
import 'package:excelso_attendance/resource/style.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
// ignore: avoid_web_libraries_in_flutter
// import 'dart:html' as html;

class OnBoardingView extends StatefulWidget {
  const OnBoardingView({super.key});

  @override
  State<OnBoardingView> createState() => _OnBoardingViewState();
}

class _OnBoardingViewState extends State<OnBoardingView> {
  bool getAllApi = false;
  String? errorMessage;

  List<BranchModel> nearestBranch = [];
  List<ShiftModel> shiftList = [];

  @override
  void initState() {
    super.initState();
    getUserPermission().then((value) {
      if (value) {
        getUserLocationAndNearestBranch();
      }
    });

    // final perm =
    //     await html.window.navigator.permissions!.query({"name": "camera"});
    // if (perm.state == "denied") {
    //   // ignore: use_build_context_synchronously
    //   Navigator.pushNamedAndRemoveUntil(
    //       context, Routes.errorCamera, (route) => false);
    //   return;
    // }
  }

  Future<bool> getNearestBranch() async {
    ApiResponse getNearestBranch = await Api.getNearestBranch();

    if (getNearestBranch.error) {
      errorMessage = getNearestBranch.msg;
      getAllApi = true;
      return false;
    } else {
      List<BranchModel> dataBranchs =
          getNearestBranch.data["branchs"] as List<BranchModel>;
      String distance = getNearestBranch.data["distance"].toString();
      nearestBranch = dataBranchs;
      if (dataBranchs.isEmpty) {
        errorMessage = Strings.noOutletArround(distance);
        getAllApi = true;
        return false;
      }
      return true;
    }
  }

  void getShiftList() async {
    ApiResponse getShiftList = await Api.getShiftList();
    setState(() {
      getAllApi = true;
      if (getShiftList.error) {
        errorMessage = Strings.errorGetShiftList;
      } else {
        List<ShiftModel> dataShift = getShiftList.data as List<ShiftModel>;
        shiftList = dataShift;
        if (dataShift.isEmpty) {
          errorMessage = Strings.errorGetShiftList;
        }
      }
    });
  }

  Future<void> getUserLocationAndNearestBranch() async {
    Position position = await Geolocator.getCurrentPosition();
    setLatitude(position.latitude.toString()).then((value) {
      setLongitude(position.longitude.toString()).then((value) {
        getNearestBranch().then((branchBool) {
          if (branchBool) {
            // ambil list shift kalau ada outlet
            getShiftList();
          } else {
            // setstate aja, gausah ambil list shift karena gak ada utlet
            setState(() {});
          }
        });
      });
    });
  }

  Future<bool> getUserPermission() async {
    LocationPermission permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.always ||
        permission == LocationPermission.whileInUse) {
      return true;
    } else {
      // ignore: use_build_context_synchronously
      Navigator.pushNamedAndRemoveUntil(
        context,
        Routes.errorWidget,
        (route) => false,
        arguments: ErrorWidgetArguments(
          errorMessage: Strings.locationNotActive,
        ),
      );
      return false;
    }
    // await html.window.navigator.getUserMedia(audio: true, video: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorManager.backgroundColor,
      body: ScreenResponsive(
        widget: BodyWidget(
          getAllApi: getAllApi,
          errorMessage: errorMessage,
          nearestBranch: nearestBranch,
          shiftList: shiftList,
        ),
        widthScreen: MediaQuery.of(context).size.width,
      ),
    );
  }
}

class BodyWidget extends StatelessWidget {
  const BodyWidget({
    super.key,
    required this.getAllApi,
    required this.nearestBranch,
    this.errorMessage,
    required this.shiftList,
  });

  final bool getAllApi;
  final String? errorMessage;
  final List<BranchModel> nearestBranch;
  final List<ShiftModel> shiftList;

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Column(
      children: [
        Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: ColorManager.primary,
            borderRadius: const BorderRadius.only(
              bottomLeft: Radius.circular(50),
              bottomRight: Radius.circular(50),
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: EdgeInsets.only(
                  top: AppPadding.safeAreaTop(context) + 38,
                  left: AppPadding.p20,
                  right: AppPadding.p20,
                ),
                child: Center(
                  child: Image(
                    width: 119,
                    height: 46,
                    image: AssetImage(Assets.excelso),
                  ),
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(
                  horizontal: AppPadding.p20,
                ),
                margin: EdgeInsets.only(
                  top: AppMargin.m16,
                ),
                width: double.infinity,
                height: size.height * 0.37,
                child: Image(
                  fit: BoxFit.fill,
                  image: AssetImage(
                    Assets.onboarding,
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 40,
                ),
                margin: const EdgeInsets.only(
                  top: 32,
                  bottom: 59,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "Attendance",
                      style: getSemiBoldStyle(
                        color: Colors.white,
                        fontSize: 24,
                        fontFamily: FontConstants.montserrat,
                      ),
                    ),
                    Text(
                      '''Memudahkan anda melakukan absen 
dengan sekali klik''',
                      style: getRegularStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
        GestureDetector(
          onTap: () {
            if (getAllApi) {
              Navigator.pushNamed(
                context,
                Routes.home,
                arguments: HomeArguments(
                  branchModel: nearestBranch,
                  shiftModel: shiftList,
                ),
              );
            }
          },
          child: Container(
            margin: EdgeInsets.only(
              top: size.height * 0.05,
            ),
            padding: EdgeInsets.symmetric(
              horizontal: AppPadding.p20,
            ),
            child: Center(
              child: (getAllApi)
                  ? (errorMessage == null)
                      ? Container(
                          width: 60,
                          height: 60,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(100),
                            color: ColorManager.primary,
                          ),
                          child: const Center(
                            child: Icon(
                              Icons.arrow_forward_ios_rounded,
                              color: Colors.white,
                              size: 23,
                            ),
                          ),
                        )
                      : Column(
                          children: [
                            Text(
                              errorMessage!,
                              style: getSemiBoldStyle(
                                color: Colors.black,
                                fontSize: 16,
                              ),
                              textAlign: TextAlign.center,
                            ),
                            (errorMessage == Strings.cantConnectToServer)
                                ? GestureDetector(
                                    onTap: () {
                                      Navigator.pushNamedAndRemoveUntil(
                                        context,
                                        Routes.onBoarding,
                                        (route) => false,
                                      );
                                    },
                                    child: Container(
                                      width: 60,
                                      height: 60,
                                      margin: EdgeInsets.only(
                                        top: AppMargin.m10,
                                      ),
                                      decoration: BoxDecoration(
                                        borderRadius:
                                            BorderRadius.circular(100),
                                        color: ColorManager.primary,
                                      ),
                                      child: const Center(
                                        child: Icon(
                                          Icons.refresh_rounded,
                                          color: Colors.white,
                                          size: 23,
                                        ),
                                      ),
                                    ),
                                  )
                                : const SizedBox(),
                          ],
                        )
                  : CircularProgressIndicator(
                      color: ColorManager.primary,
                    ),
            ),
          ),
        ),
        const Spacer(),
        Container(
          margin: const EdgeInsets.only(
            top: 30,
          ),
          child: Text(
            companyName,
            style: getMediumStyle(
              color: Colors.black,
            ),
          ),
        ),
        SizedBox(
          height: AppMargin.m10,
        )
      ],
    );
  }
}
