import 'package:flutter/material.dart';

import 'package:hl_lieferservice/domain/entity/car.dart';
import 'package:hl_lieferservice/feature/cars/presentation/car_card.dart';
import 'package:hl_lieferservice/feature/cars/presentation/car_dialog.dart';

class CarManagementOverview extends StatefulWidget {
  final List<Car> cars;
  /// UUID des aktuell für heute ausgewählten Fahrzeugs (oder `null`).
  final String? selectedCarId;
  final Function(String plate) onAdd;
  final Function(String id) onDelete;
  final Function(String id, String plate) onEdit;
  final Future<void> Function() onRefresh;

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

  @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) {
    widget.onDelete(car.id);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Fahrzeuge"),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Theme.of(context).colorScheme.onSecondary,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addCar,
        backgroundColor: Theme.of(context).primaryColor,
        child: Icon(
          Icons.add,
          color: Theme.of(context).colorScheme.onSecondary,
        ),
      ),
      body: RefreshIndicator(
        onRefresh: widget.onRefresh,
        child: widget.cars.isEmpty
            ? ListView(
                physics: const AlwaysScrollableScrollPhysics(),
                padding: const EdgeInsets.all(10),
                children: const [
                  SizedBox(
                    height: 200,
                    child: Center(child: Text("keine Fahrzeuge vorhanden")),
                  ),
                ],
              )
            : ListView.builder(
                physics: const AlwaysScrollableScrollPhysics(),
                padding: const EdgeInsets.all(10),
                itemCount: widget.cars.length,
                itemBuilder: (context, index) {
                  final car = widget.cars[index];
                  return CarCard(
                    car: car,
                    isSelected: widget.selectedCarId == car.id,
                    onEdit: _editCar,
                    onDelete: _removeCar,
                  );
                },
              ),
      ),
    );
  }
}
