import 'package:flutter/material.dart';

import 'package:anyway/layout.dart';
import 'package:anyway/structs/trip.dart';


class TripsOverview extends StatefulWidget {
  final Future<List<Trip>> trips;
  const TripsOverview({
    super.key,
    required this.trips,
    });

  @override
  State<TripsOverview> createState() => _TripsOverviewState();
}

class _TripsOverviewState extends State<TripsOverview> {

  Widget listBuild (BuildContext context, AsyncSnapshot<List<Trip>> snapshot) {
    List<Widget> children;
    if (snapshot.hasData) {
      children = List<Widget>.generate(snapshot.data!.length, (index) {
        Trip trip = snapshot.data![index];
        return ListTile(
          title: FutureBuilder(
            future: trip.cityName,
            builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
              if (snapshot.hasData) {
                return Text("Trip to ${snapshot.data}");
              } else if (snapshot.hasError) {
                return Text("Error: ${snapshot.error}");
              } else {
                return const Text("Trip to ...");
              }
            },
          ),
          leading: Icon(Icons.pin_drop),
          onTap: () {
            Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => BasePage(mainScreen: "map", trip: trip)
              )
            );
          },
        );
      });
    } else if (snapshot.hasError) {
      children = [
        const Icon(
          Icons.error_outline,
          color: Colors.red,
          size: 60,
        ),
        Padding(
          padding: const EdgeInsets.only(top: 16),
          child: Text('Error: ${snapshot.error}'),
        ),
      ];
    } else {
      children = [Center(child: CircularProgressIndicator())];
    }

    return ListView(
      children: children,
      padding: const EdgeInsets.only(top: 0),
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: widget.trips,
      builder: listBuild,
    );
  }
}