import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:conalep_pos/themes/themes.dart';
import 'package:intl/intl.dart';
import '../../viewmodels/corte_caja_view_model.dart';
import '../../widgets/widgets.dart';

class CorteCajaForm extends StatefulWidget {
  final int? corteCajaId;

  const CorteCajaForm({this.corteCajaId, Key? key}) : super(key: key);

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

class _CorteCajaFormState extends State<CorteCajaForm> {
  final TextEditingController _fondoController = TextEditingController();
  final TextEditingController _fondoSiguienteController =
      TextEditingController();
  final TextEditingController _ventasMostradorController =
      TextEditingController();
  final TextEditingController _montoDepositoController =
      TextEditingController();
  final TextEditingController _montoGastoController = TextEditingController();
  final TextEditingController _descripcionDepositoController =
      TextEditingController();
  final TextEditingController _descripcionGastoController =
      TextEditingController();

  bool showDepositoPanel = false;
  bool showGastoPanel = false;

  @override
  void initState() {
    super.initState();
    if (widget.corteCajaId != null) {
      Provider.of<CorteCajaViewModel>(context, listen: false)
          .fetchDepositosAndGastos(widget.corteCajaId!);
    }
  }

  @override
  Widget build(BuildContext context) {
    final viewModel = Provider.of<CorteCajaViewModel>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Corte de Caja Conalep',
            style: TextStyle(color: AppTheme.quaternary)),
        iconTheme: IconThemeData(color: AppTheme.quaternary),
      ),
      body: Column(children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 50, vertical: 20),
          width: MediaQuery.of(context).size.width,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Expanded(
                flex: 4,
                child: _buildFormContent(context, viewModel),
              ),
              SizedBox(width: 80),
              Expanded(
                flex: 3,
                child: Column(
                  children: [
                    if (showDepositoPanel) _buildDepositoPanel(viewModel),
                    if (showGastoPanel) _buildGastoPanel(viewModel),
                  ],
                ),
              ),
            ],
          ),
        )
      ]),
    );
  }

  Widget _buildFormContent(BuildContext context, CorteCajaViewModel viewModel) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "Fecha: ${DateFormat('dd/MM/yyyy').format(DateTime.now())}",
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
        ),
        SizedBox(height: 20),
        tarjeta(
          Table(
            defaultVerticalAlignment: TableCellVerticalAlignment.middle,
            columnWidths: {0: FlexColumnWidth(4), 1: FlexColumnWidth(2)},
            children: [
              _buildTableRow("Fondo", _fondoController),
              _buildDepositoRow(viewModel),
              _buildTableRow("Fondo día siguiente", _fondoSiguienteController),
              _buildTableRow(
                  "Ventas mostrador efectivo", _ventasMostradorController),
              _buildGastoRow(viewModel),
              _buildCorteFinalRow(viewModel),
            ],
          ),
        ),
        SizedBox(height: 20),
        Center(
          child: ElevatedButton(
            onPressed: () {
              viewModel.calcularCorteFinal(
                double.tryParse(_fondoController.text) ?? 0,
                double.tryParse(_fondoSiguienteController.text) ?? 0,
                double.tryParse(_ventasMostradorController.text) ?? 0,
              );
            },
            child:
                Text('Finalizar', style: TextStyle(color: AppTheme.quaternary)),
            style: ElevatedButton.styleFrom(
              backgroundColor: AppTheme.primary,
              padding: EdgeInsets.symmetric(horizontal: 50, vertical: 15),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
            ),
          ),
        ),
      ],
    );
  }

  TableRow _buildTableRow(String label, TextEditingController controller) {
    return TableRow(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(label, style: TextStyle(fontWeight: FontWeight.bold)),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: TextField(
            controller: controller,
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              hintText: "\$",
              border: OutlineInputBorder(),
              contentPadding: EdgeInsets.symmetric(vertical: 8, horizontal: 12),
            ),
          ),
        ),
      ],
    );
  }

  TableRow _buildDepositoRow(CorteCajaViewModel viewModel) {
    return TableRow(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child:
              Text("Depósitos", style: TextStyle(fontWeight: FontWeight.bold)),
        ),
        Row(
          children: [
            Expanded(
              child: Container(
                height: 45,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(5),
                ),
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 12),
                child: Text("\$${viewModel.totalDepositos.toStringAsFixed(2)}"),
              ),
            ),
            IconButton(
              icon: Icon(Icons.add, color: AppTheme.primary),
              onPressed: () {
                setState(() {
                  showDepositoPanel = true;
                  showGastoPanel = false;
                });
              },
            ),
          ],
        ),
      ],
    );
  }

  TableRow _buildGastoRow(CorteCajaViewModel viewModel) {
    return TableRow(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text("Gastos del Día",
              style: TextStyle(fontWeight: FontWeight.bold)),
        ),
        Row(
          children: [
            Expanded(
              child: Container(
                height: 45,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(5),
                ),
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 12),
                child: Text("\$${viewModel.totalGastos.toStringAsFixed(2)}"),
              ),
            ),
            IconButton(
              icon: Icon(Icons.add, color: AppTheme.primary),
              onPressed: () {
                setState(() {
                  showGastoPanel = true;
                  showDepositoPanel = false;
                });
              },
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildDepositoPanel(CorteCajaViewModel viewModel) {
    return tarjeta(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Depósitos",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 10),
          TextField(
            controller: _montoDepositoController,
            decoration: InputDecoration(
              labelText: "Monto del depósito",
              border: OutlineInputBorder(),
            ),
            keyboardType: TextInputType.number,
          ),
          SizedBox(height: 10),
          TextField(
            controller: _descripcionDepositoController,
            decoration: InputDecoration(
              labelText: "Descripción del depósito",
              border: OutlineInputBorder(),
            ),
          ),
          SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {
              double monto =
                  double.tryParse(_montoDepositoController.text) ?? 0;
              String descripcion = _descripcionDepositoController.text;

              viewModel.addDeposito(monto, descripcion, widget.corteCajaId!);
              _montoDepositoController.clear();
              _descripcionDepositoController.clear();
              viewModel.calcularTotalDeposito();

              setState(() {
                showDepositoPanel = false;
              });
            },
            child: Text("Agregar"),
          ),
          SizedBox(height: 20),
          _buildDepositoList(viewModel),
        ],
      ),
    );
  }

  Widget _buildDepositoList(CorteCajaViewModel viewModel) {
    return ListView.builder(
      shrinkWrap: true,
      itemCount: viewModel.depositos.length,
      itemBuilder: (context, index) {
        var deposito = viewModel.depositos[index];
        return ListTile(
          title: Text("\$${deposito.monto?.toStringAsFixed(2)}"),
          subtitle: Text(deposito.descripcion!),
          trailing: IconButton(
            icon: Icon(Icons.delete, color: Colors.red),
            onPressed: () {
              viewModel.quitarDeposito(index);
              viewModel.calcularTotalDeposito();
            },
          ),
        );
      },
    );
  }

  Widget _buildGastoPanel(CorteCajaViewModel viewModel) {
    return tarjeta(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Gastos",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 10),
          TextField(
            controller: _montoGastoController,
            decoration: InputDecoration(
              labelText: "Monto del gasto",
              border: OutlineInputBorder(),
            ),
            keyboardType: TextInputType.number,
          ),
          SizedBox(height: 10),
          TextField(
            controller: _descripcionGastoController,
            decoration: InputDecoration(
              labelText: "Descripción del gasto",
              border: OutlineInputBorder(),
            ),
          ),
          SizedBox(height: 10),
          ElevatedButton(
            onPressed: () {
              double monto = double.tryParse(_montoGastoController.text) ?? 0;
              String descripcion = _descripcionGastoController.text;

              viewModel.addGasto(monto, descripcion, widget.corteCajaId!);
              _montoGastoController.clear();
              _descripcionGastoController.clear();
              viewModel.calcularTotalGasto();

              setState(() {
                showGastoPanel = false;
              });
            },
            child: Text("Agregar"),
          ),
          SizedBox(height: 20),
          _buildGastoList(viewModel),
        ],
      ),
    );
  }

  Widget _buildGastoList(CorteCajaViewModel viewModel) {
    return ListView.builder(
      shrinkWrap: true,
      itemCount: viewModel.gastos.length,
      itemBuilder: (context, index) {
        var gasto = viewModel.gastos[index];
        return ListTile(
          title: Text("\$${gasto.monto?.toStringAsFixed(2)}"),
          subtitle: Text(gasto.descripcion!),
          trailing: IconButton(
            icon: Icon(Icons.delete, color: Colors.red),
            onPressed: () {
              viewModel.quitarGasto(index);
              viewModel.calcularTotalGasto();
            },
          ),
        );
      },
    );
  }

  TableRow _buildCorteFinalRow(CorteCajaViewModel viewModel) {
    return TableRow(
      children: [
        Padding(
          padding: EdgeInsets.all(8.0),
          child: Text("Corte Final",
              style: TextStyle(fontWeight: FontWeight.bold)),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text("\$${viewModel.corteFinal.toStringAsFixed(2)}",
              style: TextStyle(fontWeight: FontWeight.bold)),
        ),
      ],
    );
  }
}
