import 'package:flutter/material.dart';
import 'package:garage/car/widget/date_picker_button.dart';
import 'package:garage/utils/expiry_colors.dart';
import 'package:garage/utils/show_ok_dialog.dart';
import 'package:get_it/get_it.dart';

import '../../utils/date_time_utils.dart';
import '../model/car.dart';
import '../service/car_service.dart';

class CarRow extends StatefulWidget {
  final Car car;
  final VoidCallback refresh;

  const CarRow({super.key, required this.car, required this.refresh});

  @override
  State<CarRow> createState() => _CarRowState();
}

class _CarRowState extends State<CarRow> {
  final CarService carService = GetIt.instance<CarService>();

  late DateTime? newExpirationSTK =
      widget.car.getCurrentSTK()!.add(Duration(days: 2 * 365));

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(10.0),
      child: Row(
        children: [
          _buildCell(widget.car.name),
          _buildCell(widget.car.spz),
          _buildCell(getPrettyDate(widget.car.getCurrentSTK())),
          FloatingActionButton(
            heroTag: "STK ${widget.car.name}",
            onPressed: () => _setNextSTK(context),
            child: Text("STK"),
          )
        ],
      ),
    );
  }

  Widget _buildCell(String text) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(10.0),
        child: Text(text, style: _getTextStyle()),
      ),
    );
  }

  void _setNextSTK(BuildContext context) {
    showDialog<String>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
                title: Text("Prodloužit STK pro:"),
                content: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text("Název: ${widget.car.name}"),
                    Text("Výrobce: ${widget.car.brand}"),
                    Text("Spz: ${widget.car.spz}"),
                    Text(
                        "Aktuální expirace STK: ${getPrettyDate(widget.car.getCurrentSTK())}"),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text("Nová expirace STK:"),
                        DatePickerButton(
                            date: newExpirationSTK,
                            onSave: (date) =>
                                setState(() => newExpirationSTK = date))
                      ],
                    )
                  ],
                ),
                actions: <Widget>[
                  TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: Text("Zrušit")),
                  TextButton(
                      onPressed: () {
                        if (newExpirationSTK == null) {
                          showOkDialog(context, "Nový datum STK nevybrán!");
                          return;
                        }
                        Car newCar =
                            widget.car.copyWithNewSTK(newExpirationSTK!);
                        carService.updateItem(newCar);
                        Navigator.pop(context);
                        showOkDialog(context,
                            "Nová STK: ${getPrettyDate(newExpirationSTK)}");
                        widget.refresh();
                        setState(() {
                          newExpirationSTK = widget.car
                              .getCurrentSTK()!
                              .add(Duration(days: 2 * 365));
                        });
                      },
                      child: Text("Uložit")),
                ]));
  }

  TextStyle? _getTextStyle() {
    final expiryColors = Theme.of(context).extension<ExpiryColors>()!;
    final bool expired = widget.car.getCurrentSTK()!.isBefore(DateTime.now());
    final bool lessThanMonth = widget.car
        .getCurrentSTK()!
        .isBefore(DateTime.now().add(Duration(days: 30)));
    if (expired) {
      return TextStyle(
          color: expiryColors.expired, fontWeight: FontWeight.bold);
    }
    if (lessThanMonth) {
      return TextStyle(
          color: expiryColors.monthLess, fontWeight: FontWeight.bold);
    }
    return null;
  }
}
