// pages/encaissement_screen.dart
import 'package:flutter/material.dart';
import 'package:itrimobe/pages/caisse_screen.dart';
import 'package:itrimobe/widgets/command_directe_dialog.dart';
import '../services/restaurant_api_service.dart';
import '../models/tables_order.dart';
import '../widgets/command_card.dart';

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

  @override
  // ignore: library_private_types_in_public_api
  _EncaissementScreenState createState() => _EncaissementScreenState();
}

class _EncaissementScreenState extends State<EncaissementScreen> {
  List<TableOrder> commandes = [];
  bool isLoading = true;

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

Future<void> _loadCommandes() async {
  if (!mounted) return; // Vérifier si le widget est encore monté
  
  setState(() => isLoading = true);

  try {
    final result = await RestaurantApiService.getCommandes();
    
    if (!mounted) return; // Vérifier à nouveau avant setState
    
    setState(() {
      commandes = result;
      isLoading = false;
    });
  } catch (e) {
    if (!mounted) return; // Vérifier avant setState
    
    setState(() => isLoading = false);
    _showErrorSnackBar('Erreur lors du chargement: $e');
  }
}

  // Dans encaissement_screen.dart, modifier la méthode _allerAlaCaisse:
  Future<void> _allerAlaCaisse(TableOrder commande) async {
    // Navigation vers la page de caisse
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder:
            (context) => CaisseScreen(
              commandeId: commande.id.toString(),
              tableName: commande.tablename.toString(),
            ),
      ),
    );

    // Recharger les données si le paiement a été effectué
    if (result == true) {
      _loadCommandes();
    }
  }

  void _showCommandeDirecteDialog() {
    showDialog(
      context: context,
      builder:
          (context) => CommandeDirecteDialog(
            onCommandeCreated: () {
              Navigator.of(context).pop();
              _loadCommandes();
            },
          ),
    );
  }

  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        duration: const Duration(seconds: 3),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA),
      body: Column(
        children: [
          // Header personnalisé
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                const Icon(Icons.attach_money, color: Colors.black54, size: 28),
                const SizedBox(width: 12),
                Text(
                  'Prêt à encaisser (${commandes.length})',
                  style: const TextStyle(
                    color: Colors.black87,
                    fontSize: 20,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const Spacer(),
                // Bouton Commande Directe
                // ElevatedButton.icon(
                //   onPressed: _showCommandeDirecteDialog,
                //   icon: const Icon(Icons.add_shopping_cart, size: 20),
                //   label: const Text('Commande Directe'),
                //   style: ElevatedButton.styleFrom(
                //     backgroundColor: const Color(0xFF007BFF),
                //     foregroundColor: Colors.white,
                //     elevation: 2,
                //     padding: const EdgeInsets.symmetric(
                //       horizontal: 16,
                //       vertical: 12,
                //     ),
                //     shape: RoundedRectangleBorder(
                //       borderRadius: BorderRadius.circular(8),
                //     ),
                //   ),
                // ),
              ],
            ),
          ),

          const Divider(height: 1, color: Color(0xFFE5E5E5)),

          // Contenu principal
          Expanded(
            child: RefreshIndicator(
              onRefresh: _loadCommandes,
              child:
                  isLoading
                      ? const Center(
                        child: CircularProgressIndicator(
                          color: Color(0xFF28A745),
                        ),
                      )
                      : commandes.isEmpty
                      ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.receipt_long,
                              size: 64,
                              color: Colors.grey[400],
                            ),
                            const SizedBox(height: 16),
                            Text(
                              'Aucune commande prête à encaisser',
                              style: TextStyle(
                                fontSize: 18,
                                color: Colors.grey[600],
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                            const SizedBox(height: 8),
                            Text(
                              'Les commandes terminées apparaîtront ici',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.grey[500],
                              ),
                            ),
                          ],
                        ),
                      )
                      : ListView.builder(
                        padding: const EdgeInsets.all(16),
                        itemCount: commandes.length,
                        itemBuilder: (context, index) {
                          return CommandeCard(
                            commande: commandes[index],
                            onAllerCaisse:
                                () => _allerAlaCaisse(commandes[index]),
                          );
                        },
                      ),
            ),
          ),
        ],
      ),
    );
  }
}
