import 'package:anyway/main.dart';
import 'package:anyway/pages/current_trip.dart';
import 'package:anyway/structs/preferences.dart';
import 'package:anyway/structs/trip.dart';
import 'package:anyway/utils/fetch_trip.dart';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';


class NewTripButton extends StatefulWidget {
  final Trip trip;
  final UserPreferences preferences;

  const NewTripButton({super.key,
    required this.trip,
    required this.preferences,
    });

  @override
  State<NewTripButton> createState() => _NewTripButtonState();
}

class _NewTripButtonState extends State<NewTripButton> {

  @override
  Widget build(BuildContext context) {
    return ListenableBuilder(
      listenable: widget.trip,
      builder: (BuildContext context, Widget? child) {
        if (widget.trip.landmarks.isEmpty){
          // Fallback if the trip setup is lagging behind
          // This should in theory never happen
          return Container();
        }
        return FloatingActionButton.extended(
          onPressed: onPressed,
          icon: const Icon(Icons.directions),
          label: const AutoSizeText('Start planning!'),
        );
      }
    );
  }

  void onPressed() async {
    // Check that the preferences are valid
    UserPreferences preferences = widget.preferences;
    if (preferences.nature.value == 0 && preferences.shopping.value == 0 && preferences.sightseeing.value == 0){
      rootScaffoldMessengerKey.currentState!.showSnackBar(
        const SnackBar(content: Text("Please specify at least one preference"))
      );
    } else if (preferences.maxTime.value == 0){
      rootScaffoldMessengerKey.currentState!.showSnackBar(
        const SnackBar(content: Text("Please choose a longer duration"))
      );
    } else {
      Trip trip = widget.trip;
      fetchTrip(trip, widget.preferences);
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => TripPage(trip: trip)
        )
      );
    }
  }
}
