package mx.gob.jumapacelaya.ui;

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.html.H3;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.richtexteditor.RichTextEditor;
import com.vaadin.flow.data.renderer.ComponentRenderer;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import jakarta.annotation.security.PermitAll;
import mx.gob.jumapacelaya.api.RedmineClient;
import mx.gob.jumapacelaya.api.ServerProperties;
import mx.gob.jumapacelaya.models.ActividadDiaria;
import mx.gob.jumapacelaya.models.RedmineUser;
import mx.gob.jumapacelaya.models.Ticket;
import mx.gob.jumapacelaya.services.LdapService;
import mx.gob.jumapacelaya.services.UserService;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;


@PermitAll
@PageTitle("Actividades Diarias")
@Route(value = "actdiaria", layout = MainLayout.class)
@CssImport("./themes/sistema-mantenimiento/styles.css")
public class ActDiariaView extends VerticalLayout {

    private final RedmineClient redmineClient;
    private final UserService userService;
    private final Grid<Ticket> grid;


    public ActDiariaView(ServerProperties properties, RedmineClient redmineClient, UserService userService) {
        this.userService = userService;
        this.redmineClient = redmineClient;
        this.grid = new Grid<>(Ticket.class, false);

        // Configuración de columnas del grid
        grid.addColumn(Ticket::getId).setHeader("No.")
                .setAutoWidth(true).setFlexGrow(0).setSortable(true);

        grid.addColumn(Ticket::getType)
                .setHeader("Tipo")
                .setAutoWidth(true);

        grid.addColumn(Ticket::getSubject).setHeader("Asunto")
                .setWidth("25em");

        grid.addColumn(createStatusRender()).setHeader("Estado");

        grid.addColumn(ticket -> {
            Date date = ticket.getDateCreate();
            if (date != null) {
                SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                return formatter.format(date);
            } else {
                return "";
            }
        }).setHeader("Fecha creacion").setAutoWidth(true);

        grid.addColumn(ticket -> {
            LocalDate fechaCierre = ticket.getDateClose();
            if (fechaCierre != null) {
                DateTimeFormatter formatterClose = DateTimeFormatter.ofPattern("dd/MM/yyyy");
                return fechaCierre.format(formatterClose);
            } else {
                return "";
            }
        }).setHeader("Fecha cierre").setAutoWidth(true);

        //grid.addColumn(ticket -> ticket.tiempoEst(ticket.getTrackerId())).setHeader("Tiempo estimado de atencion").setAutoWidth(false);

        grid.addComponentColumn(ticket -> {
            Button btnVer = new Button(new Icon(VaadinIcon.EYE));
            btnVer.addClickListener(event -> showDescription(ticket));
            btnVer.getStyle().set("color", "#A02142");
            return btnVer;
        }).setAutoWidth(true);

        grid.addColumn(buttonTicketComponentRenderer()).setAutoWidth(true);

        grid.addThemeVariants(GridVariant.LUMO_WRAP_CELL_CONTENT);
        grid.getStyle().set("opacity", "0.8");
        grid.setAllRowsVisible(false);
        grid.setSizeFull();

        // Ajustar tamaño del Grid y Layout
        grid.setSizeFull();
        setSizeFull();


        add(grid);
        //expand(grid);
        setMargin(false);

        loadTickets();
    }

    private void loadTickets() {
        try {
            List<Ticket> tickets = redmineClient.getTickets(userService.getRedmineUser(), true);
            List<Ticket> filteredTickets = tickets.stream()
                            .filter(ticket -> ticket.getTrackerId() == 13 || ticket.getTrackerId() == 14)
                                    .toList();
            grid.setItems(filteredTickets);
        } catch (Exception e) {
            e.printStackTrace();
            // Manejo de error al cargar los tickets
        }
    }

    private ComponentRenderer<Span, Ticket> createStatusRender() {
        return new ComponentRenderer<>(ticket -> {
            // Creamos un Span para mostrar el estado
            Span span = new Span(ticket.getStatus());

            // Estilos basados en el estado del ticket
            switch (ticket.getStatus().toLowerCase()) {
                case "análisis":
                    span.getElement().getStyle().set("color","orange");
                    break;
                case "desarrollo":
                    span.getElement().getStyle().set("color","blue");
                    break;
                case "rechazada":
                    span.getElement().getStyle().set("color","red");
                    break;
                case "cerrada":
                    span.getElement().getStyle().set("color","grey");
                    break;
                case "solicitado":
                    span.getElement().getStyle().set("color","purple");
                    break;
                case "qa":
                    span.getElement().getStyle().set("color","#C21DF2");
                    break;
                default:
                    span.getElement().getStyle().set("color","green");
                    break;
            }

            return span;
        });
    }

    public ComponentRenderer<Button, Ticket> buttonTicketComponentRenderer() {
        return new ComponentRenderer<>(ticket -> {
            Button button = new Button(new Icon(VaadinIcon.EDIT) );
            button.getStyle().set("color", "#A02142");
            button.addClickListener(e -> {
                RedmineUser currentUser = userService.getRedmineUser();

                if (ticket.getTrackerId() == 13) {
                    UI.getCurrent().navigate("mantenimiento");
                } else if (ticket.getTrackerId() == 14) {
                    cerrarTicket(ticket, currentUser);
                } else {
                    Notification.show("El ticket no es de tipo Mantenimiento o Actividad.");
                }
            });
            return button;
        });
    }

    public void cerrarTicket(Ticket ticket, RedmineUser user) {
        try {
            //Llamar al metodo para cambiar el estado del ticket
            redmineClient.closeTicket(ticket.getId(), user);
            Notification.show("El ticket " + ticket.getId() + " se ha cerrado exitosamente.", 3000, Notification.Position.MIDDLE)
                    .addThemeVariants(NotificationVariant.LUMO_SUCCESS);

            UI.getCurrent().getPage().executeJs("setTimeout(() => { window.location.reload(); }, 3000);");

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            Notification.show("Error al cerrar el ticket " + ticket.getId());
        }
    }

    // Metodo para mostrar las descripciones en un componente Dialog
    private void showDescription(Ticket ticket) {

        Dialog dialog = new Dialog();
        dialog.getElement().setAttribute("arial-label", "Add note");
        dialog.setMaxHeight("500px");
        dialog.setMaxWidth("1100px");

        RichTextEditor textEditor  = new RichTextEditor();
        textEditor.setValue(ticket.getDescription());
        textEditor.setReadOnly(true);

        Button closeButton = new Button("Cerrar", new Icon(VaadinIcon.CLOSE));
        closeButton.addThemeVariants(ButtonVariant.LUMO_ERROR);
        closeButton.addClickListener(e -> dialog.close());

        HorizontalLayout buttonLayout = new HorizontalLayout(closeButton);
        buttonLayout.setWidthFull();
        buttonLayout.setJustifyContentMode(FlexComponent.JustifyContentMode.END);
        buttonLayout.add(closeButton);

        dialog.add(textEditor, buttonLayout);

        dialog.open();
    }
}
