import 'package:hl_lieferservice/feature/cars/presentation/car_card.dart';

import '../../../model/car.dart';
import 'car_dialog.dart';
import 'package:flutter/material.dart';

class CarManagementOverview extends StatefulWidget {
  final List<Car> cars;
  final Function(String plate) onAdd;
  final Function(String id) onDelete;
  final Function(String id, String plate) onEdit;

  const CarManagementOverview({
    super.key,
    required this.cars,
    required this.onDelete,
    required this.onEdit,
    required this.onAdd,
  });

  @override
  State<StatefulWidget> createState() => _CarManagementOverviewState();
}

class _CarManagementOverviewState extends State<CarManagementOverview> {
  void _addCar() async {
    showDialog(
      context: context,
      builder: (context) {
        return CarDialog(onAction: widget.onAdd);
      },
    );
  }

  void _removeCar(Car car) async {
    widget.onDelete(car.id.toString());
  }

  void _editCar(Car car, String newName) async {
    widget.onEdit(car.id.toString(), newName);
  }

  Widget _buildCarOverview() {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: widget.cars.isEmpty ? const Center(child: Text("keine Fahrzeuge vorhanden")) :  ListView.builder(
        itemBuilder:
            (context, index) => CarCard(
              car: widget.cars[index],
              onEdit: _editCar,
              onDelete: _removeCar,
            ),
        itemCount: widget.cars.length,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Fahrzeugverwaltung",
          style: Theme.of(context).textTheme.headlineMedium,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addCar,
        backgroundColor: Theme.of(context).primaryColor,
        child: Icon(
          Icons.add,
          color: Theme.of(context).colorScheme.onSecondary,
        ),
      ),
      body: _buildCarOverview(),
    );
  }
}
