package com.example.application.views.crearnuevoticket;

import com.example.application.api.ApiRedmine;
import com.example.application.views.MainLayout;
import com.nimbusds.jose.shaded.gson.Gson;
import com.nimbusds.jose.shaded.gson.JsonObject;
import com.nimbusds.jose.shaded.gson.JsonParser;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextArea;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.Route;
import jakarta.annotation.security.PermitAll;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Route(value="", layout = MainLayout.class)
@PermitAll
public class CrearnuevoTicketView extends VerticalLayout {

    public CrearnuevoTicketView() {

        //Combo de los tipos de tickets
        ComboBox<String> tipoTickets = new ComboBox<>("Tipo de ticket");
        ApiRedmine api = new ApiRedmine();
        List<String> types = api.getTicketTypes();
        tipoTickets.setItems(types);


        //Campo de texto para el asunto
        TextField asunto = new TextField("Asunto");
        asunto.setWidth("700px");


        //Campo de texto para la descripcion
        TextArea descripcion = new TextArea("Descripcion");
        descripcion.setWidth("1000px");
        descripcion.setHeight("250px");


        //Respuestas Json para verificar posibles errores al enviar los nuevos tickets no visibles en la interfaz
        TextArea jsonOutput = new TextArea("JSON Output");
        jsonOutput.setReadOnly(true);
        TextArea responseField = new TextArea("Response");
        responseField.setReadOnly(true);



        Button createButton = new Button("Enviar ticket", event -> {
            Map<String, String> issueDetails = new HashMap<>();
            issueDetails.put("project_id", "proyecto-de-prueba");
            issueDetails.put("subject", asunto.getValue());
            issueDetails.put("description", descripcion.getValue());

            String response = ApiRedmine.createIssue(issueDetails);
            if (response.startsWith("{\"issue\":")) {
                //Aqui extraigo el numero del ticket de la respuesta json
                JsonObject jsonResponse = JsonParser.parseString(response).getAsJsonObject();
                int issueNumber = jsonResponse.getAsJsonObject("issue").get("id").getAsInt();

                String notificationMessage = "¡Su ticket se ha enviado corrrectamente! Numero de ticket: #" + issueNumber;
                Notification issueNtf = new Notification(notificationMessage, 5000, Notification.Position.MIDDLE);
                issueNtf.addThemeVariants(NotificationVariant.LUMO_SUCCESS);
                issueNtf.open();

                //Limpiando los campos
                asunto.clear();
                descripcion.clear();
                tipoTickets.clear();
            } else {
                Notification errNtf = Notification.show("Ha ocurrido un error al enviar el ticket: "+response, 5000, Notification.Position.MIDDLE);
                errNtf.addThemeVariants(NotificationVariant.LUMO_ERROR);
            }
        });
        createButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

        VerticalLayout fieldsLayout = new VerticalLayout(descripcion);
        fieldsLayout.setAlignItems(Alignment.CENTER);

        HorizontalLayout firstFields = new HorizontalLayout(tipoTickets, asunto);

        VerticalLayout buttonLayout = new VerticalLayout(createButton);
        buttonLayout.setAlignItems(Alignment.END);
        buttonLayout.setMargin(true);

        add(new H2("Crear nuevo ticket"), firstFields, fieldsLayout,buttonLayout/*,jsonOutput,responseField*/);
    }


    //Metodo para convertir un Map a json usando la libreria GSON
    private static String mapToJson(Map<String, String> map) {
        Gson gson = new Gson();
        return gson.toJson(map);
    }
}
