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.Application;
import mx.gob.jumapacelaya.api.RedmineClient;
import mx.gob.jumapacelaya.api.ServerPrpperties;
import mx.gob.jumapacelaya.models.Ticket;
import mx.gob.jumapacelaya.services.UserService;
import mx.gob.jumapacelaya.views.MainLayout;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Route(value="mytickets", layout = MainLayout.class)
@PermitAll
@PageTitle("Mis tickets")


public class MisTicketsView extends VerticalLayout {


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

    @Autowired
    public MisTicketsView(ServerPrpperties prpperties, RedmineClient redmineClient, UserService userService, Application application) {
        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::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");

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


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

        loadTickets();
        this.application = application;
    }

    // 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");
        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();
    }

    private void loadTickets() {
        try {
            List<Ticket> tickets = redmineClient.getTicketsAuthor(userService.getRedmineUser());
            grid.setItems(tickets);
        } catch (Exception e) {
            e.printStackTrace();
            // Manejo de error al cargar los tickets
        }
    }


    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;
        });
    }
}
