import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:pharmacy_mobile/tables/ref_categories.dart';
import 'package:pharmacy_mobile/tables/ref_generic_names.dart';
import 'package:pharmacy_mobile/tables/ref_manufactorers.dart';
import 'package:pharmacy_mobile/tables/ref_medicines.dart';
import 'package:pharmacy_mobile/tables/ref_types.dart';
import 'package:pharmacy_mobile/widgets/button_widget.dart';
import 'package:pharmacy_mobile/widgets/dropdown_widget.dart';
import 'package:pharmacy_mobile/widgets/dropdown_wrapper_widget.dart';
import 'package:pharmacy_mobile/widgets/form_border_widget.dart';
import 'package:pharmacy_mobile/widgets/input_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 AddMedicinePage extends StatefulWidget {
  const AddMedicinePage({super.key});

  @override
  State<AddMedicinePage> createState() => _AddMedicinePageState();
}

class _AddMedicinePageState extends State<AddMedicinePage> {
  final _formKey = GlobalKey<FormState>();
  final _refGenericNames = RefGenericNames();
  final _refCategories = RefCategories();
  final _refTypes = RefTypes();
  final _refManufactorer = RefManufactorers();
  final _refMedicines = RefMedicines();
  final _nameController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  bool _isLoading = false;

  late List _genericNameList = [];
  late String _selectedGeneric = '';
  late String _selectedCategory = '';
  late List _typeList = [];
  late String _selectedType = '';
  late List _manufactorerList = [];
  late String _selectedManufactorer = '';

  void _checkResult(List list, String name) {
    if (list.isEmpty) {
      if (mounted) {
        showNotification(context, 'Error: No $name Found', false);

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

  void _getGenerics() async {
    _genericNameList = await _refGenericNames.getList();
    _checkResult(_genericNameList, 'Generics');
  }

  void _getTypes() async {
    _typeList = await _refTypes.getList();
    _checkResult(_typeList, 'Types');
  }

  void _getManufactorer() async {
    _manufactorerList = await _refManufactorer.getList();
    _checkResult(_manufactorerList, 'Manufactorer');
  }

  void autoRun() async {
    if (await InternetConnectionChecker.instance.hasConnection) {
      _getGenerics();
      _getTypes();
      _getManufactorer();

      setState(() {});

      final sample = await _refMedicines.getList2();
      log(sample.toString());
    } else {
      if (mounted) {
        showNotification(context, 'Error: No Internet Connection', false);

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

  void _updateGeneric(dynamic generic) async {
    _selectedGeneric = generic;
    final catuuid = await _refGenericNames.getCategoryUUID(_selectedGeneric);
    final catname = await _refCategories.getName(catuuid);

    setState(() => _selectedCategory = catname);
  }

  void _updateType(dynamic type) {
    _selectedType = type;
  }

  void _updateManufactorer(dynamic manufactorer) {
    _selectedManufactorer = manufactorer;
  }

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

    try {
      if (await InternetConnectionChecker.instance.hasConnection) {
        final medName = _nameController.text;
        final medGenericUUID = await _refGenericNames.getUUID(_selectedGeneric);
        final medTypeUUID = await _refTypes.getUUID(_selectedType);
        final medManufactorerUUID = await _refManufactorer.getUUID(_selectedManufactorer);

        await _refMedicines.postMedicine(medName, medManufactorerUUID, medGenericUUID, medTypeUUID);
      } 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();
    _focusNode.dispose();

    _genericNameList = [];
    _selectedGeneric = '';
    _selectedCategory = '';
    _typeList = [];
    _selectedType = '';
    _manufactorerList = [];
    _selectedManufactorer = '';
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageBackgroundWidget(
        child: Center(
          child: Column(
            children: [
              const Gap(96),
              const TitleWidget(firstTextSize: 20, secondTextSize: 32),
              const Gap(32),
              const TextWidget(text: 'Add Medicine'),
              const Gap(16),
              FormBorderWidget(
                color: 'green',
                child: Form(
                    key: _formKey,
                    child: Center(
                      child: Column(
                        children: [
                          InputWidget(label: 'Name', controller: _nameController),
                          const Gap(16),
                          DropdownWrapperWidget(
                              list: _genericNameList,
                              text: 'Generics',
                              widget: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  DropDownWidget(
                                      label: 'Generic Name',
                                      list: _genericNameList,
                                      listTitle: 'generic_name',
                                      onChanged: _updateGeneric),
                                  const Gap(8),
                                  TextWidget(text: _selectedCategory, size: 18),
                                ],
                              )),
                          const Gap(16),
                          DropdownWrapperWidget(
                              list: _typeList,
                              text: 'Types',
                              widget: DropDownWidget(
                                  label: 'Type', list: _typeList, listTitle: 'type_name', onChanged: _updateType)),
                          const Gap(16),
                          DropdownWrapperWidget(
                              list: _manufactorerList,
                              text: 'Manufactorers',
                              widget: DropDownWidget(
                                  label: 'Manufactorer',
                                  list: _manufactorerList,
                                  listTitle: 'manufactorer_name',
                                  onChanged: _updateManufactorer)),
                          const Gap(32),
                          if (_isLoading)
                            const Center(child: CircularProgressIndicator(color: Colors.white))
                          else
                            ButtonWidget(text: 'Save Medicine', onPressed: _saveMedicine)
                        ],
                      ),
                    )),
              )
            ],
          ),
        ),
      ),
    );
  }
}
