import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:satu/core/models/dialog_models.dart';
import 'package:satu/core/models/dictionary/contragent/contragent_response_entity.dart';
import 'package:satu/core/services/dialog_service.dart';
import 'package:satu/core/services/dictionary_service.dart';
import 'package:satu/core/services/navigator_service.dart';
import 'package:satu/core/utils/locator.dart';
import 'package:satu/core/utils/logger.dart';
import 'package:satu/shared/ui_helpers.dart';
import 'package:satu/widgets/bar/products_app_bar.dart';
import 'package:satu/widgets/buttons/busy_button.dart';
import 'package:satu/widgets/fields/input_checkbox.dart';
import 'package:satu/widgets/fields/input_field.dart';

class ContragentEdit extends StatefulWidget {
  const ContragentEdit({
    required this.contragent,
    Key? key,
  }) : super(key: key);
  final ContragentResponseEntity contragent;

  @override
  _ContragentEditState createState() => _ContragentEditState();
}

class _ContragentEditState extends State<ContragentEdit> {
  final NavigatorService _navigatorService = locator<NavigatorService>();
  final DictionaryService _dictionaryService = locator<DictionaryService>();
  final DialogService _dialogService = locator<DialogService>();
  final Logger log = getLogger('_GoodEditState');
  late TextEditingController _controllerName;
  late TextEditingController _controllerBinIin;
  late TextEditingController _controllerPhone;
  late TextEditingController _controllerMail;
  late bool _isNds;
  late bool _isResident;

  String parentCategoryName = '';
  int? parentCategoryId;

  @override
  void initState() {
    super.initState();
    _controllerName = TextEditingController(text: widget.contragent.name ?? '');
    _controllerBinIin =
        TextEditingController(text: widget.contragent.biniin ?? '');
    _controllerPhone =
        TextEditingController(text: widget.contragent.phone ?? '');
    _controllerMail =
        TextEditingController(text: widget.contragent.email ?? '');
    _isNds = widget.contragent.nds == 1;
    _isResident = widget.contragent.resident == 1;
  }

  @override
  void dispose() {
    _controllerName.dispose();
    super.dispose();
  }

  void save() async {
    ContragentResponseEntity contragent = widget.contragent;
    contragent.name = _controllerName.text;
    contragent.biniin = _controllerBinIin.text;
    contragent.phone = _controllerPhone.text;
    contragent.email = _controllerMail.text;
    contragent.nds = _isNds ? 1 : 0;
    contragent.resident = _isResident ? 1 : 0;
    String? message = await _dictionaryService.saveContragent(contragent);
    if (message != null) {
      _dialogService.showDialog(description: message);
    } else {
      _navigatorService.pop(true);
    }
  }

  void delete() async {
    ContragentResponseEntity contragent = widget.contragent;
    String? message = await _dictionaryService.deleteContragent(contragent);
    if (message != null) {
      _dialogService.showDialog(description: message);
    } else {
      _navigatorService.pop(true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: ProductsAppBar(
        title: widget.contragent.id == null
            ? 'Добавление контрагента'
            : 'Редактирование контрагента',
      ),
      body: SingleChildScrollView(
        physics: const BouncingScrollPhysics(),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            verticalSpaceSmall,
            InputField(
              controller: _controllerName,
              labelText: 'Наименование',
              placeholder: 'Введите наименование контрагента',
              enterPressed: (){
                FocusManager.instance.primaryFocus?.unfocus();
              },
              textInputAction: TextInputAction.done,
            ),
            InputField(
              controller: _controllerBinIin,
              labelText: 'БИН/ИИН>',
              placeholder: 'Введите БИН/ИИН',
              enterPressed: (){
                FocusManager.instance.primaryFocus?.unfocus();
              },
              textInputAction: TextInputAction.done,
            ),
            InputField(
              controller: _controllerPhone,
              labelText: 'Телефон',
              placeholder: 'Введите номер телефона',
              enterPressed: (){
                FocusManager.instance.primaryFocus?.unfocus();
              },
              textInputAction: TextInputAction.done,
            ),
            InputField(
              controller: _controllerMail,
              labelText: 'E-mail"',
              placeholder: 'Введите электронную почту',
              enterPressed: (){
                FocusManager.instance.primaryFocus?.unfocus();
              },
              textInputAction: TextInputAction.done,
            ),
            InputCheckBox('НДС', value: _isNds, labelText: 'Плательщик НДС',
                onChanged: (value) {
              setState(() {
                _isNds = value ?? false;
              });
            }),
            InputCheckBox('', value: _isResident, labelText: 'Резидент',
                onChanged: (value) {
              setState(() {
                _isResident = value ?? false;
              });
            }),
            Padding(
              padding:
                  const EdgeInsets.symmetric(horizontal: 45.0, vertical: 20.0),
              child: BusyButton(
                  title: 'СОХРАНИТЬ',
                  onPressed: () {
                    save();
                  }),
            ),
            if (widget.contragent.id != null)
              Padding(
                padding: const EdgeInsets.symmetric(
                    horizontal: 45.0, vertical: 20.0),
                child: BusyButton(
                  title: 'УДАЛИТЬ',
                  onPressed: () async {
                    DialogResponse response =
                        await _dialogService.showConfirmationDialog(
                            title: 'Внимание',
                            description:
                                'Вы уверены, что хотите удалить категорию?',
                            confirmationTitle: 'Удалить',
                            cancelTitle: 'Отмена');

                    if (response.confirmed) {
                      delete();
                    }
                  },
                  isDanger: true,
                ),
              ),
          ],
        ),
      ),
    );
  }
}
