import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'src/features/auth/data/auth_session_store.dart';
import 'src/features/auth/domain/auth_models.dart';
import 'src/app.dart';
import 'src/smoke/smoke_overrides.dart';

const _preauthToken = String.fromEnvironment('TDC114_PREAUTH_TOKEN');
const _preauthExpiresAt = String.fromEnvironment('TDC114_PREAUTH_EXPIRES_AT');
const _preauthUserId = String.fromEnvironment('TDC114_PREAUTH_USER_ID');
const _preauthUserName = String.fromEnvironment('TDC114_PREAUTH_USER_NAME');
const _preauthUserPhone = String.fromEnvironment('TDC114_PREAUTH_USER_PHONE');
const _preauthTenantId = String.fromEnvironment('TDC114_PREAUTH_TENANT_ID');
const _preauthTenantName = String.fromEnvironment('TDC114_PREAUTH_TENANT_NAME');
const _preauthTenantSlug = String.fromEnvironment('TDC114_PREAUTH_TENANT_SLUG');
const _preauthDepartment = String.fromEnvironment('TDC114_PREAUTH_DEPARTMENT');
const _preauthGrade = String.fromEnvironment('TDC114_PREAUTH_GRADE');
const _preauthPosition = String.fromEnvironment('TDC114_PREAUTH_POSITION');
const _preauthJobTitle = String.fromEnvironment('TDC114_PREAUTH_JOB_TITLE');

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const _BootstrapApp());
}

class _BootstrapApp extends StatefulWidget {
  const _BootstrapApp();

  @override
  State<_BootstrapApp> createState() => _BootstrapAppState();
}

class _BootstrapAppState extends State<_BootstrapApp> {
  late final Future<void> _bootstrapFuture;

  @override
  void initState() {
    super.initState();
    _bootstrapFuture = _seedSmokeSessionIfConfigured();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<void>(
      future: _bootstrapFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            home: Scaffold(
              body: SafeArea(
                child: Center(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: const [
                      CircularProgressIndicator(),
                      SizedBox(height: 16),
                      Text('앱을 준비하고 있습니다...'),
                    ],
                  ),
                ),
              ),
            ),
          );
        }

        if (snapshot.hasError) {
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            home: Scaffold(
              body: SafeArea(
                child: Center(
                  child: Padding(
                    padding: const EdgeInsets.all(24),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Text('앱 시작 중 문제가 발생했습니다.'),
                        const SizedBox(height: 12),
                        Text('${snapshot.error}', textAlign: TextAlign.center),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          );
        }

        return ProviderScope(
          overrides: useSmokeMockDirectory
              ? [smokeDirectoryOverride, smokeOrganizationOverride]
              : const [],
          child: const Tdc114PlusApp(),
        );
      },
    );
  }
}

Future<void> _seedSmokeSessionIfConfigured() async {
  if (_preauthToken.isEmpty ||
      _preauthExpiresAt.isEmpty ||
      _preauthUserId.isEmpty ||
      _preauthUserName.isEmpty ||
      _preauthUserPhone.isEmpty ||
      _preauthTenantId.isEmpty ||
      _preauthTenantName.isEmpty ||
      _preauthTenantSlug.isEmpty) {
    return;
  }

  final expiresAt = DateTime.tryParse(_preauthExpiresAt);
  if (expiresAt == null) {
    return;
  }

  await const AuthSessionStore().save(
    PhoneLoginResponse(
      status: 'ok',
      token: _preauthToken,
      expiresAt: expiresAt,
      user: LoginUser(
        id: _preauthUserId,
        name: _preauthUserName,
        phoneNumber: _preauthUserPhone,
        tenantId: _preauthTenantId,
        tenantName: _preauthTenantName,
        tenantSlug: _preauthTenantSlug,
        department: _valueOrNull(_preauthDepartment),
        grade: _valueOrNull(_preauthGrade),
        position: _valueOrNull(_preauthPosition),
        jobTitle: _valueOrNull(_preauthJobTitle),
      ),
    ),
  );
}

String? _valueOrNull(String value) => value.trim().isEmpty ? null : value;
