import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_navigation/src/snackbar/snackbar.dart';
import 'package:intl/intl.dart';
import 'package:youmazgestion/Components/commandManagementComponents/PaymentMethod.dart';
import 'package:youmazgestion/Components/paymentType.dart';
import 'package:youmazgestion/Models/client.dart';

class PaymentMethodDialog extends StatefulWidget {
  final Commande commande;

  const PaymentMethodDialog({super.key, required this.commande});

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

class _PaymentMethodDialogState extends State<PaymentMethodDialog> {
  PaymentType _selectedPayment = PaymentType.cash;
  final _amountController = TextEditingController();
  
  void _validatePayment() {
    final montantFinal = widget.commande.montantTotal;
    
    if (_selectedPayment == PaymentType.cash) {
      final amountGiven = double.tryParse(_amountController.text) ?? 0;
      if (amountGiven < montantFinal) {
        Get.snackbar(
          'Erreur',
          'Le montant donné est insuffisant',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.red,
          colorText: Colors.white,
        );
        return;
      }
    }

    Navigator.pop(context, PaymentMethod(
      type: _selectedPayment,
      amountGiven: _selectedPayment == PaymentType.cash 
          ? double.parse(_amountController.text) 
          : montantFinal,
    ));
  }
  
  @override
  void initState() {
    super.initState();
    final montantFinal = widget.commande.montantTotal;
    _amountController.text = montantFinal.toStringAsFixed(2);
  }

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

  @override
  Widget build(BuildContext context) {
    final amount = double.tryParse(_amountController.text) ?? 0;
    final montantFinal = widget.commande.montantTotal;
    final change = amount - montantFinal;

    return AlertDialog(
      title: const Text('Méthode de paiement', style: TextStyle(fontWeight: FontWeight.bold)),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Affichage du montant à payer (simplifié)
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.blue.shade200),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text('Montant à payer:', style: TextStyle(fontWeight: FontWeight.bold)),
                  Text('${NumberFormat('#,##0', 'fr_FR').format(montantFinal)} MGA', 
                    style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
                ],
              ),
            ),
            
            const SizedBox(height: 16),
            
            // Section Paiement mobile
            const Align(
              alignment: Alignment.centerLeft,
              child: Text('Mobile Money', style: TextStyle(fontWeight: FontWeight.w500)),
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                Expanded(
                  child: _buildMobileMoneyTile(
                    title: 'Mvola',
                    imagePath: 'assets/mvola.jpg',
                    value: PaymentType.mvola,
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: _buildMobileMoneyTile(
                    title: 'Orange Money',
                    imagePath: 'assets/Orange_money.png',
                    value: PaymentType.orange,
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: _buildMobileMoneyTile(
                    title: 'Airtel Money',
                    imagePath: 'assets/airtel_money.png',
                    value: PaymentType.airtel,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            
            // Section Carte bancaire
            const Align(
              alignment: Alignment.centerLeft,
              child: Text('Carte Bancaire', style: TextStyle(fontWeight: FontWeight.w500)),
            ),
            const SizedBox(height: 8),
            _buildPaymentMethodTile(
              title: 'Carte bancaire',
              icon: Icons.credit_card,
              value: PaymentType.card,
            ),
            const SizedBox(height: 16),
            
            // Section Paiement en liquide
            const Align(
              alignment: Alignment.centerLeft,
              child: Text('Espèces', style: TextStyle(fontWeight: FontWeight.w500)),
            ),
            const SizedBox(height: 8),
            _buildPaymentMethodTile(
              title: 'Paiement en liquide',
              icon: Icons.money,
              value: PaymentType.cash,
            ),
            if (_selectedPayment == PaymentType.cash) ...[
              const SizedBox(height: 12),
              TextField(
                controller: _amountController,
                decoration: const InputDecoration(
                  labelText: 'Montant donné',
                  prefixText: 'MGA ',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                onChanged: (value) => setState(() {}),
              ),
              const SizedBox(height: 8),
              Text(
                'Monnaie à rendre: ${NumberFormat('#,##0', 'fr_FR').format(change)} MGA',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: change >= 0 ? Colors.green : Colors.red,
                ),
              ),
            ],
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Annuler', style: TextStyle(color: Colors.grey)),
        ),
        ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.blue.shade800,
            foregroundColor: Colors.white,
          ),
          onPressed: _validatePayment,
          child: const Text('Confirmer'),
        ),
      ],
    );
  }

  Widget _buildMobileMoneyTile({
    required String title,
    required String imagePath,
    required PaymentType value,
  }) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
        side: BorderSide(
          color: _selectedPayment == value ? Colors.blue : Colors.grey.withOpacity(0.2),
          width: 2,
        ),
      ),
      child: InkWell(
        borderRadius: BorderRadius.circular(8),
        onTap: () => setState(() => _selectedPayment = value),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Column(
            children: [
              Image.asset(
                imagePath,
                height: 30,
                width: 30,
                fit: BoxFit.contain,
                errorBuilder: (context, error, stackTrace) => 
                    const Icon(Icons.mobile_friendly, size: 30),
              ),
              const SizedBox(height: 8),
              Text(
                title,
                textAlign: TextAlign.center,
                style: const TextStyle(fontSize: 12),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPaymentMethodTile({
    required String title,
    required IconData icon,
    required PaymentType value,
  }) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
        side: BorderSide(
          color: _selectedPayment == value ? Colors.blue : Colors.grey.withOpacity(0.2),
          width: 2,
        ),
      ),
      child: InkWell(
        borderRadius: BorderRadius.circular(8),
        onTap: () => setState(() => _selectedPayment = value),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            children: [
              Icon(icon, size: 24),
              const SizedBox(width: 12),
              Text(title),
            ],
          ),
        ),
      ),
    );
  }
}