import 'dart:io';

import 'package:flutter/material.dart';
import 'package:garage/car/model/tyre_type.dart';
import 'package:garage/car/service/car_service.dart';
import 'package:garage/car/widget/add_edit_text_field.dart';
import 'package:garage/car/widget/date_picker_button.dart';
import 'package:garage/car/widget/tyre_picker.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:garage/user/model/user_provider.dart';
import 'package:get_it/get_it.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import '../model/car.dart';

class AddCarPage extends StatefulWidget {
  final VoidCallback callback;

  const AddCarPage({super.key, required this.callback});

  @override
  State<AddCarPage> createState() => _AddCarPageState();
}

class _AddCarPageState extends State<AddCarPage> {
  final CarService carService = GetIt.instance<CarService>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  File? photo;
  DateTime? _highwayToll;
  DateTime? _expirationSTK;
  bool withInsurance = false;
  TyreType _tyreType = getTyres();
  Currency? currency = Currency.CZK;
  DateTime? _expirationInsurance;
  late final List<TextEditingController> _carCons =
      List.generate(4, (_) => TextEditingController());

  late final List<TextEditingController> _insuranceCons =
      List.generate(3, (_) => TextEditingController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Form(
          key: formKey,
          autovalidateMode: AutovalidateMode.disabled,
          child: ListView(
            children: [
              Text(
                "Detaily vozidla",
                style: TextStyle(fontSize: 25),
              ),

              // Car fields
              AddEditTextField(
                controller: _carCons[0],
                hint: "Název",
                validator: (val) =>
                    (val == null || val.isEmpty) ? "Povinné pole" : null,
              ),
              AddEditTextField(controller: _carCons[1], hint: "SPZ"),
              AddEditTextField(controller: _carCons[2], hint: "Výrobce"),
              AddEditTextField(controller: _carCons[3], hint: "Model"),
              _buildPickerRow(
                "Platnost dálniční známky:",
                DatePickerButton(
                    date: _highwayToll,
                    onSave: (date) => setState(() => _highwayToll = date)),
              ),
              _buildPickerRow(
                  "Datum expirace STK:",
                  DatePickerButton(
                      date: _expirationSTK,
                      onSave: (date) => setState(() => _expirationSTK = date))),
              _buildPickerRow(
                  "Druh pneumatik:",
                  Flexible(
                    flex: 2,
                    child: TyrePicker(
                        onChanged: (type) => setState(() => _tyreType = type!),
                        initialValue: _tyreType),
                  )),
              ElevatedButton(
                  onPressed: _selectImage,
                  child: Text(photo == null ? "Nahrát fotku" : "Změnit fotku")),
              _displayImage(),

              // Insurance fields
              Row(
                children: [
                  Expanded(
                    child: Text(
                      "Pojištění",
                      style: TextStyle(fontSize: 25),
                    ),
                  ),
                  Switch(
                      value: withInsurance,
                      onChanged: (value) {
                        setState(() {
                          withInsurance = !withInsurance;
                        });
                      }),
                ],
              ),
              if (withInsurance) ...initInsuranceFields(),
              Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                Padding(
                  padding: const EdgeInsets.only(bottom: 10),
                  child: FloatingActionButton.extended(
                    heroTag: "Save",
                    onPressed: () => _saveCar(context),
                    label: Text("Uložit záznam"),
                  ),
                ),
              ])
            ],
          ),
        ),
      ),
    );
  }

  Future _selectImage() async {
    final returnedImage =
        await ImagePicker().pickImage(source: ImageSource.gallery);
    if (returnedImage == null) {
      return;
    }
    setState(() {
      photo = File(returnedImage.path);
    });
  }

  Widget _displayImage() {
    return photo == null
        ? Center()
        : Stack(
            children: [
              Padding(
                padding: const EdgeInsets.all(10.0),
                child: Center(
                  child: ClipRRect(
                      borderRadius: const BorderRadius.all(Radius.circular(10)),
                      child: Image.file(photo!, height: 200)),
                ),
              ),
              Positioned(
                right: -10,
                top: -10,
                child: IconButton(
                    color: Colors.red,
                    onPressed: () {
                      setState(() {
                        photo = null;
                      });
                    },
                    icon: Icon(Icons.highlight_remove_rounded)),
              )
            ],
          );
  }

  Widget _buildPickerRow(String text, Widget child) {
    return Padding(
      padding: const EdgeInsets.only(left: 12.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [Text(text, style: TextStyle(fontSize: 16)), Spacer(), child],
      ),
    );
  }

  List<Widget> initInsuranceFields() {
    return [
      AddEditTextField(controller: _insuranceCons[0], hint: "Číslo smlouvy"),
      AddEditTextField(controller: _insuranceCons[1], hint: "Společnost"),
      Row(
        children: [
          Flexible(
              flex: 4,
              child: AddEditTextField(
                  controller: _insuranceCons[2],
                  hint: "Cena",
                  onlyNumbers: true)),
          Flexible(
              child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: CurrencyPicker(
                initialValue: Currency.CZK,
                onChanged: (newVal) => setState(() => currency = newVal)),
          )),
        ],
      ),
      _buildPickerRow(
          "Datum expirace pojištění:",
          DatePickerButton(
              date: _expirationSTK,
              onSave: (date) => setState(() => _expirationInsurance = date))),
    ];
  }

  void _saveCar(BuildContext context) {
    if (!formKey.currentState!.validate()) {
      return;
    }
    if (_expirationSTK == null) {
      showDialog<String>(
          context: context,
          builder: (BuildContext context) => AlertDialog(
                title: Text("Chybí datum expirace STK"),
                content: TextButton(
                    onPressed: () => Navigator.pop(context), child: Text("Ok")),
              ));
      return;
    }
    if (withInsurance && _expirationInsurance == null) {
      showDialog<String>(
          context: context,
          builder: (BuildContext context) => AlertDialog(
                title: Text("Chybí datum expirace pojištění"),
                content: TextButton(
                    onPressed: () => Navigator.pop(context), child: Text("Ok")),
              ));
      return;
    }
    showDialog<String>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
              title: Text("Přidávání vozidla"),
              content: CircularProgressIndicator(),
            ));
    final List<Insurance> insurances = [];
    if (withInsurance) {
      final Insurance insurance = Insurance(
          company: _insuranceCons[1].text,
          contractNumber: _insuranceCons[0].text,
          amount: int.parse(_insuranceCons[2].text),
          currency: currency!,
          expirationDate: _expirationInsurance!);
      insurances.add(insurance);
    }

    final Car car = Car(
      id: null,
      insurances: insurances,
      name: _carCons[0].text,
      spz: _carCons[1].text,
      brand: _carCons[2].text,
      model: _carCons[3].text,
      tyreType: _tyreType,
      tollExpiration: _highwayToll,
      stkExpirations: [_expirationSTK!],
      serviceBook: [],
    );
    UserProvider provider = context.read<UserProvider>();
    final docRef = carService.createItem(car);
    docRef.then((value) {
      provider.addNewCar(value.id);
      carService.updatePhoto(photo, value.id);
    });
    _clearControllers();
    widget.callback();
    Navigator.pop(context);
    showDialog<String>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
              title: Text("Vozidlo úspěšně přidáno"),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: const Text('Ok'),
                ),
              ],
            ));
  }

  void _clearControllers() {
    _carCons.map((e) => e.clear());
  }
}
