import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:superport/models/equipment_unified_model.dart';
import 'package:superport/screens/common/app_layout_redesign.dart';
import 'package:superport/screens/common/theme_shadcn.dart';
import 'package:superport/screens/company/company_form.dart';
import 'package:superport/screens/equipment/equipment_in_form.dart';
import 'package:superport/screens/equipment/equipment_out_form.dart';
import 'package:superport/screens/equipment/equipment_history_screen.dart';
import 'package:superport/screens/license/license_form.dart'; // MaintenanceFormScreen으로 사용
import 'package:superport/screens/user/user_form.dart';
import 'package:superport/screens/warehouse_location/warehouse_location_form.dart';
import 'package:superport/services/auth_service.dart';
import 'package:superport/utils/constants.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:superport/screens/login/login_screen.dart';
import 'package:superport/di/injection_container.dart' as di;

void main() async {
  // Flutter 바인딩 초기화
  WidgetsFlutterBinding.ensureInitialized();
  
  try {
    // 의존성 주입 설정
    await di.setupDependencies();
  } catch (e) {
    print('Failed to setup dependencies: $e');
    // 에러가 발생해도 앱은 실행되도록 함
  }
  
  // MockDataService는 싱글톤으로 자동 초기화됨
  runApp(const SuperportApp());
}

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

  @override
  Widget build(BuildContext context) {
    AuthService? authService;
    try {
      authService = GetIt.instance<AuthService>();
    } catch (e) {
      print('Failed to get AuthService: $e');
    }
    
    return MaterialApp(
      title: 'supERPort',
      theme: ShadcnTheme.lightTheme,
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [Locale('ko', 'KR'), Locale('en', 'US')],
      locale: const Locale('ko', 'KR'),
      home: authService == null
          ? const LoginScreen() // AuthService가 없으면 바로 로그인 화면
          : FutureBuilder<bool>(
              future: authService.isLoggedIn(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Scaffold(
                    body: Center(
                      child: CircularProgressIndicator(),
                    ),
                  );
                }
                
                // 에러 처리 추가
                if (snapshot.hasError) {
                  print('Auth check error: ${snapshot.error}');
                  // 에러가 발생해도 로그인 화면으로 이동
                  return const LoginScreen();
                }
                
                if (snapshot.hasData && snapshot.data!) {
                  // 토큰이 유효하면 홈 화면으로
                  return AppLayoutRedesign(initialRoute: Routes.home);
                } else {
                  // 토큰이 없거나 유효하지 않으면 로그인 화면으로
                  return const LoginScreen();
                }
              },
            ),
      onGenerateRoute: (settings) {
        // 로그인 라우트 처리
        if (settings.name == '/login') {
          return MaterialPageRoute(builder: (context) => const LoginScreen());
        }
        // 기본 AppLayout으로 라우팅할 경로 (홈, 목록 화면들)
        if (settings.name == Routes.home ||
            settings.name == Routes.equipment ||
            settings.name == Routes.equipmentInList ||
            settings.name == Routes.equipmentOutList ||
            settings.name == Routes.equipmentRentList ||
            settings.name == Routes.company ||
            settings.name == Routes.user ||
            settings.name == Routes.license) {
          return MaterialPageRoute(
            builder:
                (context) => AppLayoutRedesign(initialRoute: settings.name!),
          );
        }

        // 기존 라우팅 처리 (폼 화면들)
        switch (settings.name) {
          // 장비 입고 관련 라우트
          case Routes.equipmentInAdd:
            return MaterialPageRoute(
              builder: (context) => const EquipmentInFormScreen(),
            );
          case Routes.equipmentInEdit:
            final id = settings.arguments as int;
            return MaterialPageRoute(
              builder: (context) => EquipmentInFormScreen(equipmentInId: id),
            );

          // 장비 출고 관련 라우트
          case Routes.equipmentOutAdd:
            // 선택된 장비 정보와 입고 ID가 전달되었는지 확인
            final args = settings.arguments;
            Equipment? equipment;
            int? equipmentInId;
            List<Map<String, dynamic>>? selectedEquipments;

            // 인자 처리
            if (args is Map<String, dynamic>) {
              // 다중 선택 장비 처리
              if (args.containsKey('selectedEquipments')) {
                selectedEquipments =
                    args['selectedEquipments'] as List<Map<String, dynamic>>;
                debugPrint('선택된 장비 목록: ${selectedEquipments.length}개');
              } else {
                // 단일 장비 선택 (기존 방식)
                equipment = args['equipment'] as Equipment?;
                equipmentInId = args['equipmentInId'] as int?;
                debugPrint('단일 장비 선택');
              }
            } else if (args is List<Map<String, dynamic>>) {
              // 직접 리스트가 전달된 경우
              selectedEquipments = args;
              debugPrint('직접 리스트로 전달된 장비 목록: ${selectedEquipments.length}개');
            } else if (args is Equipment) {
              equipment = args; // 기존 방식 대응 (하위 호환)
              debugPrint('단일 Equipment 객체 전달');
            } else {
              debugPrint('알 수 없는 인자 타입: ${args.runtimeType}');
            }

            return MaterialPageRoute(
              builder:
                  (context) => EquipmentOutFormScreen(
                    selectedEquipment: equipment,
                    selectedEquipmentInId: equipmentInId,
                    selectedEquipments: selectedEquipments,
                  ),
            );
          case Routes.equipmentOutEdit:
            final id = settings.arguments as int;
            return MaterialPageRoute(
              builder: (context) => EquipmentOutFormScreen(equipmentOutId: id),
            );
          
          // 장비 이력 조회
          case Routes.equipmentHistory:
            final args = settings.arguments as Map<String, dynamic>;
            return MaterialPageRoute(
              builder: (context) => EquipmentHistoryScreen(
                equipmentId: args['equipmentId'] as int,
                equipmentName: args['equipmentName'] as String,
              ),
            );

          // 회사 관련 라우트
          case Routes.companyAdd:
            return MaterialPageRoute(
              builder: (context) => const CompanyFormScreen(),
            );
          case Routes.companyEdit:
            final args = settings.arguments;
            if (args is Map) {
              return MaterialPageRoute(
                builder: (context) => CompanyFormScreen(args: args),
              );
            } else if (args is int) {
              // 하위 호환: int만 넘어오는 경우
              return MaterialPageRoute(
                builder:
                    (context) => CompanyFormScreen(args: {'companyId': args}),
              );
            } else {
              return MaterialPageRoute(
                builder: (context) => CompanyFormScreen(),
              );
            }

          // 사용자 관련 라우트
          case Routes.userAdd:
            return MaterialPageRoute(
              builder: (context) => const UserFormScreen(),
            );
          case Routes.userEdit:
            final id = settings.arguments as int;
            return MaterialPageRoute(
              builder: (context) => UserFormScreen(userId: id),
            );

          // 라이센스 관련 라우트
          case Routes.licenseAdd:
            return MaterialPageRoute(
              builder: (context) => const MaintenanceFormScreen(),
            );
          case Routes.licenseEdit:
            final id = settings.arguments as int;
            return MaterialPageRoute(
              builder: (context) => MaintenanceFormScreen(maintenanceId: id),
            );

          // 입고지 관련 라우트
          case Routes.warehouseLocationAdd:
            return MaterialPageRoute(
              builder: (context) => const WarehouseLocationFormScreen(),
            );
          case Routes.warehouseLocationEdit:
            final id = settings.arguments as int;
            return MaterialPageRoute(
              builder: (context) => WarehouseLocationFormScreen(id: id),
            );
          default:
            return MaterialPageRoute(
              builder:
                  (context) => AppLayoutRedesign(initialRoute: Routes.home),
            );
        }
      },
      navigatorKey: GlobalKey<NavigatorState>(),
    );
  }
}
