import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'api_service.dart';
import 'profile_manager.dart'; // Import ProfileManager
import 'screens/profile_login_screen.dart'; // Change import
import 'screens/store_dashboard_screen.dart'; // New Import
import 'screens/profile_screen.dart'; // New Import
import 'screens/product_list_screen.dart';
import 'screens/product_editor_screen.dart';
import 'models/product.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MultiProvider( // Use MultiProvider
      providers: [
        ChangeNotifierProvider(create: (_) => ApiService()),
        ChangeNotifierProvider(create: (_) => ProfileManager()),
      ],
      child: MaterialApp(
        title: 'Inventory Manager',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          useMaterial3: true,
          brightness: Brightness.dark,
          colorScheme: ColorScheme.fromSeed(
            seedColor: Colors.blue,
            brightness: Brightness.dark,
            background: const Color(0xFF111827), 
            surface: const Color(0xFF1F2937),
          ),
          scaffoldBackgroundColor: const Color(0xFF111827),
          appBarTheme: const AppBarTheme(
            backgroundColor: Color(0xFF1F2937),
            elevation: 0,
            centerTitle: false,
          ),
          inputDecorationTheme: InputDecorationTheme(
            filled: true,
            fillColor: const Color(0xFF374151),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: BorderSide.none,
            ),
            hintStyle: const TextStyle(color: Colors.grey),
          ),
        ),
        home: const AuthWrapper(),
        routes: {
          '/product/new': (context) => const ProductEditorScreen(),
          '/profile': (context) => const ProfileScreen(),
        },
        onGenerateRoute: (settings) {
            if (settings.name == '/product/edit') {
                final product = settings.arguments as Product;
                return MaterialPageRoute(
                    builder: (context) => ProductEditorScreen(product: product),
                );
            }
            return null;
        },
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    // Current Flow:
    // 1. App Start
    // 2. Check ProfileManager.isAuthenticated (PIN Protection)
    //    NO -> ProfileLoginScreen
    //    YES -> SiteSelectionScreen
    
    return Consumer<ProfileManager>(
      builder: (context, profile, child) {
        if (!profile.isAuthenticated) {
          return const ProfileLoginScreen();
        } else {
          return const StoreDashboardScreen();
        }
      },
    );
  }
}
