import 'package:app/extensions/obtainProviderExtension.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;

  Future<LatLng?> getLatLng() async {
    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) {
        return null;
      }
    }

    setState(() {
      locationEnabled = true;
    });

    Position? position;
    try {
      position = await Geolocator.getCurrentPosition();
    } catch (e) {
      position = await Geolocator.getLastKnownPosition();
    }

    if (position != null) {
      return LatLng(position.latitude, position.longitude);
    }
    return null;
  }


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

    Geolocator.checkPermission().then((permission) => setState(() {
      locationEnabled = permission != LocationPermission.denied && permission != LocationPermission.deniedForever;
    }));
  }

  @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);
              if (latLng != null) {
                mapState.getMapController.move(latLng, 16);
              }
            },
          ),
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: () {
              showDialog(
                context: context,
                builder: (context) => const AppInfoView(),
              );
            },
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: WatchState<MapState>((context, state) {
          if(locationEnabled)  {
            if(state.isCurrentlyLoading) {
              return const Padding(padding: EdgeInsets.all(15), child: CircularProgressIndicator(strokeWidth: 3));
            } else {
              return const Icon(Icons.my_location);
            }
          }

          return const Icon(Icons.location_disabled);
        }),
        onPressed: () async {
          MapState mapState = context.obtainState<MapState>();
          mapState.setLoading(true);
          LatLng? latLng = await getLatLng();
          if (latLng != null) {
            mapState.setCurrentLocation(latLng);
            mapState.getMapController.move(latLng, 16);
          }
          mapState.setLoading(false);
        },
      ),
      body: Column(
        children: [
          WatchState<TimeWarningState>((context, state) {
            if(!state.show) return const SizedBox.shrink();

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