import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:pharmacy_mobile/blocs/caches/stocklist/functions/cache_setstocklist.dart';
import 'package:pharmacy_mobile/functions/checkresult_function.dart';
import 'package:pharmacy_mobile/functions/getlist_cache_function.dart';
import 'package:pharmacy_mobile/tables/stocks.dart';
import 'package:pharmacy_mobile/widgets/button_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';
import 'package:pharmacy_mobile/widgets/warning_widget.dart';

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

  @override
  State<DeleteStockPage> createState() => _DeleteStockPageState();
}

class _DeleteStockPageState extends State<DeleteStockPage> {
  final _formKey = GlobalKey<FormState>();
  final _stocks = Stocks();
  final _quantityController = TextEditingController();

  late List _stockList = [];
  late String _selectedStock = '';
  late bool _aboveQuantity = false;
  late bool _noStock = false;
  late double _serverQuantity = 0;
  late String _selectedUUID = '';

  void _getStocks() async {
    _stockList = await _stocks.getList();

    if (mounted) {
      final result = await checkResult(context, _stockList, 'Generics');
      if (result) {
        if (mounted) {
          context.pop();
        }
      } else {
        setState(() => {});
      }
    }
  }

  void _updateStock(dynamic stock) {
    _selectedStock = stock;
    _getQuantity(_selectedStock);
  }

  Future<void> _getStockListCache() async {
    final stockList = await _stocks.getList();

    if (stockList.isNotEmpty) {
      // ignore: use_build_context_synchronously
      final setCache = await cacheSetStockList(context, stockList);
      if (!setCache) {}
    }
  }

  void _saveDeletion() async {
    final newQuantity = _serverQuantity - double.parse(_quantityController.text);
    final newQuantityFixed = newQuantity.toStringAsFixed(0);

    try {
      _stocks.updateStock(_selectedUUID, 'quantity', newQuantityFixed);
      await _getStockListCache();

      if (mounted) {
        showNotification(context, '$_selectedStock updated', true);

        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) context.pop();
        });
      }
    } catch (e) {
      if (mounted) {
        showNotification(context, 'Error: $e', false);
      }
    }
  }

  void _getQuantity(String name) async {
    final uuid = await _stocks.getUUID(name);
    final quantity = await _stocks.getQuantity(uuid);
    _serverQuantity = double.parse(quantity);
    _selectedUUID = uuid;
  }

  void _setQuantity(dynamic quantity) async {
    if (_selectedStock.isEmpty) {
      _noStock = true;
      setState(() {});
    } else {
      _noStock = false;

      if (double.parse(quantity) > _serverQuantity) {
        _aboveQuantity = true;
        setState(() {});
      } else {
        _aboveQuantity = false;
        setState(() {});
      }
    }
  }

  void autoRun() async {
    final cache = await getListCache(context, 'stock');

    if (cache.isEmpty) {
      if (await InternetConnectionChecker.instance.hasConnection) {
        _getStocks();
      } else {
        // ignore: use_build_context_synchronously
        showNotification(context, 'Error: No Internet Connection', false);
      }
    } else {
      setState(() {
        _stockList = cache;
      });
    }
  }

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

  @override
  void dispose() {
    _stockList = [];
    _selectedStock = '';
    _quantityController.dispose();
    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: 'Remove Stock',
        title: true,
      ),
      const Gap(16),
      FormBorderWidget2(
          color: 'red',
          child: Form(
              key: _formKey,
              child: Column(
                children: [
                  DropdownWrapperMultiWidget(list: _stockList, text: 'Stocks', children: [
                    DropDownWidget(
                      label: 'Stocks',
                      list: _stockList,
                      listTitle: 'medicine_name',
                      onChanged: _updateStock,
                      // value: _selectedStock,
                    ),
                    const Gap(16),
                    InputFormWidget(label: 'Quantity', controller: _quantityController, onChanged: _setQuantity),
                    const Gap(32),
                    if (_noStock)
                      const WarningWidget(
                        text: 'Removing Disabled',
                        warning: 'Stock is empty',
                      )
                    else if (_aboveQuantity)
                      const WarningWidget(
                        text: 'Removing Disabled',
                        warning: 'Quantity is above stocked',
                      )
                    else
                      ButtonWidget(text: 'Remove', onPressed: _saveDeletion)
                  ])
                ],
              )))
    ]))));
  }
}
