import 'package:flutter/material.dart';

enum CarAction { edit, add }

class CarDialog extends StatefulWidget {
  const CarDialog({
    super.key,
    required this.onAction,
    this.action = CarAction.add,
    this.initialPlateValue = "",
  });

  final CarAction action;
  final String initialPlateValue;
  final Function(String) onAction;

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

class _CarDialogState extends State<CarDialog> {
  final _formKey = GlobalKey<FormState>();
  late final TextEditingController _plateController;

  @override
  void initState() {
    super.initState();

    _plateController = TextEditingController.fromValue(
      TextEditingValue(text: widget.initialPlateValue),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      content: SizedBox(
        height: 120,
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: const EdgeInsets.only(bottom: 10.0),
                child: Text(
                  "Fahrzeug ${widget.action == CarAction.add ? "hinzufügen" : "bearbeiten"}",
                  style: const TextStyle(
                    fontSize: 18.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              TextFormField(
                validator: (value) {
                  if (value == "") {
                    return "Kennzeichen darf nicht leer sein";
                  }

                  return null;
                },
                decoration: const InputDecoration(labelText: "Kennzeichen"),
                controller: _plateController,
              ),
            ],
          ),
        ),
      ),
      actions: [
        OutlinedButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: const Text("Abbrechen"),
        ),
        FilledButton(
          onPressed: () {
            if (_formKey.currentState!.validate()) {
              widget.onAction(_plateController.text);
              Navigator.of(context).pop();
            }
          },
          child: Text(
            widget.action == CarAction.add ? "Hinzufügen" : "Bearbeiten",
          ),
        ),
      ],
    );
  }
}
