import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:gap/gap.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:pharmacy_mobile/functions/barcode_scan_function.dart';
import 'package:pharmacy_mobile/functions/checkresult_function.dart';
import 'package:pharmacy_mobile/security/encryption.dart';
import 'package:pharmacy_mobile/tables/ref_medicines.dart';
import 'package:pharmacy_mobile/tables/stocks.dart';
import 'package:pharmacy_mobile/widgets/button_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_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:simple_barcode_scanner/simple_barcode_scanner.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 _medicineController = TextEditingController();
  final _stocks = Stocks();

  final bool _isLoading = false;

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

  // void autoRun() async {
  //   _medicineList = await _refMedicines.getList();
  // }

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

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

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

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

  // Future<bool> _getMedicines() async {
  //   late bool? result;
  //   _medicineList = await _refMedicines.getList();
  //   if (mounted) {
  //     result = await checkResult(context, _medicineList, 'Medicines');
  //     log(result.toString());
  //   }
  //   return result ?? false;
  // }

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

  void _saveStock() async {
    // final stockNameUUID = await _refMedicines.getUUID(_selectedMedicine);
    // final stockQuantity = _quantityController.text;
    // final stockExpiration = _dateController.text;

    // await _stocks.postStock(stockNameUUID, stockExpiration, stockQuantity);
    final aa = await encrypt('text');
    final bb =
        await decrypt('4cee2f33af6ebac8dcfdeeccdd6c73c4698ce25b0cb26249c571fafc8483b5a047baefc4d626fa56e027343d');
    log('encrypt: $aa');
    log('plain: $bb');
  }

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

    setState(() {
      _selectedMedicine = scannedBarcode;
    });
  }

  // Future<String> _getMedicineUsingBarcode(String barcode) async {
  //   final encryptedBarcode = await _refMedicines.getBarcode(barcode);
  //   final barcode = decrypt(encryptedBarcode);
  //   return barcode;
  // }

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

  @override
  void dispose() {
    _medicineList = [];
    _selectedMedicine = '';
    _quantityController.dispose();
    _dateController.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'),
              const Gap(16),
              FormBorderWidget2(
                color: 'green',
                child: Form(
                  key: _formKey,
                  child: Center(
                    child: DropdownWrapperMultiWidget(
                      list: _medicineList,
                      text: 'Data',
                      children: [
                        DropDownWidget(
                            label: 'Medicine Name',
                            list: _medicineList,
                            listTitle: 'medicine_name',
                            onChanged: _updateMedicine),
                        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: Row(
                                  children: [
                                    Icon(
                                      Icons.qr_code_scanner,
                                      color: Colors.white,
                                      size: 22,
                                    ),
                                    const Gap(8),
                                    TextWidget(
                                      text: 'Scan Barcode',
                                      size: 14,
                                      color: Colors.white,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        const Gap(16),
                        InputWidget(label: 'Quantity', controller: _quantityController),
                        const Gap(16),
                        DatePickerWidget(
                          label: 'Date Expiration',
                          controller: _dateController,
                          value: selectedDate,
                        ),
                        const Gap(32),
                        ButtonWidget(text: 'Add Stock', onPressed: _saveStock),
                        const Gap(16),
                        TextWidget(
                          text: barcode,
                          size: 14,
                        )
                      ],
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
