import 'package:app/extensions/obtainProviderExtension.dart';
import 'package:app/extensions/positionLatLngExtension.dart';
import 'package:app/state/mapState.dart';
import 'package:app/state/timeStatusState.dart';
import 'package:app/util/watchState.dart';
import 'package:app/view/appInfo.dart';
import 'package:app/view/locationSearch.dart';
import 'package:app/view/timeWarning.dart';
import 'package:app/view/map.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong2/latlong.dart';

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

  @override
  State<HomeView> createState() => _HomePageState();
}

class _HomePageState extends State<HomeView> {
  bool locationEnabled = false;
  bool locationLoading = false;

  @override
  void initState() {
    super.initState();

    Geolocator.getServiceStatusStream().listen((status) {
      setState(() {
        locationEnabled = status == ServiceStatus.enabled;
      });
    });

    requestLiveLocation(context.obtainState<MapState>(), false, true, true);
  }

  Future<void> requestLiveLocation(MapState mapState, bool ask, bool orLast, bool loadingIndicator) async {
    Position? position;
    LocationPermission permission = await Geolocator.checkPermission();

    if (loadingIndicator && permission != LocationPermission.deniedForever) {
      setState(() {
        locationLoading = true;
      });
    }

    if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) {
      if (ask && permission != LocationPermission.deniedForever) {
        permission = await Geolocator.requestPermission();
      }
      if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) {
        if (orLast) position = await Geolocator.getLastKnownPosition();
      }
    }

    if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) {
      if (position != null) {
        setState(() => locationEnabled = true);
        mapState.setCurrentLocation(position.latlng());
      }
      setState(() => locationLoading = false);
      return;
    }

    try {
      position = await Geolocator.getCurrentPosition();
      setState(() {
        locationEnabled = true;
      });
      mapState.setCurrentLocation(position.latlng());
      mapState.setLocationLive(true);
      Geolocator.getServiceStatusStream().first.then((_) => setState(() {
        mapState.setLocationLive(false);
      }));
    } catch (_) {
      if (orLast) {
        position = await Geolocator.getLastKnownPosition();
        if (position != null) {
          setState(() => locationEnabled = true);
          mapState.setCurrentLocation(position.latlng());
        }
      }
    }

    setState(() => locationLoading = false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text("Bubatzkarte"),
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () async {
              MapState mapState = context.obtainState<MapState>();
              LatLng? latLng = await showSearch<LatLng?>(
                context: context,
                delegate: LocationSearchDelegate(),
              );
              mapState.setActiveMarker(latLng);
            },
          ),
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: () {
              showDialog(
                context: context,
                builder: (context) => const AppInfoView(),
              );
            },
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: WatchState<MapState>((context, state) {
          if (locationLoading) {
            return const Padding(padding: EdgeInsets.all(15), child: CircularProgressIndicator(strokeWidth: 3));
          }
          if (locationEnabled) {
            return Icon(state.isLocationLive ? Icons.my_location : Icons.location_searching);
          }
          return const Icon(Icons.location_disabled);
        }),
        onPressed: () => requestLiveLocation(context.obtainState<MapState>(), true, false, true),
      ),
      body: Column(
        children: [
          WatchState<TimeWarningState>((context, state) {
            if(!state.show || DateTime.now().hour >= 20 || DateTime.now().hour < 7) {
              return const SizedBox.shrink();
            }

            return const SizedBox(
              height: 100,
              child: TimeWarningView(),
            );
          }),
          const Expanded(
            child: MapView(),
          )
        ],
      ),
    );
  }
}
