import 'package:flutter/material.dart';
import 'package:p_tits_pas/screens/administrateurs/creation/gestionnaires_create.dart';
import 'package:p_tits_pas/widgets/admin/admin_management_widget.dart';
import 'package:p_tits_pas/widgets/admin/assistante_maternelle_management_widget.dart';
import 'package:p_tits_pas/widgets/admin/dashboard_admin.dart';
import 'package:p_tits_pas/widgets/admin/gestionnaire_management_widget.dart';
import 'package:p_tits_pas/widgets/admin/parent_managmant_widget.dart';

class UserManagementPanel extends StatefulWidget {
  /// Afficher l'onglet Administrateurs (sinon 3 onglets : Gestionnaires, Parents, AM).
  final bool showAdministrateursTab;

  const UserManagementPanel({
    super.key,
    this.showAdministrateursTab = true,
  });

  @override
  State<UserManagementPanel> createState() => _UserManagementPanelState();
}

class _UserManagementPanelState extends State<UserManagementPanel> {
  int _subIndex = 0;
  int _gestionnaireRefreshTick = 0;
  int _adminRefreshTick = 0;
  final TextEditingController _searchController = TextEditingController();
  final TextEditingController _amCapacityController = TextEditingController();
  String? _parentStatus;

  @override
  void initState() {
    super.initState();
    _searchController.addListener(_onFilterChanged);
    _amCapacityController.addListener(_onFilterChanged);
  }

  @override
  void dispose() {
    _searchController.removeListener(_onFilterChanged);
    _amCapacityController.removeListener(_onFilterChanged);
    _searchController.dispose();
    _amCapacityController.dispose();
    super.dispose();
  }

  void _onFilterChanged() {
    if (!mounted) return;
    setState(() {});
  }

  void _onSubTabChange(int index) {
    final maxIndex = widget.showAdministrateursTab ? 3 : 2;
    setState(() {
      _subIndex = index.clamp(0, maxIndex);
      _searchController.clear();
      _parentStatus = null;
      _amCapacityController.clear();
    });
  }

  String _searchHintForTab() {
    switch (_subIndex) {
      case 0:
        return 'Rechercher un gestionnaire...';
      case 1:
        return 'Rechercher un parent...';
      case 2:
        return 'Rechercher une assistante...';
      case 3:
        return 'Rechercher un administrateur...';
      default:
        return 'Rechercher...';
    }
  }

  Widget? _subBarFilterControl() {
    if (_subIndex == 1) {
      return DropdownButtonHideUnderline(
        child: DropdownButton<String?>(
          value: _parentStatus,
          isExpanded: true,
          hint: const Padding(
            padding: EdgeInsets.only(left: 10),
            child: Text('Statut', style: TextStyle(fontSize: 12)),
          ),
          items: const [
            DropdownMenuItem<String?>(
              value: null,
              child: Padding(
                padding: EdgeInsets.only(left: 10),
                child: Text('Tous', style: TextStyle(fontSize: 12)),
              ),
            ),
            DropdownMenuItem<String?>(
              value: 'actif',
              child: Padding(
                padding: EdgeInsets.only(left: 10),
                child: Text('Actif', style: TextStyle(fontSize: 12)),
              ),
            ),
            DropdownMenuItem<String?>(
              value: 'en_attente',
              child: Padding(
                padding: EdgeInsets.only(left: 10),
                child: Text('En attente', style: TextStyle(fontSize: 12)),
              ),
            ),
            DropdownMenuItem<String?>(
              value: 'suspendu',
              child: Padding(
                padding: EdgeInsets.only(left: 10),
                child: Text('Suspendu', style: TextStyle(fontSize: 12)),
              ),
            ),
          ],
          onChanged: (value) {
            setState(() {
              _parentStatus = value;
            });
          },
        ),
      );
    }

    if (_subIndex == 2) {
      return TextField(
        controller: _amCapacityController,
        decoration: const InputDecoration(
          hintText: 'Capacité min',
          hintStyle: TextStyle(fontSize: 12),
          border: InputBorder.none,
          isDense: true,
          contentPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
        ),
        keyboardType: TextInputType.number,
      );
    }
    return null;
  }

  Widget _buildBody() {
    switch (_subIndex) {
      case 0:
        return GestionnaireManagementWidget(
          key: ValueKey('gestionnaires-$_gestionnaireRefreshTick'),
          searchQuery: _searchController.text,
        );
      case 1:
        return ParentManagementWidget(
          searchQuery: _searchController.text,
          statusFilter: _parentStatus,
        );
      case 2:
        return AssistanteMaternelleManagementWidget(
          searchQuery: _searchController.text,
          capacityMin: int.tryParse(_amCapacityController.text),
        );
      case 3:
        return AdminManagementWidget(
          key: ValueKey('admins-$_adminRefreshTick'),
          searchQuery: _searchController.text,
        );
      default:
        return const Center(child: Text('Page non trouvée'));
    }
  }

  @override
  Widget build(BuildContext context) {
    final subTabCount = widget.showAdministrateursTab ? 4 : 3;
    return Column(
      children: [
        DashboardUserManagementSubBar(
          selectedSubIndex: _subIndex,
          onSubTabChange: _onSubTabChange,
          searchController: _searchController,
          searchHint: _searchHintForTab(),
          filterControl: _subBarFilterControl(),
          onAddPressed: _handleAddPressed,
          addLabel: 'Ajouter',
          subTabCount: subTabCount,
        ),
        Expanded(child: _buildBody()),
      ],
    );
  }

  Future<void> _handleAddPressed() async {
    if (_subIndex == 0) {
      final created = await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (dialogContext) {
          return const AdminUserFormDialog();
        },
      );

      if (!mounted) return;
      if (created == true) {
        setState(() {
          _gestionnaireRefreshTick++;
        });
      }
      return;
    }

    if (_subIndex == 3) {
      final created = await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (dialogContext) {
          return const AdminUserFormDialog(
            adminMode: true,
            withRelais: false,
          );
        },
      );

      if (!mounted) return;
      if (created == true) {
        setState(() {
          _adminRefreshTick++;
        });
      }
      return;
    }

    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text(
          'La création est disponible pour les gestionnaires et administrateurs.',
        ),
      ),
    );
  }
}
