import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'dart:io';
import 'package:flutter_single_instance/flutter_single_instance.dart';

import 'services/productos_service.dart';
import 'views/home/home_screen.dart';
import 'views/login/login_screen.dart';
import 'views/perfil/perfil_screen.dart';
import 'themes/themes.dart';
import 'viewmodels/viewmodels.dart';
import 'package:timezone/data/latest.dart' as tzdata;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  tzdata.initializeTimeZones();

  if (!await FlutterSingleInstance.platform.isFirstInstance()) {
    print("La aplicación ya se está ejecutando");
    exit(0);
  }

  // Inicialización de la base de datos para plataformas de escritorio con FFI
  if (Platform.isWindows || Platform.isLinux) {
    sqfliteFfiInit();
    databaseFactory = databaseFactoryFfi;
  }

  final productosService = ProductosService();
  if (await productosService.isDatabaseEmpty()) {
    await productosService.fillCategoriaBD();
    await productosService.fillProductoBD();
  }

  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeRight,
    DeviceOrientation.landscapeLeft,
  ]).then((_) {
    runApp(MultiProvider(providers: [
      ChangeNotifierProvider(create: (_) => LoginViewModel()),
      ChangeNotifierProvider(create: (_) => UsuarioViewModel()),
      ChangeNotifierProvider(create: (_) => ProfileViewModel()),
      ChangeNotifierProvider(create: (_) => CategoriaProductoViewModel()),
      ChangeNotifierProvider(create: (_) => ProductoViewModel()),
      ChangeNotifierProvider(create: (_) => TopingCategoriaViewModel()),
      ChangeNotifierProvider(create: (_) => MediaViewModel()),
      ChangeNotifierProvider(create: (_) => TopingViewModel()),
      ChangeNotifierProvider(create: (_) => PedidoViewModel()),
      ChangeNotifierProvider(create: (_) => DescuentoViewModel()),
      ChangeNotifierProvider(create: (_) => VariableViewModel()),
      ChangeNotifierProvider(create: (_) => SucursalViewModel()),
      ChangeNotifierProvider(create: (_) => PermisoViewModel()),
      ChangeNotifierProvider(create: (_) => CorteCajaViewModel()),
      ChangeNotifierProvider(create: (_) => MesaViewModel()),
      ChangeNotifierProvider(create: (_) => PropinaViewModel()),
      // Agrega aquí cualquier otro provider que necesites
    ], child: const MyApp()));
  });
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      locale: const Locale("en", "ES"),
      debugShowCheckedModeBanner: false,
      title: 'Turquessa',
      theme: AppTheme.lightTheme,
      initialRoute: 'login',
      routes: {
        'login': (context) => const LoginScreen(),
        'home': (context) => const HomeScreen(),
        'perfil': (context) => const PerfilScreen(),
      },
    );
  }
}
