// widgets/commande_directe_dialog.dart
import 'package:flutter/material.dart';
import 'package:itrimobe/services/restaurant_api_service.dart';

class CommandeDirecteDialog extends StatefulWidget {
  final VoidCallback onCommandeCreated;

  const CommandeDirecteDialog({super.key, required this.onCommandeCreated});

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

class _CommandeDirecteDialogState extends State<CommandeDirecteDialog> {
  final _formKey = GlobalKey<FormState>();
  final _tableController = TextEditingController();
  final _personnesController = TextEditingController(text: '1');
  final _totalController = TextEditingController();
  bool _isLoading = false;

  Future<void> _creerCommande() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isLoading = true);

    final commandeData = {
      'table_number': int.parse(_tableController.text),
      'persons': int.parse(_personnesController.text),
      'total': double.parse(_totalController.text),
      'time': TimeOfDay.now().format(context),
      'date': DateTime.now().toString().split(' ')[0],
      'is_direct': true,
    };

    final success = await RestaurantApiService.creerCommandeDirecte(
      commandeData,
    );

    setState(() => _isLoading = false);

    if (success) {
      widget.onCommandeCreated();
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Commande directe créée avec succès'),
          backgroundColor: Colors.green,
        ),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Erreur lors de la création'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Container(
        padding: EdgeInsets.all(24),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.add_shopping_cart, color: Color(0xFF007BFF)),
                  SizedBox(width: 12),
                  Text(
                    'Nouvelle Commande Directe',
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                  ),
                ],
              ),

              SizedBox(height: 24),

              TextFormField(
                controller: _tableController,
                decoration: InputDecoration(
                  labelText: 'Numéro de table',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  prefixIcon: Icon(Icons.table_restaurant),
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value?.isEmpty ?? true) return 'Numéro de table requis';
                  if (int.tryParse(value!) == null) return 'Numéro invalide';
                  return null;
                },
              ),

              SizedBox(height: 16),

              TextFormField(
                controller: _personnesController,
                decoration: InputDecoration(
                  labelText: 'Nombre de personnes',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  prefixIcon: Icon(Icons.people),
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value?.isEmpty ?? true)
                    return 'Nombre de personnes requis';
                  if (int.tryParse(value!) == null) return 'Nombre invalide';
                  return null;
                },
              ),

              SizedBox(height: 16),

              TextFormField(
                controller: _totalController,
                decoration: InputDecoration(
                  labelText: 'Total (MGA)',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  prefixIcon: Icon(Icons.euro),
                ),
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                validator: (value) {
                  if (value?.isEmpty ?? true) return 'Total requis';
                  if (double.tryParse(value!) == null)
                    return 'Montant invalide';
                  return null;
                },
              ),

              SizedBox(height: 24),

              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: _isLoading ? null : () => Navigator.pop(context),
                    child: Text('Annuler'),
                  ),
                  SizedBox(width: 12),
                  ElevatedButton(
                    onPressed: _isLoading ? null : _creerCommande,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Color(0xFF28A745),
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(
                        horizontal: 24,
                        vertical: 12,
                      ),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    child:
                        _isLoading
                            ? SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                color: Colors.white,
                              ),
                            )
                            : Text('Créer'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
