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/medicinelist/functions/cache_getmedicinelist.dart';
import 'package:pharmacy_mobile/functions/barcode_scan_function.dart';
import 'package:pharmacy_mobile/functions/checkresult_function.dart';
import 'package:pharmacy_mobile/tables/ref_medicines.dart';
import 'package:pharmacy_mobile/tables/stocks.dart';
import 'package:pharmacy_mobile/widgets/buttonwithprogress_widget.dart';
import 'package:pharmacy_mobile/widgets/datepicker_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/textbox_widget.dart';
import 'package:pharmacy_mobile/widgets/title_widget.dart';
import 'package:go_router/go_router.dart';

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

  @override
  State<AddStockPage> createState() => _AddStockPageState();
}

class _AddStockPageState extends State<AddStockPage> with WidgetsBindingObserver {
  final _formKey = GlobalKey<FormState>();
  final _refMedicines = RefMedicines();
  final _quantityController = TextEditingController();
  final _dateController = TextEditingController();
  final _priceController = TextEditingController();
  final _stocks = Stocks();

  late bool _isLoading = false;
  late List _medicineList = [];
  late String _selectedMedicine = '';
  late DateTime selectedDate = DateTime.now();
  late String barcode = '';

  final sampleBarcode = '8992185411017';

  void _getMedicines() async {
    _medicineList = await _refMedicines.getList();

    setState(() {
      checkResult(context, _medicineList, 'Medicines');
    });
  }

  Future<bool> _getMedicinesCache() async {
    final cache = await cacheGetMedicineList(context);

    if (cache.isNotEmpty) {
      _medicineList = cache;

      return true;
    } else {
      return false;
    }
  }

  void autoRun() async {
    final medicines = await _getMedicinesCache();

    if (!medicines) {
      if (await InternetConnectionChecker.instance.hasConnection) {
        _getMedicines();
      } else {
        if (mounted) {
          showNotification(context, 'Error: No Internet Connection', false);

          WidgetsBinding.instance.addPostFrameCallback((_) {
            context.pop();
          });
        }
      }
    } else {
      setState(() {});
    }
  }

  void _updateMedicine(dynamic medicine) {
    _selectedMedicine = medicine;
  }

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

    try {
      if (await InternetConnectionChecker.instance.hasConnection) {
        final stockNameUUID = await _refMedicines.getUUID(_selectedMedicine);
        final stockQuantity = _quantityController.text;
        final stockExpiration = _dateController.text;
        final price = _priceController.text;

        final success = await _stocks.postStock(stockNameUUID, stockExpiration, stockQuantity, price);
        if (success) {
          if (mounted) {
            showNotification(context, 'Stock added successfully', true);
            setState(() => _isLoading = false);
            context.pop();
          }
        } else {
          if (mounted) {
            showNotification(context, 'Error: Stock not added', false);
          }
        }
      } else {
        if (mounted) {
          showNotification(context, 'Error: No Internet Connection', false);
        }
      }
    } catch (e) {
      if (mounted) {
        showNotification(context, 'Error: $e', false);
      }
    } finally {
      setState(() => _isLoading = false);
    }
  }

  Future<void> _scanBarcode() async {
    final scannedBarcode = await barcodeScan(context);
    final meds = await _getMedicineUsingBarcode(scannedBarcode);

    setState(() {
      barcode = meds;
    });
  }

  Future<String> _getMedicineUsingBarcode(String barcode) async {
    final medicine = await _refMedicines.getNameUsingBarcode(barcode);
    return medicine;
  }

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

  @override
  void dispose() {
    _medicineList = [];
    _selectedMedicine = '';
    _quantityController.dispose();
    _dateController.dispose();
    _priceController.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: 'Add Stock',
                title: true,
              ),
              const Gap(16),
              FormBorderWidget2(
                color: 'green',
                child: Form(
                  key: _formKey,
                  child: DropdownWrapperMultiWidget(
                    list: _medicineList,
                    text: 'Data',
                    children: [
                      if (barcode.isEmpty)
                        DropDownWidget(
                          label: 'Medicine Name',
                          list: _medicineList,
                          listTitle: 'medicine_name',
                          onChanged: _updateMedicine,
                        )
                      else
                        TextboxWidget(text: barcode),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          GestureDetector(
                            onTap: _scanBarcode,
                            child: Container(
                              padding: const EdgeInsets.only(top: 8),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(20),
                                // color: const Color.fromARGB(0, 36, 18, 58),
                                // boxShadow: [
                                //   BoxShadow(
                                //     color: Colors.black26,
                                //     blurRadius: 5.0,
                                //     offset: Offset(0, 2),
                                //   ),
                                // ],
                              ),
                              child: const Row(
                                children: [
                                  Icon(
                                    Icons.qr_code_scanner,
                                    color: Colors.white,
                                    size: 22,
                                  ),
                                  Gap(8),
                                  TextWidget(
                                    text: 'Scan Barcode',
                                    size: 14,
                                    color: Colors.white,
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                      const Gap(16),
                      InputFormWidget(label: 'Quantity', controller: _quantityController),
                      const Gap(16),
                      DatePickerWidget(
                        label: 'Date Expiration',
                        controller: _dateController,
                        value: selectedDate,
                      ),
                      const Gap(16),
                      InputFormWidget(label: 'Price', controller: _priceController),
                      const Gap(32),
                      ButtonWithProgressWidget(
                          trigger: _isLoading, progressText: 'Adding Stock', buttonText: 'Save', onPressed: _saveStock)
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
