import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/models.dart';
import '../../viewmodels/viewmodels.dart';

class DescuentoScreen extends StatefulWidget {
  DescuentoScreen({super.key});

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

class _DescuentoScreenState extends State<DescuentoScreen> {
  final TextEditingController _porcentajeController = TextEditingController();
  String? _errorText;

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

    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<DescuentoViewModel>(context, listen: false)
          .cargarDescuentos();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Gestionar Descuentos"),
      ),
      body: Consumer<DescuentoViewModel>(
        builder: (context, viewModel, child) {
          return Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Card(
                  elevation: 4,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(12.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          "Agregar Nuevo Descuento",
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 18,
                          ),
                        ),
                        const SizedBox(height: 10),
                        Row(
                          children: [
                            Expanded(
                              child: TextField(
                                controller: _porcentajeController,
                                decoration: InputDecoration(
                                  labelText: "Porcentaje (%)",
                                  errorText: _errorText,
                                  border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(8.0),
                                  ),
                                ),
                                keyboardType: TextInputType.number,
                              ),
                            ),
                            const SizedBox(width: 10),
                            ElevatedButton.icon(
                              icon: Icon(Icons.add),
                              label: Text("Agregar"),
                              onPressed: () {
                                setState(() {
                                  _errorText = null;
                                });

                                if (_porcentajeController.text.isNotEmpty) {
                                  final int porcentaje =
                                      int.parse(_porcentajeController.text);

                                  if (porcentaje > 100) {
                                    setState(() {
                                      _errorText =
                                          'El descuento no puede ser mayor a 100%';
                                    });
                                  } else {
                                    viewModel.guardarDescuento(
                                        Descuento(porcentaje: porcentaje));
                                    _porcentajeController.clear();
                                  }
                                }
                              },
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.black,
                                foregroundColor: Colors.white,
                                padding: const EdgeInsets.symmetric(
                                    vertical: 15, horizontal: 20),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 10),
              Expanded(
                child: Card(
                  elevation: 2,
                  margin: const EdgeInsets.symmetric(horizontal: 16.0),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: ListView.builder(
                    itemCount: viewModel.descuentos.length,
                    itemBuilder: (context, index) {
                      final descuento = viewModel.descuentos[index];
                      return ListTile(
                        title: Text(
                          '${descuento.porcentaje}%',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        trailing: IconButton(
                          icon: const Icon(Icons.delete, color: Colors.red),
                          onPressed: () =>
                              viewModel.eliminarDescuento(descuento.id!),
                        ),
                      );
                    },
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}
