package mx.gob.jumapacelaya.views.tickets;

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.orderedlayout.VerticalLayout;
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.services.UserService;
import mx.gob.jumapacelaya.views.MainLayout;

import java.text.SimpleDateFormat;
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.addColumn(Ticket::getDescription).setHeader("Descripcion").setWidth("25em");
        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();
    }

    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","purple");
                    break;
                case "desarrollo":
                    span.getElement().getStyle().set("color","green");
                    break;
                default:
                    span.getElement().getStyle().set("color","blue");
                    break;
            }
            return span;
        });
    }
}
