import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:image_picker/image_picker.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:pharmacy_mobile/blocs/caches/distributorlist/functions/cache_getdistributorlist.dart';
import 'package:pharmacy_mobile/blocs/caches/genericlist/functions/cache_getgenericlist.dart';
import 'package:pharmacy_mobile/blocs/caches/manufacturerlist/functions/cache_getmanufacturerlist.dart';
import 'package:pharmacy_mobile/blocs/caches/supplierlist/functions/cache_getsupplierlist.dart';
import 'package:pharmacy_mobile/blocs/caches/typelist/functions/cache_gettypelist.dart';
import 'package:pharmacy_mobile/functions/barcode_scan_function.dart';
import 'package:pharmacy_mobile/functions/checkresult_function.dart';
import 'package:pharmacy_mobile/tables/ref_categories.dart';
import 'package:pharmacy_mobile/tables/ref_distributors.dart';
import 'package:pharmacy_mobile/tables/ref_generic_names.dart';
import 'package:pharmacy_mobile/tables/ref_manufacturers.dart';
import 'package:pharmacy_mobile/tables/ref_medicines.dart';
import 'package:pharmacy_mobile/tables/ref_suppliers.dart';
import 'package:pharmacy_mobile/tables/ref_types.dart';
import 'package:pharmacy_mobile/tables/storage.dart';
import 'package:pharmacy_mobile/widgets/button_widget.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/image_widget.dart';
import 'package:pharmacy_mobile/widgets/input_form_widget.dart';
import 'package:pharmacy_mobile/widgets/page_background_widget.dart';
import 'package:pharmacy_mobile/widgets/scanbarcode_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:uuid/uuid.dart';
import 'package:flutter_image_compress/flutter_image_compress.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 _refManufacturer = RefManufacturers();
  final _refMedicines = RefMedicines();
  final _refDistributors = RefDistributors();
  final _refSuppliers = RefSuppliers();
  final _storage = Storage();
  final _nameController = TextEditingController();
  final _barcodeController = TextEditingController();

  late bool _isLoading = false;
  late List _genericNameList = [];
  late String _selectedGeneric = '';
  late String _selectedCategory = '';
  late List _typeList = [];
  late String _selectedType = '';
  late List _manufacturerList = [];
  late List _distributorList = [];
  late List _supplierList = [];
  late String _selectedManufacturer = '';
  late String _selectedDistributor = '';
  late String _selectedSupplier = '';
  late String uuid = '';
  late bool imageUploaded = false;
  late String imageUrl = '';
  late bool uploaded = false;

  Future<void> _getGenerics() async {
    _genericNameList = await _refGenericNames.getList();

    setState(() {
      checkResult(context, _genericNameList, 'Generics');
    });
  }

  Future<bool> _getGenericsCache() async {
    final cache = await cacheGetGenericList(context);

    if (cache.isNotEmpty) {
      _genericNameList = cache;

      return true;
    } else {
      return false;
    }
  }

  Future<void> _getTypes() async {
    _typeList = await _refTypes.getList();
    setState(() {
      checkResult(context, _typeList, 'Types');
    });
  }

  Future<bool> _getTypesCache() async {
    final cache = await cacheGetTypeList(context);

    if (cache.isNotEmpty) {
      _typeList = cache;

      return true;
    } else {
      return false;
    }
  }

  Future<void> _getManufacturers() async {
    _manufacturerList = await _refManufacturer.getList();
    setState(() {
      checkResult(context, _manufacturerList, 'Manufacturer');
    });
  }

  Future<void> _getDistributors() async {
    _distributorList = await _refDistributors.getList();
    setState(() {
      checkResult(context, _distributorList, 'Distributor');
    });
  }

  Future<void> _getSuppliers() async {
    _supplierList = await _refSuppliers.getList();
    setState(() {
      checkResult(context, _supplierList, 'Supplier');
    });
  }

  Future<bool> _getManufacturersCache() async {
    final cache = await cacheGetManufacturerList(context);

    if (cache.isNotEmpty) {
      _manufacturerList = cache;

      return true;
    } else {
      return false;
    }
  }

  Future<bool> _getDistributorsCache() async {
    final cache = await cacheGetDistributorList(context);

    if (cache.isNotEmpty) {
      _distributorList = cache;

      return true;
    } else {
      return false;
    }
  }

  Future<bool> _getSuppliersCache() async {
    final cache = await cacheGetSupplierList(context);

    if (cache.isNotEmpty) {
      _supplierList = cache;

      return true;
    } else {
      return false;
    }
  }

  void autoRun() async {
    final generics = await _getGenericsCache();
    final types = await _getTypesCache();
    final manufacturers = await _getManufacturersCache();
    final distributors = await _getDistributorsCache();
    final suppliers = await _getSuppliersCache();

    print('generics: $generics');
    print('types: $types');
    print('manufacturers: $manufacturers');
    print('distributors: $distributors');
    print('suppliers: $suppliers');

    if (!generics || !types || !manufacturers || !distributors || !suppliers) {
      if (await InternetConnectionChecker.instance.hasConnection) {
        await _getGenerics();
        await _getTypes();
        await _getManufacturers();
        await _getDistributors();
        await _getSuppliers();
      } else {
        if (mounted) {
          showNotification(context, 'Error: No Internet Connection', false);

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

    // if (await InternetConnectionChecker.instance.hasConnection) {
    //   await _getGenerics();
    //   await _getTypes();
    //   await _getManufacturers();
    //   await _getDistributors();
    //   await _getSuppliers();
    // } else {
    //   if (mounted) {
    //     showNotification(context, 'Error: No Internet Connection', false);

    //     WidgetsBinding.instance.addPostFrameCallback((_) {
    //       if (mounted) {
    //         context.pop();
    //       }
    //     });
    //   }
    // }
  }

  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 _updateManufacturer(dynamic manufacturer) {
    _selectedManufacturer = manufacturer;
  }

  void _updateDistributor(dynamic distributor) {
    _selectedDistributor = distributor;
  }

  void _updateSupplier(dynamic supplier) {
    _selectedSupplier = supplier;
  }

  Future<void> _scanBarcode() async {
    // String? barcode = await SimpleBarcodeScanner.scanBarcode(
    //   context,
    //   // barcodeAppBar: const BarcodeAppBar(
    //   //     // appBarTitle: 'Test',
    //   //     // centerTitle: false,
    //   //     // enableBackButton: false,
    //   //     // backButtonIcon: Icon(Icons.arrow_back_ios),
    //   //     ),
    //   // isShowFlashIcon: true,
    //   delayMillis: 2000,
    //   scanType: ScanType.barcode,
    //   cameraFace: CameraFace.back,
    // );
    _barcodeController.text = await barcodeScan(context);
  }

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

    try {
      // final String encrpytedBarcode = await encrypt(_barcodeController.text);
      final String encrpytedBarcode = _barcodeController.text;

      if (await InternetConnectionChecker.instance.hasConnection) {
        final medName = _nameController.text;
        final medGenericUUID = await _refGenericNames.getUUID(_selectedGeneric);
        final medTypeUUID = await _refTypes.getUUID(_selectedType);
        final medManufacturerUUID = await _refManufacturer.getUUID(_selectedManufacturer);
        final medDistributorUUID = await _refDistributors.getUUID(_selectedDistributor);
        final medSupplierUUID = await _refSuppliers.getUUID(_selectedSupplier);

        final posted = await _refMedicines.postMedicine(uuid, medName, medManufacturerUUID, medGenericUUID, medTypeUUID,
            encrpytedBarcode, medDistributorUUID, medSupplierUUID);

        if (posted) {
          if (mounted) {
            showNotification(context, 'Medicine Added Successfully', true);
            setState(() => _isLoading = false);
            context.pop();
          }
        } else {
          if (mounted) {
            showNotification(context, 'Error: Medicine 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);
    }
  }

  void _addImage() async {
    final imageName = Uuid().v4();

    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery, imageQuality: 100);
    const storageName = 'ref_medicines_images';

    final imageBytes = await image!.readAsBytes();
    final webpImage = await _webpConvert(imageBytes);

    uuid = imageName;

    if (mounted) {
      uploaded = await _storage.uploadImage(context, storageName, webpImage, '$imageName.webp');
    }

    if (!uploaded) {
      if (mounted) {
        showNotification(context, 'Image Upload failed, try again.', false);
        return;
      }
    }

    if (imageName.isNotEmpty) {
      final url = await _getImageUrl('$imageName.webp');
      setState(() {
        imageUrl = url;
      });
    }
  }

  Future<Uint8List> _webpConvert(Uint8List file) async {
    final result = await FlutterImageCompress.compressWithList(
      file,
      quality: 70,
      rotate: 0,
      keepExif: false,
      format: CompressFormat.webp,
    );
    return result;
  }

  Future<String> _getImageUrl(String imageName) async {
    final image = await _storage.getImageURL('ref_medicines_images', imageName);
    return image;
  }

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

  @override
  void dispose() {
    _nameController.dispose();
    _barcodeController.dispose();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: PageBackgroundWidget(
            height: MediaQuery.of(context).size.height + 600,
            child: Center(
                child: Column(children: [
              const Gap(96),
              const TitleWidget(
                firstTextSize: 14,
                secondTextSize: 24,
                logoSize: 90,
              ),
              const Gap(32),
              const TextWidget(
                text: 'Add Medicine',
                title: true,
              ),
              const Gap(16),
              FormBorderWidget2(
                  color: 'green',
                  child: Form(
                      key: _formKey,
                      child: DropdownWrapperMultiWidget(list: _supplierList, text: 'Data', children: [
                        Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                          InputFormWidget(label: 'Name', controller: _nameController),
                          const Gap(16),
                          DropDownWidget(
                            label: 'Generic Name',
                            list: _genericNameList,
                            listTitle: 'generic_name',
                            onChanged: _updateGeneric,
                          ),
                          const Gap(8),
                          Padding(
                            padding: const EdgeInsets.only(left: 12),
                            child: TextWidget(text: _selectedCategory, size: 18),
                          ),
                          const Gap(16),
                          DropDownWidget(
                            label: 'Type',
                            list: _typeList,
                            listTitle: 'type_name',
                            onChanged: _updateType,
                          ),
                          const Gap(16),
                          DropDownWidget(
                            label: 'Manufacturer',
                            list: _manufacturerList,
                            listTitle: 'manufacturer_name',
                            onChanged: _updateManufacturer,
                          ),
                          const Gap(16),
                          DropDownWidget(
                            label: 'Distributor',
                            list: _distributorList,
                            listTitle: 'distributor_name',
                            onChanged: _updateDistributor,
                          ),
                          const Gap(16),
                          DropDownWidget(
                            label: 'Supplier',
                            list: _supplierList,
                            listTitle: 'supplier_name',
                            onChanged: _updateSupplier,
                          ),
                          const Gap(16),
                          InputFormWidget(label: 'Barcode', controller: _barcodeController),
                          ScanbarcodeWidget(onTap: _scanBarcode),
                          const Gap(16),
                          if (imageUrl.isNotEmpty)
                            Center(
                                child: ClipRRect(
                                    borderRadius: BorderRadius.circular(12), // Add your desired border radius here
                                    child: ImageWidget(
                                      imagePath: imageUrl,
                                      size: 250,
                                      measureByHeight: false,
                                      network: true,
                                    ))
                                // Image.network(imageUrl, fit: BoxFit.cover, width: 250, height: 250)),
                                )
                          else
                            ButtonWidget(
                              text: 'Add Image',
                              onPressed: _addImage,
                              outline: true,
                            ),
                          const Gap(32),
                          // if (_isLoading)
                          //   const Center(child: CircularProgressIndicator(color: Colors.white))
                          // else
                          //   ButtonWidget(text: 'Save Medicine', onPressed: _saveMedicine)
                          if (uploaded)
                            ButtonWithProgressWidget(
                                trigger: _isLoading,
                                progressText: 'Adding Medicine',
                                buttonText: 'Save',
                                onPressed: _saveMedicine)
                        ])
                      ])))
            ]))));
  }
}
