import 'package:flutter/material.dart';
import 'package:project_manager/pages/delivery_item.dart';
import 'package:project_manager/utils/dataObjects/delivery.dart';

import '../utils/api/deliveries.dart';

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

  @override
  State<ListViewHome> createState() => _ListViewState();
}

/// The following API endpoints are what should be used for the inventory
/// GET      specific delivery:   GET      http://10.0.2.2:21000/deliveries/{delivery_id}
/// DELETE   specific delivery:   DELETE   http://10.0.2.2:21000/deliveries/{delivery_id}
/// UPDATE   specific delivery:   PUT      http://10.0.2.2:21000/deliveries/{delivery_id}
/// Note: The entirety of the updated delivery object needs to be sent as the request body
/// The format above is just for notes: <HTTP Method>  <URL>

class _ListViewState extends State<ListViewHome> {
  Future<List<Delivery>> futureDeliveries = fetchDeliveries();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FutureBuilder<List<Delivery>>(
          future: futureDeliveries,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const CircularProgressIndicator();
            } else if (snapshot.hasData) {
              final deliveries = snapshot.data!;
              return buildDeliveries(deliveries);
            } else {
              return const Text("No data available");
            }
          },
        ),
      ),
    );
  }

  Widget buildDeliveries(List<Delivery> deliveries) {
    return ListView.builder(
      itemCount: deliveries.length,
      itemBuilder: (context, index) {
        final delivery = deliveries[index];
        return Container(
          color: Colors.grey.shade300,
          margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 1),
          padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 1),
          height: 120,
          width: double.maxFinite,
          child: Row(
            children: [
              Expanded(
                  flex: 1, child: Text("Delivery #${delivery.deliveryId!}")),
              const SizedBox(width: 15),
              Expanded(
                  flex: 2,
                  child: Text(
                      "${delivery.addressLine1!} ${delivery.addressLine2 == "NaN" ? "" : delivery.addressLine2}")),
              Expanded(
                  flex: 3,
                  child: TextButton(
                    onPressed: () {Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => DeliveryCard(id: delivery.deliveryId!)),
                    );},
                    child: const Text('View Details'),
                  )),
            ],
          ),
        );
      },
    );
  }
}
