import 'package:flutter/material.dart';
import 'package:youmazgestion/Components/app_bar.dart';
//import 'package:youmazgestion/Models/Permission.dart';
//import 'package:youmazgestion/Services/app_database.dart';
import 'package:youmazgestion/Models/role.dart';
import 'package:youmazgestion/Services/stock_managementDatabase.dart';
import 'package:youmazgestion/Views/RolePermissionPage.dart';

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

  @override
  State<RoleListPage> createState() => _RoleListPageState();
}

class _RoleListPageState extends State<RoleListPage> {
  final db = AppDatabase.instance;
  final TextEditingController _roleController = TextEditingController();
  List<Role> roles = [];

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

  Future<void> _loadRoles() async {
    final roleList = await db.getRoles();
    setState(() {
      roles = roleList;
    });
  }

  Future<void> _addRole() async {
    String designation = _roleController.text.trim();
    if (designation.isEmpty) return;

    await db.createRole(Role(designation: designation));
    _roleController.clear();
    await _loadRoles();
  }

  Future<void> _deleteRole(int roleId) async {
    await db.deleteRole(roleId);
    await _loadRoles();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:  CustomAppBar(title: "Gestion des rôles"),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // Section d'ajout de rôle
            Card(
              elevation: 4,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    Text(
                      'Ajouter un nouveau rôle',
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                    ),
                    const SizedBox(height: 10),
                    Row(
                      children: [
                        Expanded(
                          child: TextField(
                            controller: _roleController,
                            decoration: InputDecoration(
                              labelText: 'Nom du rôle',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                              contentPadding: const EdgeInsets.symmetric(
                                  horizontal: 12, vertical: 12),
                            ),
                          ),
                        ),
                        const SizedBox(width: 10),
                        ElevatedButton(
                          onPressed: _addRole,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                            // padding: const EdgeInsets.symmetric(
                            //     horizontal: 20, vertical: 15),
                          ),
                          
                        ),
                        child: const Text('Ajouter'),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 20),
            // Liste des rôles existants
            Expanded(
              child: Card(
                elevation: 4,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Liste des rôles',
                        style: Theme.of(context).textTheme.titleMedium?.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                      ),
                      const SizedBox(height: 10),
                      Expanded(
                        child: roles.isEmpty
                            ? const Center(
                                child: Text('Aucun rôle créé'),
                              )
                            : ListView.builder(
                                itemCount: roles.length,
                                itemBuilder: (context, index) {
                                  final role = roles[index];
                                  return Card(
                                    margin: const EdgeInsets.only(bottom: 8),
                                    elevation: 2,
                                    child: ListTile(
                                      title: Text(role.designation),
                                      trailing: Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          IconButton(
                                            icon: const Icon(Icons.edit,
                                                color: Colors.blue),
                                            onPressed: () {
                                              _navigateToRolePermissions(
                                                  context, role);
                                            },
                                          ),
                                          IconButton(
                                            icon: const Icon(Icons.delete,
                                                color: Colors.red),
                                            onPressed: () {
                                              _showDeleteDialog(role);
                                            },
                                          ),
                                        ],
                                      ),
                                      onTap: () {
                                        _navigateToRolePermissions(
                                            context, role);
                                      },
                                    ),
                                  );
                                },
                              ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _navigateToRolePermissions(BuildContext context, Role role) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => RolePermissionsPage(role: role),
      ),
    );
  }

  void _showDeleteDialog(Role role) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Confirmer la suppression'),
          content: Text(
              'Êtes-vous sûr de vouloir supprimer le rôle "${role.designation}" ?'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('Annuler'),
            ),
            TextButton(
              onPressed: () async {
                Navigator.of(context).pop();
                await _deleteRole(role.id!);
              },
              child: const Text('Supprimer', style: TextStyle(color: Colors.red)),
            ),
          ],
        );
      },
    );
  }
}