import 'package:gap/gap.dart';
import 'package:flutter/material.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:pharmacy_mobile/blocs/caches/categorylist/functions/cache_getcategorylist.dart';
import 'package:pharmacy_mobile/functions/checkexisting_function.dart';
import 'package:pharmacy_mobile/tables/ref_categories.dart';
import 'package:pharmacy_mobile/tables/ref_generic_names.dart';
import 'package:pharmacy_mobile/widgets/buttonwithprogress_widget.dart';
import 'package:pharmacy_mobile/widgets/dropdown_widget.dart';
import 'package:pharmacy_mobile/widgets/dropdown_wrappermulti_widget.dart';
import 'package:pharmacy_mobile/widgets/form_border_widget2.dart';
import 'package:pharmacy_mobile/widgets/input_form_widget.dart';
import 'package:pharmacy_mobile/widgets/page_background_widget.dart';
import 'package:pharmacy_mobile/widgets/snackbar_widget.dart';
import 'package:pharmacy_mobile/widgets/text_widget.dart';
import 'package:pharmacy_mobile/widgets/title_widget.dart';
import 'package:go_router/go_router.dart';

class AddGenericsPage extends StatefulWidget {
  const AddGenericsPage({super.key});

  @override
  State<AddGenericsPage> createState() => _AddGenericsPageState();
}

class _AddGenericsPageState extends State<AddGenericsPage> {
  final _refCategories = RefCategories();
  final _refGenericNames = RefGenericNames();
  final _nameController = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  late bool _isLoading = false;
  // late final List _categoryListCache = [];

  late List _categoryList = [];
  late String _selectedCategory = '';
  late String _categoryUUID = '';

  void _getList() async {
    _categoryList = await _refCategories.getList();

    if (_categoryList.isEmpty) {
      if (mounted) {
        showNotification(context, 'Error: No Categories Found', false);

        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            context.pop();
          }
        });
      }
    } else {
      setState(() => {});
    }
  }

  Future<void> _getCategory() async {
    final categoryListCache = await cacheGetCategoryList(context);

    if (categoryListCache.isNotEmpty) {
      setState(() {
        _categoryList = categoryListCache;
      });
    } else {
      if (await InternetConnectionChecker.instance.hasConnection) {
        _getList();
      } else {
        if (mounted) {
          showNotification(context, 'Error: No Internet Connection', false);

          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (mounted) {
              context.push('/main');
            }
          });
        }
      }
    }
  }

  void autoRun() async {
    _getCategory();
  }

  void _updateCategory(dynamic category) {
    _selectedCategory = category;
  }

  void _saveGeneric() async {
    setState(() => _isLoading = true);

    try {
      if (await InternetConnectionChecker.instance.hasConnection) {
        final existing = await checkExisting(_refGenericNames, _nameController);

        if (existing && mounted) {
          showNotification(context, 'Generic Name already existing', false);
          return;
        }

        _categoryUUID = await _refCategories.getUUID(_selectedCategory);

        final post = await _refGenericNames.postGeneric(_nameController.text, _categoryUUID);

        if (post && mounted) {
          showNotification(context, 'Generic name saved', true);

          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (mounted) {
              context.push('/main');
            }
          });
        } else {
          if (mounted) {
            showNotification(context, 'Generic name not saved', false);
          }
        }
      } else {
        if (mounted) {
          showNotification(context, 'Error: No Internet Connection', false);
        }
      }
    } catch (e) {
      if (mounted) {
        showNotification(context, 'Error: $e', false);
      }
    } finally {
      setState(() => _isLoading = false);
    }
  }

  @override
  void initState() {
    autoRun();
    super.initState();
  }

  @override
  void dispose() {
    _nameController.dispose();
    _categoryList = [];
    _selectedCategory = '';
    _categoryUUID = '';
    _isLoading = false;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageBackgroundWidget(
        child: Center(
            child: Column(
          children: [
            const Gap(96),
            const TitleWidget(
              firstTextSize: 14,
              secondTextSize: 24,
              logoSize: 90,
            ),
            const Gap(32),
            const TextWidget(
              text: 'Add Generics',
              title: true,
            ),
            const Gap(16),
            FormBorderWidget2(
              color: 'blue',
              child: Form(
                  key: _formKey,
                  child: DropdownWrapperMultiWidget(list: _categoryList, text: 'List', children: [
                    Column(
                      children: [
                        InputFormWidget(label: 'Name', controller: _nameController),
                        const Gap(16),
                        DropDownWidget(
                          label: 'Category',
                          list: _categoryList,
                          listTitle: 'category_name',
                          onChanged: _updateCategory,
                        ),
                        const Gap(32),
                        ButtonWithProgressWidget(
                            trigger: _isLoading,
                            progressText: 'Adding Generics',
                            buttonText: 'Save',
                            onPressed: _saveGeneric)
                      ],
                    ),
                  ])),
            )
          ],
        )),
      ),
    );
  }
}
