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 com.vaadin.flow.server.auth.AnonymousAllowed;
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)
@AnonymousAllowed
@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")
                .setAutoWidth(true);

        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::getDescription).setHeader("Descripcion").setWidth("25em");

        grid.addThemeVariants(GridVariant.LUMO_WRAP_CELL_CONTENT);


        // Ajustar tamaño del Grid y Layout
        grid.setSizeFull();
        setSizeFull();
        setPadding(false);
        setMargin(false);
        setSpacing(false);

        add(grid);
        expand(grid);

        // Cargar tickets
        loadTickets();
    }

    private void loadTickets() {
        try {
            List<Ticket> tickets = redmineClient.getTickets(userService.getRedmineUser());
            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 "en curso":
                    span.getElement().getStyle().set("color", "purple");
                    break;
                case "comentarios":
                    span.getElement().getStyle().set("color", "orange");
                    break;
                case "resuelta":
                    span.getElement().getStyle().set("color", "green");
                    break;
                default:
                    span.getElement().getStyle().set("color", "blue");
                    break;
            }
            return span;
        });
    }
}
