import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:youmazgestion/Components/app_bar.dart';
import 'package:youmazgestion/Components/appDrawer.dart';
import 'package:youmazgestion/Services/stock_managementDatabase.dart';
import 'package:youmazgestion/controller/userController.dart';

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

  @override
  _HistoriqueSortiesPersonnellesPageState createState() => _HistoriqueSortiesPersonnellesPageState();
}

class _HistoriqueSortiesPersonnellesPageState extends State<HistoriqueSortiesPersonnellesPage> {
  final AppDatabase _database = AppDatabase.instance;
  final UserController _userController = Get.find<UserController>();
  
  List<Map<String, dynamic>> _historique = [];
  String? _filtreStatut;
  bool _isLoading = false;
  bool _afficherSeulementMesDemandes = false;

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

  Future<void> _loadHistorique() async {
    setState(() => _isLoading = true);
    try {
       final historique = await _database.getHistoriqueSortiesPersonnelles(
        adminId: _afficherSeulementMesDemandes ? _userController.userId : null,
        statut: _filtreStatut,
        pointDeVenteId: _userController.pointDeVenteId == 0 ? null : _userController.pointDeVenteId, // Si pointDeVenteId = 0, ne pas filtrer
        limit: 100,
      );
      setState(() {
        _historique = historique;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      Get.snackbar('Erreur', 'Impossible de charger l\'historique: $e');
    }
  }

  Color _getStatutColor(String statut) {
    switch (statut) {
      case 'en_attente':
        return Colors.orange;
      case 'approuvee':
        return Colors.green;
      case 'refusee':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  String _getStatutText(String statut) {
    switch (statut) {
      case 'en_attente':
        return 'En attente';
      case 'approuvee':
        return 'Approuvée';
      case 'refusee':
        return 'Refusée';
      default:
        return statut;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(title: 'Historique sorties personnelles'),
      drawer: CustomDrawer(),
      body: Column(
        children: [
          // Filtres
          Container(
            padding: const EdgeInsets.all(16),
            color: Colors.grey.shade50,
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                      child: DropdownButtonFormField<String>(
                        value: _filtreStatut,
                        decoration: const InputDecoration(
                          labelText: 'Filtrer par statut',
                          border: OutlineInputBorder(),
                          isDense: true,
                        ),
                        items: const [
                          DropdownMenuItem(value: null, child: Text('Tous les statuts')),
                          DropdownMenuItem(value: 'en_attente', child: Text('En attente')),
                          DropdownMenuItem(value: 'approuvee', child: Text('Approuvées')),
                          DropdownMenuItem(value: 'refusee', child: Text('Refusées')),
                        ],
                        onChanged: (value) {
                          setState(() {
                            _filtreStatut = value;
                          });
                          _loadHistorique();
                        },
                      ),
                    ),
                    const SizedBox(width: 12),
                    ElevatedButton.icon(
                      onPressed: _loadHistorique,
                      icon: const Icon(Icons.refresh, size: 18),
                      label: const Text('Actualiser'),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                Row(
                  children: [
                    Checkbox(
                      value: _afficherSeulementMesDemandes,
                      onChanged: (value) {
                        setState(() {
                          _afficherSeulementMesDemandes = value ?? false;
                        });
                        _loadHistorique();
                      },
                    ),
                    const Text('Afficher seulement mes demandes'),
                  ],
                ),
              ],
            ),
          ),

          // Liste
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : RefreshIndicator(
                    onRefresh: _loadHistorique,
                    child: _historique.isEmpty
                        ? const Center(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(Icons.history, size: 64, color: Colors.grey),
                                SizedBox(height: 16),
                                Text(
                                  'Aucun historique trouvé pour ce point de vente',
                                  style: TextStyle(fontSize: 18, color: Colors.grey),
                                  textAlign: TextAlign.center,
                                ),
                              ],
                            ),
                          )
                        : ListView.builder(
                            padding: const EdgeInsets.all(16),
                            itemCount: _historique.length,
                            itemBuilder: (context, index) {
                              final sortie = _historique[index];
                              return _buildHistoriqueCard(sortie);
                            },
                          ),
                  ),
          ),
        ],
      ),
    );
  }

  Widget _buildHistoriqueCard(Map<String, dynamic> sortie) {
    final dateSortie = DateTime.parse(sortie['date_sortie'].toString());
    final statut = sortie['statut'].toString();
    final statutColor = _getStatutColor(statut);
    
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(color: statutColor.withOpacity(0.3), width: 1),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // En-tête avec statut et date
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: statutColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: statutColor.withOpacity(0.5)),
                  ),
                  child: Text(
                    _getStatutText(statut),
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                      color: statutColor,
                    ),
                  ),
                ),
                const Spacer(),
                Text(
                  DateFormat('dd/MM/yyyy HH:mm').format(dateSortie),
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey.shade600,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),

            // Informations principales
            Row(
              children: [
                Expanded(
                  flex: 2,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        sortie['produit_nom'].toString(),
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text('Réf: ${sortie['produit_reference'] ?? 'N/A'}'),
                      Text('Quantité: ${sortie['quantite']}'),
                    ],
                  ),
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Demandeur:',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                      ),
                      Text(
                        '${sortie['admin_nom']} ${sortie['admin_nom_famille'] ?? ''}',
                        style: const TextStyle(fontWeight: FontWeight.w500),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),

            // Motif
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.grey.shade50,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Motif:',
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                      color: Colors.grey.shade700,
                    ),
                  ),
                  Text(sortie['motif'].toString()),
                ],
              ),
            ),

            // Informations d'approbation/refus
            if (statut != 'en_attente' && sortie['approbateur_nom'] != null) ...[
              const SizedBox(height: 12),
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: statutColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      statut == 'approuvee' ? 'Approuvé par:' : 'Refusé par:',
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: Colors.grey.shade700,
                      ),
                    ),
                    Text('${sortie['approbateur_nom']} ${sortie['approbateur_nom_famille'] ?? ''}'),
                    if (sortie['date_approbation'] != null)
                      Text(
                        'Le ${DateFormat('dd/MM/yyyy HH:mm').format(DateTime.parse(sortie['date_approbation'].toString()))}',
                        style: TextStyle(
                          fontSize: 11,
                          color: Colors.grey.shade600,
                        ),
                      ),
                  ],
                ),
              ),
            ],

            // Notes supplémentaires
            if (sortie['notes'] != null && sortie['notes'].toString().isNotEmpty) ...[
              const SizedBox(height: 8),
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.blue.shade50,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Notes:',
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                        color: Colors.blue.shade700,
                      ),
                    ),
                    Text(
                      sortie['notes'].toString(),
                      style: const TextStyle(fontSize: 12),
                    ),
                  ],
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}