package mx.gob.jumapacelaya.views.tickets;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
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.Span;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
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.ServerPrpperties;
import mx.gob.jumapacelaya.models.Ticket;
import mx.gob.jumapacelaya.models.TicketComment;
import mx.gob.jumapacelaya.services.UserService;
import mx.gob.jumapacelaya.views.MainLayout;

import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Route(value="tickets", layout = MainLayout.class)
@PermitAll
@PageTitle("Todos los tickets")
public class AllTicketsView extends VerticalLayout {

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


    public AllTicketsView(ServerPrpperties prpperties , RedmineClient redmineClient, UserService userService) {
        this.redmineClient = redmineClient;
        this.userService = userService;
        //this.redmineClient = new RedmineClient(prpperties.REDMINE_URL, prpperties.API_KEY);
        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::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");

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

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

        grid.addThemeVariants(GridVariant.LUMO_WRAP_CELL_CONTENT);
        grid.getStyle().set("opacity", "0.8");
        grid.addClassName("vaadin-grid::part(selected-row-cell)");


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

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

        // Cargar tickets
        loadTickets();
    }

    // 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 verNotas = new Button("Comentarios", VaadinIcon.COMMENTS.create());
        verNotas.addClickListener(event -> showComents(ticket));

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

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

        dialog.add(textEditor, buttonLayout);

        dialog.open();
    }

    private void showComents(Ticket ticket) {
        Dialog comentDialog = new Dialog();
        comentDialog.getElement().setAttribute("arial-label", "Comentarios del ticket");
        comentDialog.setMaxHeight("500px");
        comentDialog.setMaxWidth("1100px");

        VerticalLayout layout = new VerticalLayout();
        layout.setPadding(true);
        layout.setSpacing(true);

        // Obtenemos los comentarios desde Proyman
        List<TicketComment> comentarios = redmineClient.getTicketComments(ticket.getId(), userService.getRedmineUser());

        if (comentarios != null && !comentarios.isEmpty()) {
            DateTimeFormatter inputFormatter = DateTimeFormatter.ISO_DATE_TIME;
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");

            for (TicketComment comentario : comentarios) {
                String formattedDate = "Fecha desconocida";

                try {
                    ZonedDateTime dateTime = ZonedDateTime.parse(comentario.getDate(), inputFormatter);
                    formattedDate = dateTime.withZoneSameInstant(ZoneId.systemDefault()).format(outputFormatter);
                } catch (Exception e) {
                    System.err.println("Error al parsear la fecha: " + comentario.getDate());
                }

                VerticalLayout commentLayout = new VerticalLayout();
                commentLayout.getElement().getStyle().set("background", "#DDC9A3");
                commentLayout.getElement().getStyle().set("padding", "10px");
                commentLayout.getElement().getStyle().set("border-radius", "5px");
                commentLayout.getElement().getStyle().set("margin-bottom", "5px");

                Span dateSpan = new Span("📆 " + formattedDate);
                dateSpan.getElement().getStyle().set("font-weight", "bold");
                dateSpan.getElement().getStyle().set("color", "#333");

                Span commentSpan = new Span(comentario.getComment());
                commentSpan.getElement().getStyle().set("margin-top", "5px");

                commentLayout.add(dateSpan, commentSpan);
                layout.add(commentLayout);
            }
        } else {
            layout.add(new Span("No hay comentarios para este ticket."));
        }

        Button closeButton = new Button("Cerrar", VaadinIcon.CLOSE_SMALL.create(), event -> comentDialog.close());
        closeButton.addThemeVariants(ButtonVariant.LUMO_ERROR);

        layout.add(closeButton);
        comentDialog.add(layout);
        comentDialog.open();
    }

    private void loadTickets() {
        try {
            List<Ticket> tickets = redmineClient.getTickets(userService.getRedmineUser(), true);
            if (tickets != null && !tickets.isEmpty()) {
                grid.setItems(tickets);
            } else {
                System.out.println("No se pudieron obtener tickets, la lista de tickets es null o está vacía");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Ocurrió un error al cargar los tickets: " + e.getMessage());
        }
    }

    private ComponentRenderer<Span, Ticket> createStatusRender() {
        return new ComponentRenderer<>(ticket -> {
            Span span = new Span(ticket.getStatus());
            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;
                default:
                    span.getElement().getStyle().set("color","green");
                    break;
            }
            return span;
        });
    }
}
