import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:satu/core/models/dialog_models.dart';
import 'package:satu/core/models/dictionary/category/category_response.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/routes/route_names.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_field.dart';
import 'package:satu/widgets/fields/line_tile.dart';

class CategoryEdit extends StatefulWidget {
  const CategoryEdit({
    required this.category,
    Key? key,
  }) : super(key: key);
  final CategoryResponse category;

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

class _CategoryEditState extends State<CategoryEdit> {
  final NavigatorService _navigatorService = locator<NavigatorService>();
  final DictionaryService _dictionaryService = locator<DictionaryService>();
  final DialogService _dialogService = locator<DialogService>();
  final Logger log = getLogger('_CategoryEditState');
  late TextEditingController _controller;

  String? parentCategoryName;
  int? parentCategoryId;

  @override
  void initState() {
    super.initState();
    if (widget.category.parentId != null) {
      parentCategoryId = widget.category.parentId;
      parentCategoryName = widget.category.parentId.toString();
    }
    _controller = TextEditingController(text: widget.category.name);
  }

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

  void save() async {
    CategoryResponse category = widget.category;
    category.name = _controller.text;
    category.parentId = parentCategoryId;
    String? message = await _dictionaryService.saveCategory(category);
    if (message != null) {
      _dialogService.showDialog(description: message);
    } else {
      _navigatorService.pop(true);
    }
  }

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



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: ProductsAppBar(
        title: widget.category.id == null
            ? 'Создание категории'
            : 'Редактирование категории',
      ),
      body: SingleChildScrollView(
        physics: const BouncingScrollPhysics(),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            verticalSpaceSmall,
            LineTile(
              parentCategoryName ?? 'Корневая категория',
              onTap: selectCategory,
              labelText: 'Родительская категория',
            ),
            verticalSpaceSmall,
            InputField(
              controller: _controller,
              labelText: 'Наименование',
              placeholder: 'Введите наименование категории',
            ),
            Padding(
              padding:
                  const EdgeInsets.symmetric(horizontal: 45.0, vertical: 20.0),
              child: BusyButton(title: 'СОХРАНИТЬ', onPressed: () {
                save();
              }),
            ),
            if (widget.category.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,
                ),
              ),
          ],
        ),
      ),
    );
  }

  Future<void> selectCategory() async {
    final dynamic result =
        await _navigatorService.push(categorySelectViewRoute);
    CategoryResponse? category = result as CategoryResponse?;
    setState(() {
      parentCategoryId = category?.id;
      parentCategoryName = category?.name;
    });

  }
}
