import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_bloc.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_event.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_state.dart';
import 'package:hl_lieferservice/feature/car_selection/bloc/bloc.dart';
import 'package:hl_lieferservice/feature/car_selection/bloc/events.dart';
import 'package:hl_lieferservice/feature/car_selection/bloc/state.dart';
import 'package:hl_lieferservice/feature/cars/presentation/car_management_page.dart';
import 'package:hl_lieferservice/feature/settings/presentation/settings_page.dart';

/// Globales Side-Menu für Fahrzeuge & Einstellungen.
///
/// Da Sortieren und Beladen kein BottomNav mehr haben, sind diese
/// administrativen Funktionen nur noch über den Drawer erreichbar.
/// Während der Auslieferungs-Phase steht zusätzlich das alte BottomNav
/// weiterhin zur Verfügung.
class HomeAppDrawer extends StatelessWidget {
  const HomeAppDrawer({super.key});

  void _openPage(BuildContext context, Widget page) {
    Navigator.of(context).pop();
    Navigator.of(context).push(
      MaterialPageRoute(builder: (_) => page),
    );
  }

  Future<void> _confirmLogout(BuildContext context) async {
    final authBloc = context.read<AuthBloc>();
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (dialogContext) => AlertDialog(
        title: const Text("Abmelden"),
        content: const Text(
          "Möchten Sie sich wirklich abmelden? "
          "Beim nächsten Start ist eine erneute Anmeldung erforderlich.",
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(dialogContext).pop(false),
            child: const Text("Abbrechen"),
          ),
          FilledButton(
            style: FilledButton.styleFrom(backgroundColor: Colors.red),
            onPressed: () => Navigator.of(dialogContext).pop(true),
            child: const Text("Abmelden"),
          ),
        ],
      ),
    );
    if (confirmed != true) return;

    authBloc.add(const LogoutRequested());

    // Drawer schließen, falls noch sichtbar — der State-Wechsel auf
    // Unauthenticated leitet danach von selbst auf die LoginPage.
    if (context.mounted && Scaffold.maybeOf(context)?.isDrawerOpen == true) {
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final carState = context.watch<CarSelectBloc>().state;
    final authState = context.watch<AuthBloc>().state;
    final authenticated = authState is Authenticated ? authState : null;

    return Drawer(
      child: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            DrawerHeader(
              decoration: BoxDecoration(color: theme.primaryColor),
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Text(
                    authenticated?.displayName ?? "Holzleitner",
                    style: TextStyle(
                      color: theme.colorScheme.onSecondary,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  if (authenticated != null) ...[
                    const SizedBox(height: 2),
                    Text(
                      "Personalnummer ${authenticated.personalnummer}",
                      style: TextStyle(
                        color: theme.colorScheme.onSecondary.withValues(
                          alpha: 0.85,
                        ),
                        fontSize: 12,
                      ),
                    ),
                  ],
                  const SizedBox(height: 8),
                  if (carState is CarSelectComplete)
                    Row(
                      children: [
                        Icon(
                          Icons.local_shipping,
                          color: theme.colorScheme.onSecondary,
                          size: 16,
                        ),
                        const SizedBox(width: 6),
                        Text(
                          carState.selectedCar.plate,
                          style: TextStyle(
                            color: theme.colorScheme.onSecondary,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    )
                  else
                    Text(
                      "Kein Fahrzeug ausgewählt",
                      style: TextStyle(
                        color: theme.colorScheme.onSecondary.withValues(
                          alpha: 0.8,
                        ),
                        fontSize: 13,
                      ),
                    ),
                ],
              ),
            ),
            if (carState is CarSelectComplete)
              ListTile(
                leading: const Icon(Icons.swap_horiz),
                title: const Text("Fahrzeug wechseln"),
                onTap: () {
                  Navigator.of(context).pop();
                  context.read<CarSelectBloc>().add(CarSelectChange());
                },
              ),
            ListTile(
              leading: const Icon(Icons.local_shipping_outlined),
              title: const Text("Fahrzeuge verwalten"),
              onTap: () => _openPage(context, const CarManagementPage()),
            ),
            ListTile(
              leading: const Icon(Icons.settings_outlined),
              title: const Text("Einstellungen"),
              onTap: () => _openPage(context, const SettingsPage()),
            ),
            const Spacer(),
            const Divider(height: 1),
            ListTile(
              leading: const Icon(Icons.logout, color: Colors.red),
              title: const Text(
                "Abmelden",
                style: TextStyle(color: Colors.red),
              ),
              onTap: () => _confirmLogout(context),
            ),
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              child: Text(
                "Lieferservice-App",
                style: TextStyle(fontSize: 11, color: Colors.grey),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
