import 'package:flutter/material.dart';
import 'package:garage/car/widget/add_edit_text_field.dart';
import 'package:garage/insurance/model/currency.dart';
import 'package:garage/insurance/model/insurance.dart';
import 'package:garage/insurance/widget/currency_picker.dart';
import 'package:get_it/get_it.dart';

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

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

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

  @override
  State<InsuranceRow> createState() => _InsuranceRowState();
}

class _InsuranceRowState extends State<InsuranceRow> {
  final CarService carService = GetIt.instance<CarService>();
  late Insurance insurance = widget.car.getCurrentInsurance()!;
  late final List<TextEditingController> controllers = [
    TextEditingController(text: insurance.contractNumber),
    TextEditingController(text: insurance.company),
    TextEditingController(text: insurance.amount.toString()),
  ];
  late DateTime? expiration = insurance.expirationDate.add(Duration(days: 365));
  late Currency? currency = insurance.currency;

  @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.getCurrentInsurance()!.expirationDate)),
          FloatingActionButton(
            heroTag: "STK ${widget.car.name}",
            child: Text("Pojistka"),
            onPressed: () => _setNextInsurance(context),
          )
        ],
      ),
    );
  }

  void _setNextInsurance(BuildContext context) {
    showDialog<String>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
                title: Text("Nová pojistka pro:"),
                content: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text("Název: ${widget.car.name}"),
                    Text("Výrobce: ${widget.car.brand}"),
                    Text("Spz: ${widget.car.spz}"),
                    Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text("Číslo smlouvy: "),
                          Flexible(
                            child: AddEditTextField(
                                controller: controllers[0],
                                hint: "",
                                onlyNumbers: false),
                          ),
                        ]),
                    Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text("Společnost: "),
                          Flexible(
                            child: AddEditTextField(
                                controller: controllers[1],
                                hint: "",
                                onlyNumbers: false),
                          ),
                        ]),
                    Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text("Cena: "),
                          Flexible(
                            child: AddEditTextField(
                                controller: controllers[2],
                                hint: "",
                                onlyNumbers: true),
                          ),
                          Flexible(
                            child: CurrencyPicker(
                                onChanged: (value) =>
                                    setState(() => currency = value),
                                initialValue: currency),
                          )
                        ]),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text("Nová expirace pojištění:"),
                        DatePickerButton(
                            date: expiration,
                            onSave: (date) => setState(() => expiration = date))
                      ],
                    )
                  ],
                ),
                actions: <Widget>[
                  TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: Text("Zrušit")),
                  TextButton(
                      onPressed: () {
                        if (expiration == null) {
                          showOkDialog(
                              context, "Nový datum expirace nevybrán!");
                          return;
                        }
                        if (currency == null) {
                          showOkDialog(context, "Nevybrána měna!");
                          return;
                        }
                        final Insurance newInsurance = Insurance(
                            company: controllers[1].text,
                            contractNumber: controllers[0].text,
                            amount: int.parse(controllers[2].text),
                            currency: currency!,
                            expirationDate: expiration!);
                        Car car = widget.car.copyAndAddInsurance(newInsurance);
                        carService.updateItem(car);
                        Navigator.pop(context);
                        showOkDialog(context,
                            "Nová pojištění do: ${getPrettyDate(expiration)}");
                        widget.refresh();
                        setState(() {
                          expiration = widget.car
                              .getCurrentInsurance()!
                              .expirationDate
                              .add(Duration(days: 365));
                        });
                      },
                      child: Text("Uložit")),
                ]));
  }

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

  TextStyle? _setTextStyle() {
    final DateTime date = widget.car.getCurrentInsurance()!.expirationDate;
    final bool expired = date.isBefore(DateTime.now());
    final bool lessThanMonth =
        date.isBefore(DateTime.now().add(Duration(days: 30)));
    if (expired) {
      return TextStyle(color: Colors.red, fontWeight: FontWeight.bold);
    }
    if (lessThanMonth) {
      return TextStyle(color: Colors.orange, fontWeight: FontWeight.bold);
    }

    return null;
  }
}
