import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:barber_app/core/theme/app_theme.dart';
import 'package:barber_app/core/database/database_service.dart';
import 'package:barber_app/features/auth/presentation/bloc/auth_bloc.dart';
import 'package:barber_app/features/auth/data/repositories/auth_repository.dart';
import 'package:barber_app/features/auth/presentation/pages/login_page.dart';
import 'package:barber_app/features/home/presentation/pages/home_page.dart';

void main() async {
  try {
    WidgetsFlutterBinding.ensureInitialized();

    // Inicializa localização pt_BR
    await initializeDateFormatting('pt_BR', null);
    Intl.defaultLocale = 'pt_BR';

    // Inicializa banco de dados
    await DatabaseService.init();

    // Carrega cor personalizada do usuário logado
    final userId = DatabaseService.getCurrentUserId();
    if (userId != null) {
      final settings = DatabaseService.settingsBoxInstance.get(userId);
      if (settings != null) {
        AppColors.updatePrimaryColor(Color(settings.primaryColorValue));
      }
    }

    runApp(const BarberApp());
  } catch (e, stackTrace) {
    debugPrint('ERRO FATAL DE INICIALIZAÇÃO: $e');
    debugPrintStack(stackTrace: stackTrace);
    runApp(
      MaterialApp(
        home: Scaffold(
          backgroundColor: Colors.red,
          body: Center(
            child: Padding(
              padding: const EdgeInsets.all(24.0),
              child: SingleChildScrollView(
                child: Text(
                  'Erro ao iniciar o app:\n$e',
                  style: const TextStyle(color: Colors.white, fontSize: 16),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: DatabaseService.settingsBoxInstance.listenable(),
      builder: (context, box, _) {
        final userId = DatabaseService.getCurrentUserId();
        // Atualiza a cor global se houver configuração salva para o usuário atual
        ThemeMode themeMode = ThemeMode.dark;
        String appName = 'Barber App';

        if (userId != null && box.containsKey(userId)) {
          final settings = box.get(userId);
          if (settings != null) {
            AppColors.updatePrimaryColor(Color(settings.primaryColorValue));
            if (settings.appName != null && settings.appName!.isNotEmpty) {
              appName = settings.appName!;
            }
            if (settings.isDark == false) {
              themeMode = ThemeMode.light;
            }
          }
        }

        return BlocProvider(
          create: (_) =>
              AuthBloc(authRepository: AuthRepository())
                ..add(AuthCheckRequested()),
          child: MaterialApp(
            title: appName,
            debugShowCheckedModeBanner: false,
            // Configura os temas
            theme: AppTheme.lightTheme,
            darkTheme: AppTheme.darkTheme,
            themeMode: themeMode,
            localizationsDelegates: const [
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            supportedLocales: const [Locale('pt', 'BR')],
            locale: const Locale('pt', 'BR'),
            home: BlocBuilder<AuthBloc, AuthState>(
              builder: (context, state) {
                if (state is AuthLoading || state is AuthInitial) {
                  return SplashScreen(appName: appName);
                }
                if (state is AuthAuthenticated) {
                  return const HomePage();
                }
                return const LoginPage();
              },
            ),
          ),
        );
      },
    );
  }
}

class SplashScreen extends StatelessWidget {
  final String appName;
  const SplashScreen({super.key, required this.appName});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 100,
              height: 100,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                gradient: LinearGradient(
                  colors: [
                    AppColors.primaryColor,
                    AppColors.primaryColor.withValues(alpha: 0.1),
                  ],
                ),
              ),
              child: const Icon(
                Icons.content_cut,
                size: 50,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 24),
            Text(
              appName,
              style: TextStyle(
                fontSize: 28,
                fontWeight: FontWeight.bold,
                color: AppColors.primaryColor,
              ),
            ),
            const SizedBox(height: 16),
            CircularProgressIndicator(color: AppColors.primaryColor),
          ],
        ),
      ),
    );
  }
}
