import 'package:flutter/material.dart';
import 'package:p_tits_pas/models/user.dart';
import 'package:p_tits_pas/services/auth_service.dart';
import 'package:p_tits_pas/services/configuration_service.dart';
import 'package:p_tits_pas/widgets/admin/dashboard_admin.dart';
import 'package:p_tits_pas/widgets/admin/parametres_panel.dart';
import 'package:p_tits_pas/widgets/admin/user_management_panel.dart';
import 'package:p_tits_pas/widgets/app_footer.dart';
import 'package:p_tits_pas/widgets/dashboard/dashboard_bandeau.dart';

class AdminDashboardScreen extends StatefulWidget {
  const AdminDashboardScreen({super.key});

  @override
  State<AdminDashboardScreen> createState() => _AdminDashboardScreenState();
}

class _AdminDashboardScreenState extends State<AdminDashboardScreen> {
  bool? _setupCompleted;
  AppUser? _user;
  int mainTabIndex = 0;
  int settingsSubIndex = 0;

  @override
  void initState() {
    super.initState();
    _loadSetupStatus();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _loadSetupStatus() async {
    try {
      final completed = await ConfigurationService.getSetupStatus();
      final user = await AuthService.getCurrentUser();
      if (!mounted) return;
      setState(() {
        _setupCompleted = completed;
        _user = user;
        if (!completed) mainTabIndex = 1;
      });
    } catch (e) {
      if (mounted) {
        setState(() {
          _setupCompleted = false;
          mainTabIndex = 1;
        });
      }
    }
  }

  void onMainTabChange(int index) {
    setState(() {
      mainTabIndex = index;
    });
  }

  void onSettingsSubTabChange(int index) {
    setState(() {
      settingsSubIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_setupCompleted == null) {
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(60.0),
        child: DashboardBandeau(
          tabItems: [
            DashboardTabItem(
              label: 'Gestion des utilisateurs',
              enabled: _setupCompleted!,
            ),
            const DashboardTabItem(label: 'Paramètres'),
          ],
          selectedTabIndex: mainTabIndex,
          onTabSelected: onMainTabChange,
          userDisplayName: _user?.fullName.isNotEmpty == true
              ? _user!.fullName
              : 'Admin',
          userEmail: _user?.email,
          userRole: _user?.role,
          onProfileTap: () {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('Modification du profil – à venir')),
            );
          },
          onSettingsTap: () => onMainTabChange(1),
          onLogout: () {},
          showLogoutConfirmation: true,
        ),
      ),
      body: Column(
        children: [
          if (mainTabIndex == 0)
            const SizedBox.shrink()
          else
            DashboardSettingsSubBar(
              selectedSubIndex: settingsSubIndex,
              onSubTabChange: onSettingsSubTabChange,
            ),
          Expanded(
            child: _getBody(),
          ),
          const AppFooter(),
        ],
      ),
    );
  }

  Widget _getBody() {
    if (mainTabIndex == 1) {
      return ParametresPanel(
        redirectToLoginAfterSave: !_setupCompleted!,
        selectedSettingsTabIndex: settingsSubIndex,
      );
    }
    return const UserManagementPanel();
  }
}
