import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:gap/gap.dart';
import 'package:go_router/go_router.dart';
import 'package:pharmacy_mobile/auth/auth_service.dart';
import 'package:pharmacy_mobile/blocs/caches/categorylist/functions/cache_setcategorylist.dart';
import 'package:pharmacy_mobile/blocs/caches/distributorlist/functions/cache_setdistributorlist.dart';
import 'package:pharmacy_mobile/blocs/caches/genericlist/functions/cache_setgenericlist.dart';
import 'package:pharmacy_mobile/blocs/caches/manufacturerlist/functions/cache_setmanufacturerlist.dart';
import 'package:pharmacy_mobile/blocs/caches/medicinelist/functions/cache_setmedicinelist.dart';
import 'package:pharmacy_mobile/blocs/caches/stocklist/functions/cache_setstocklist.dart';
import 'package:pharmacy_mobile/blocs/caches/supplierlist/functions/cache_setsupplierlist.dart';
import 'package:pharmacy_mobile/blocs/caches/typelist/functions/cache_settypelist.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/stocks.dart';
import 'package:pharmacy_mobile/widgets/buttonwithprogress_widget.dart';
import 'package:pharmacy_mobile/widgets/menu_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:supabase_flutter/supabase_flutter.dart';

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

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  final _authService = AuthService();
  final _refCategories = RefCategories();
  final _refGenericNames = RefGenericNames();
  final _refTypes = RefTypes();
  final _refManufacturers = RefManufacturers();
  final _refMedicines = RefMedicines();
  final _stocks = Stocks();
  final _refDistributors = RefDistributors();
  final _refSuppliers = RefSuppliers();

  late bool _isLoading = false;

  void signOut() async {
    try {
      setState(() {
        _isLoading = true;
      });
      // ignore: use_build_context_synchronously
      await _authService.signOut().then((_) => {context.go('/'), showNotification(context, 'Logged Out', true)});
    } catch (e) {
      if (e is AuthException) {
        final errorMessage = e.message;

        if (mounted) {
          showNotification(context, 'Error: $errorMessage', false);
        }
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _getCategoryListCache() async {
    final categoryList = await _refCategories.getList();

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

  Future<void> _getGenericListCache() async {
    final genericNameList = await _refGenericNames.getList();

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

  Future<void> _getTypeListCache() async {
    final typeList = await _refTypes.getList();

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

  Future<void> _getManufacturerListCache() async {
    final manufacturerList = await _refManufacturers.getList();

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

  Future<void> _getMedicineListCache() async {
    final medicineList = await _refMedicines.getList();

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

  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) {}
    }
  }

  Future<void> _getDistributorListCache() async {
    final distributorList = await _refDistributors.getList();

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

  Future<void> _getSupplierListCache() async {
    final supplierList = await _refSuppliers.getList();

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

  void autoRun() async {
    await _getCategoryListCache();
    await _getGenericListCache();
    await _getTypeListCache();
    await _getManufacturerListCache();
    await _getMedicineListCache();
    await _getStockListCache();
    await _getDistributorListCache();
    await _getSupplierListCache();
  }

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

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: false,
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          body: SingleChildScrollView(
            child: PageBackgroundWidget(
              height: MediaQuery.of(context).size.height + 600,
              page: 'menu',
              child: Center(
                child: Column(
                  children: [
                    const Gap(96),
                    const TitleWidget(
                      firstTextSize: 14,
                      secondTextSize: 24,
                      logoSize: 90,
                    ),
                    const Gap(32),
                    const TextWidget(
                      text: 'Menu',
                      title: true,
                    ),
                    const Gap(16),
                    MenuWidget(
                      icon: FontAwesomeIcons.circlePlus,
                      text: 'Add Manufacturer',
                      description: 'Register manufacturer to the list',
                      onPressed: () => {context.push('/addmanufactorer')},
                      color: 'blue',
                    ),
                    const Gap(16),
                    MenuWidget(
                      icon: FontAwesomeIcons.circlePlus,
                      text: 'Add Distributor',
                      description: 'Register manufacturer to the list',
                      onPressed: () => {context.push('/adddistributor')},
                      color: 'blue',
                    ),
                    const Gap(16),
                    MenuWidget(
                      icon: FontAwesomeIcons.circlePlus,
                      text: 'Add Supplier',
                      description: 'Register manufacturer to the list',
                      onPressed: () => {context.push('/addsupplier')},
                      color: 'blue',
                    ),
                    const Gap(16),
                    MenuWidget(
                      icon: FontAwesomeIcons.circlePlus,
                      text: 'Add Type',
                      description: 'Register new medical type',
                      onPressed: () => {context.push('/addtype')},
                      color: 'blue',
                    ),
                    const Gap(16),
                    MenuWidget(
                      icon: FontAwesomeIcons.circlePlus,
                      text: 'Add Category',
                      description: 'Register new medicine category',
                      onPressed: () => {context.push('/addcategory')},
                      color: 'blue',
                    ),
                    const Gap(16),
                    MenuWidget(
                        icon: FontAwesomeIcons.circlePlus,
                        text: 'Add Generics',
                        description: 'Register generic name',
                        onPressed: () => {context.push('/addgenerics')},
                        color: 'blue'),
                    const Gap(32),
                    MenuWidget(
                        icon: FontAwesomeIcons.circlePlus,
                        text: 'Add Medicine',
                        description: 'Register medicine to the global list',
                        onPressed: () => {context.push('/addmedicines')},
                        color: 'green'),
                    const Gap(16),
                    MenuWidget(
                        icon: FontAwesomeIcons.circlePlus,
                        text: 'Add Stock',
                        description: 'Add a new stock',
                        onPressed: () => {context.push('/addstock')},
                        color: 'green'),
                    const Gap(32),
                    MenuWidget(
                        icon: Icons.delete,
                        text: 'Remove Stock',
                        description: 'Reduce stock based on purchase',
                        onPressed: () => {context.push('/deletestock')},
                        color: 'red'),
                    const Gap(32),
                    MenuWidget(
                        icon: FontAwesomeIcons.listCheck,
                        text: 'List of Stocks',
                        description: 'View the list of available stocks',
                        onPressed: () => {context.push('/liststocks')},
                        color: 'yellow'),
                    const Gap(40),
                    ButtonWithProgressWidget(
                        trigger: _isLoading, progressText: 'Logging Out', buttonText: 'Logout', onPressed: signOut),
                  ],
                ),
              ),
            ),
          ),
        ));
  }
}
