package examenes.examen20250321.vista;

import examenes.examen20250321.controlador.ControladorInquilino;
import examenes.examen20250321.controlador.ControladorLocalidad;
import examenes.examen20250321.controlador.ControladorMorosidad;
import examenes.examen20250321.controlador.ControladorVivienda;
import examenes.examen20250321.modelo.Inquilino;
import examenes.examen20250321.modelo.Localidad;
import examenes.examen20250321.modelo.Morosidad;
import examenes.examen20250321.modelo.Vivienda;

import java.awt.EventQueue;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Objects;

public class GestionAlquiler extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel contentPane;

    private JComboBox<Localidad> comboBoxLocalidad;
    private JComboBox<Vivienda> comboBoxVivienda;
    private JComboBox<Morosidad> comboBoxMorosidad;


    private JTextField textFieldFiltroVivienda;
    private JTextField textFieldDni;
    private JTextField textFieldId;
    private JTextField textFieldNombreCompleto;
    private JTextField textFieldFechaInicio;
    private JCheckBox checkBoxAlquiler;
    private JTextField textFieldFechaFin;
    private JTextField textFieldCuotaMensualidad;


    private JLabel labelCalculoConIva;


    private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");


    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GestionAlquiler frame = new GestionAlquiler();
                    frame.cargarLocalidad();
                    frame.filtrarVivienda();
                    frame.cargarMorosidad();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public GestionAlquiler() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 500, 480);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.NORTH);
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        JLabel lblNewLabel = new JLabel("Gestión de alquileres");
        lblNewLabel.setFont(new Font("Lucida Grande", Font.BOLD, 16));
        lblNewLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(lblNewLabel);

        JPanel panel_1 = new JPanel();
        panel.add(panel_1);
        GridBagLayout gbl_panel_1 = new GridBagLayout();
        gbl_panel_1.columnWidths = new int[]{0, 0, 0, 0};
        gbl_panel_1.rowHeights = new int[]{0, 0, 0, 0};
        gbl_panel_1.columnWeights = new double[]{1.0, 1.0, 0.0, Double.MIN_VALUE};
        gbl_panel_1.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
        panel_1.setLayout(gbl_panel_1);

        JLabel lblNewLabel_1 = new JLabel("Localidad:");
        GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
        gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
        gbc_lblNewLabel_1.gridx = 0;
        gbc_lblNewLabel_1.gridy = 0;
        panel_1.add(lblNewLabel_1, gbc_lblNewLabel_1);

        comboBoxLocalidad = new JComboBox<>();
        GridBagConstraints gbc_comboBox = new GridBagConstraints();
        gbc_comboBox.gridwidth = 2;
        gbc_comboBox.insets = new Insets(0, 0, 5, 0);
        gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
        gbc_comboBox.gridx = 1;
        gbc_comboBox.gridy = 0;
        panel_1.add(comboBoxLocalidad, gbc_comboBox);

        JLabel lblNewLabel_2 = new JLabel("Filtro de vivienda:");
        GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
        gbc_lblNewLabel_2.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 5);
        gbc_lblNewLabel_2.gridx = 0;
        gbc_lblNewLabel_2.gridy = 1;
        panel_1.add(lblNewLabel_2, gbc_lblNewLabel_2);

        textFieldFiltroVivienda = new JTextField();
        GridBagConstraints gbc_textField = new GridBagConstraints();
        gbc_textField.insets = new Insets(0, 0, 5, 5);
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 1;
        panel_1.add(textFieldFiltroVivienda, gbc_textField);
        textFieldFiltroVivienda.setColumns(10);

        JButton btnNewButton = new JButton("Filtrar viviendas");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                filtrarVivienda();
            }
        });
        GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
        gbc_btnNewButton.insets = new Insets(0, 0, 5, 0);
        gbc_btnNewButton.gridx = 2;
        gbc_btnNewButton.gridy = 1;
        panel_1.add(btnNewButton, gbc_btnNewButton);

        JLabel lblNewLabel_3 = new JLabel("Vivienda:");
        GridBagConstraints gbc_lblNewLabel_3 = new GridBagConstraints();
        gbc_lblNewLabel_3.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_3.insets = new Insets(0, 0, 0, 5);
        gbc_lblNewLabel_3.gridx = 0;
        gbc_lblNewLabel_3.gridy = 2;
        panel_1.add(lblNewLabel_3, gbc_lblNewLabel_3);

        comboBoxVivienda = new JComboBox<>();
        comboBoxVivienda.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                cargarInquilinoEnPantalla();
            }
        });
        GridBagConstraints gbc_comboBox_1 = new GridBagConstraints();
        gbc_comboBox_1.gridwidth = 2;
        gbc_comboBox_1.insets = new Insets(0, 0, 0, 5);
        gbc_comboBox_1.fill = GridBagConstraints.HORIZONTAL;
        gbc_comboBox_1.gridx = 1;
        gbc_comboBox_1.gridy = 2;
        panel_1.add(comboBoxVivienda, gbc_comboBox_1);

        JPanel panel_2 = new JPanel();
        contentPane.add(panel_2, BorderLayout.CENTER);
        panel_2.setLayout(new BoxLayout(panel_2, BoxLayout.Y_AXIS));

        JLabel lblNewLabel_4 = new JLabel("Datos del inquilino");
        lblNewLabel_4.setFont(new Font("Lucida Grande", Font.BOLD, 16));
        lblNewLabel_4.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel_2.add(lblNewLabel_4);

        JPanel panel_1_1 = new JPanel();
        panel_2.add(panel_1_1);
        GridBagLayout gbl_panel_1_1 = new GridBagLayout();
        gbl_panel_1_1.columnWidths = new int[]{0, 0, 0, 0};
        gbl_panel_1_1.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        gbl_panel_1_1.columnWeights = new double[]{1.0, 1.0, 0.0, Double.MIN_VALUE};
        gbl_panel_1_1.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
        panel_1_1.setLayout(gbl_panel_1_1);

        JLabel lblNewLabel_1_1 = new JLabel("Id:");
        GridBagConstraints gbc_lblNewLabel_1_1 = new GridBagConstraints();
        gbc_lblNewLabel_1_1.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_1_1.insets = new Insets(0, 0, 5, 5);
        gbc_lblNewLabel_1_1.gridx = 0;
        gbc_lblNewLabel_1_1.gridy = 0;
        panel_1_1.add(lblNewLabel_1_1, gbc_lblNewLabel_1_1);

        textFieldId = new JTextField();
        textFieldId.setEnabled(false);
        GridBagConstraints gbc_textField_2 = new GridBagConstraints();
        gbc_textField_2.gridwidth = 2;
        gbc_textField_2.insets = new Insets(0, 0, 5, 0);
        gbc_textField_2.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField_2.gridx = 1;
        gbc_textField_2.gridy = 0;
        panel_1_1.add(textFieldId, gbc_textField_2);
        textFieldId.setColumns(10);

        JLabel lblNewLabel_2_1 = new JLabel("DNI:");
        GridBagConstraints gbc_lblNewLabel_2_1 = new GridBagConstraints();
        gbc_lblNewLabel_2_1.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_2_1.insets = new Insets(0, 0, 5, 5);
        gbc_lblNewLabel_2_1.gridx = 0;
        gbc_lblNewLabel_2_1.gridy = 1;
        panel_1_1.add(lblNewLabel_2_1, gbc_lblNewLabel_2_1);

        textFieldDni = new JTextField();
        textFieldDni.setColumns(10);
        GridBagConstraints gbc_textField_1 = new GridBagConstraints();
        gbc_textField_1.gridwidth = 2;
        gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField_1.insets = new Insets(0, 0, 5, 0);
        gbc_textField_1.gridx = 1;
        gbc_textField_1.gridy = 1;
        panel_1_1.add(textFieldDni, gbc_textField_1);

        JLabel lblNewLabel_3_1 = new JLabel("Nombre completo:");
        GridBagConstraints gbc_lblNewLabel_3_1 = new GridBagConstraints();
        gbc_lblNewLabel_3_1.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_3_1.insets = new Insets(0, 0, 5, 5);
        gbc_lblNewLabel_3_1.gridx = 0;
        gbc_lblNewLabel_3_1.gridy = 2;
        panel_1_1.add(lblNewLabel_3_1, gbc_lblNewLabel_3_1);

        textFieldNombreCompleto = new JTextField();
        GridBagConstraints gbc_textField_3 = new GridBagConstraints();
        gbc_textField_3.gridwidth = 2;
        gbc_textField_3.insets = new Insets(0, 0, 5, 0);
        gbc_textField_3.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField_3.gridx = 1;
        gbc_textField_3.gridy = 2;
        panel_1_1.add(textFieldNombreCompleto, gbc_textField_3);
        textFieldNombreCompleto.setColumns(10);

        JLabel lblNewLabel_10 = new JLabel("Fecha inicio:");
        GridBagConstraints gbc_lblNewLabel_10 = new GridBagConstraints();
        gbc_lblNewLabel_10.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_10.insets = new Insets(0, 0, 5, 5);
        gbc_lblNewLabel_10.gridx = 0;
        gbc_lblNewLabel_10.gridy = 3;
        panel_1_1.add(lblNewLabel_10, gbc_lblNewLabel_10);

        textFieldFechaInicio = new JTextField();
        GridBagConstraints gbc_textFieldFechaInicio = new GridBagConstraints();
        gbc_textFieldFechaInicio.gridwidth = 2;
        gbc_textFieldFechaInicio.insets = new Insets(0, 0, 5, 5);
        gbc_textFieldFechaInicio.fill = GridBagConstraints.HORIZONTAL;
        gbc_textFieldFechaInicio.gridx = 1;
        gbc_textFieldFechaInicio.gridy = 3;
        panel_1_1.add(textFieldFechaInicio, gbc_textFieldFechaInicio);
        textFieldFechaInicio.setColumns(10);

        checkBoxAlquiler = new JCheckBox("Alquiler en activo");
        checkBoxAlquiler.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                alternarFechaFin();
            }
        });
        GridBagConstraints gbc_chckbxNewCheckBox = new GridBagConstraints();
        gbc_chckbxNewCheckBox.gridwidth = 2;
        gbc_chckbxNewCheckBox.anchor = GridBagConstraints.WEST;
        gbc_chckbxNewCheckBox.insets = new Insets(0, 0, 5, 0);
        gbc_chckbxNewCheckBox.gridx = 1;
        gbc_chckbxNewCheckBox.gridy = 4;
        panel_1_1.add(checkBoxAlquiler, gbc_chckbxNewCheckBox);

        JLabel lblNewLabel_5 = new JLabel("Fecha de fin:");
        GridBagConstraints gbc_lblNewLabel_5 = new GridBagConstraints();
        gbc_lblNewLabel_5.insets = new Insets(0, 0, 5, 5);
        gbc_lblNewLabel_5.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_5.gridx = 0;
        gbc_lblNewLabel_5.gridy = 5;
        panel_1_1.add(lblNewLabel_5, gbc_lblNewLabel_5);

        textFieldFechaFin = new JTextField();
        GridBagConstraints gbc_textField_4 = new GridBagConstraints();
        gbc_textField_4.insets = new Insets(0, 0, 5, 0);
        gbc_textField_4.gridwidth = 2;
        gbc_textField_4.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField_4.gridx = 1;
        gbc_textField_4.gridy = 5;
        panel_1_1.add(textFieldFechaFin, gbc_textField_4);
        textFieldFechaFin.setColumns(10);

        JLabel lblNewLabel_6 = new JLabel("Tipo de morosidad:");
        GridBagConstraints gbc_lblNewLabel_6 = new GridBagConstraints();
        gbc_lblNewLabel_6.insets = new Insets(0, 0, 5, 5);
        gbc_lblNewLabel_6.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_6.gridx = 0;
        gbc_lblNewLabel_6.gridy = 6;
        panel_1_1.add(lblNewLabel_6, gbc_lblNewLabel_6);

        comboBoxMorosidad = new JComboBox<>();
        GridBagConstraints gbc_comboBox_2 = new GridBagConstraints();
        gbc_comboBox_2.gridwidth = 2;
        gbc_comboBox_2.insets = new Insets(0, 0, 5, 0);
        gbc_comboBox_2.fill = GridBagConstraints.HORIZONTAL;
        gbc_comboBox_2.gridx = 1;
        gbc_comboBox_2.gridy = 6;
        panel_1_1.add(comboBoxMorosidad, gbc_comboBox_2);

        JLabel lblNewLabel_7 = new JLabel("Cuota mensual (€):");
        GridBagConstraints gbc_lblNewLabel_7 = new GridBagConstraints();
        gbc_lblNewLabel_7.insets = new Insets(0, 0, 5, 5);
        gbc_lblNewLabel_7.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_7.gridx = 0;
        gbc_lblNewLabel_7.gridy = 7;
        panel_1_1.add(lblNewLabel_7, gbc_lblNewLabel_7);

        textFieldCuotaMensualidad = new JTextField();
        GridBagConstraints gbc_textField_5 = new GridBagConstraints();
        gbc_textField_5.gridwidth = 2;
        gbc_textField_5.insets = new Insets(0, 0, 5, 0);
        gbc_textField_5.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField_5.gridx = 1;
        gbc_textField_5.gridy = 7;
        panel_1_1.add(textFieldCuotaMensualidad, gbc_textField_5);
        textFieldCuotaMensualidad.setColumns(10);

        JLabel lblNewLabel_8 = new JLabel("Total mensual (IVA incluido) €:");
        GridBagConstraints gbc_lblNewLabel_8 = new GridBagConstraints();
        gbc_lblNewLabel_8.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_8.insets = new Insets(0, 0, 0, 5);
        gbc_lblNewLabel_8.gridx = 0;
        gbc_lblNewLabel_8.gridy = 8;
        panel_1_1.add(lblNewLabel_8, gbc_lblNewLabel_8);

        labelCalculoConIva = new JLabel("0 €");
        GridBagConstraints gbc_lblNewLabel_9 = new GridBagConstraints();
        gbc_lblNewLabel_9.gridwidth = 2;
        gbc_lblNewLabel_9.gridx = 1;
        gbc_lblNewLabel_9.gridy = 8;
        panel_1_1.add(labelCalculoConIva, gbc_lblNewLabel_9);

        JButton btnNewButton_1 = new JButton("Guardar cambios");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                guardarCambios();
            }
        });
        btnNewButton_1.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel_2.add(btnNewButton_1);
    }

    private void cargarLocalidad() {
        List<Localidad> localidades = ControladorLocalidad.getAllLocalidades();

        for (Localidad l : localidades) {
            comboBoxLocalidad.addItem(l);
        }
    }

    private void cargarMorosidad() {
        List<Morosidad> morosidades = ControladorMorosidad.getAllMorosidades();

        for (Morosidad m : morosidades) {
            comboBoxMorosidad.addItem(m);
        }
    }

    private void filtrarVivienda() {
        Localidad l = (Localidad) comboBoxLocalidad.getSelectedItem();
        String textoFilrar = textFieldFiltroVivienda.getText();

        List<Vivienda> viviendas = ControladorVivienda.getAllViviendasFromLocalidadYFiltrado(l, textoFilrar);

        comboBoxVivienda.removeAllItems();

        for (Vivienda v : viviendas) {
            comboBoxVivienda.addItem(v);
        }
    }

    private void cargarInquilinoEnPantalla() {
        Vivienda v = (Vivienda) comboBoxVivienda.getSelectedItem();
        if (v != null) {
            Inquilino inquilino = ControladorInquilino.obtenerInquilino(v);
            textFieldId.setText("" + inquilino.getId());
            textFieldDni.setText(inquilino.getDni());
            textFieldNombreCompleto.setText(inquilino.getNombreCompleto());
            textFieldFechaInicio.setText(sdf.format(inquilino.getFechaInicioAlquiler()));
            if (inquilino.getFechaFinAlquiler() == null) {
                textFieldFechaFin.setText("");
                checkBoxAlquiler.setSelected(true);
                textFieldFechaFin.setEnabled(false);
            } else {
                textFieldFechaFin.setText(sdf.format(inquilino.getFechaFinAlquiler()));
                checkBoxAlquiler.setSelected(false);
                textFieldFechaFin.setEnabled(true);
            }

            for (int i = 0; i < comboBoxMorosidad.getItemCount(); i++) {
                if (comboBoxMorosidad.getItemAt(i).getId() == inquilino.getIdTipoMorosidad()) {
                    comboBoxMorosidad.setSelectedIndex(i);
                    break;
                }
            }

            textFieldCuotaMensualidad.setText("" + inquilino.getCuotaMensual());
            labelCalculoConIva.setText((inquilino.getCuotaMensual() * 1.21) + " €");
        }
    }

    private void alternarFechaFin() {
        if (checkBoxAlquiler.isSelected()) {
            textFieldFechaFin.setText("");
            textFieldFechaFin.setEnabled(false);
        } else {
            textFieldFechaFin.setEnabled(true);
        }

    }

    private void guardarCambios() {
        Inquilino inquilino = new Inquilino();

        inquilino.setId(Integer.parseInt(textFieldId.getText()));
        inquilino.setDni(textFieldDni.getText());

        if (Objects.equals(textFieldNombreCompleto.getText(), "")) {
            JOptionPane.showMessageDialog(this, "No puedes dejar un nombre vacío");
            return;
        } else inquilino.setNombreCompleto(textFieldNombreCompleto.getText());

        try {
            inquilino.setFechaInicioAlquiler(sdf.parse(textFieldFechaInicio.getText()));
        } catch (ParseException e) {
            JOptionPane.showMessageDialog(this, "Tiene que haber fecha de inicio y tiene que estar en este formato: dd/MM/yyyy");
            //throw new RuntimeException(e);
            return;
        }

        if (!checkBoxAlquiler.isSelected()) {
            try {
                inquilino.setFechaFinAlquiler(sdf.parse(textFieldFechaFin.getText()));
            } catch (ParseException e) {
                JOptionPane.showMessageDialog(this, "Si el alquiler no está activo tiene que haber fecha de fin y tiene que estar en este formato: dd/MM/yyyy");
                //throw new RuntimeException(e);
                return;
            }
        }

        inquilino.setIdTipoMorosidad(((Morosidad) comboBoxMorosidad.getSelectedItem()).getId());
        inquilino.setCuotaMensual(Float.parseFloat(textFieldCuotaMensualidad.getText()));
        inquilino.setIdVivienda(((Vivienda) comboBoxVivienda.getSelectedItem()).getId());

        if (ControladorInquilino.guardarInquilino(inquilino) > 0) {
            JOptionPane.showMessageDialog(this, "Se ha guardado correctamente el cambio");
        } else {
            JOptionPane.showMessageDialog(this, "No se ha podido guardar el cambio");
        }

    }
}
