document.addEventListener("DOMContentLoaded", function () {
    let timers = {};
    let intervalIds = {};
    let startTimes = {};

    const savedTimers = JSON.parse(localStorage.getItem("timers")) || {};
    const savedStartTimes =
        JSON.parse(localStorage.getItem("startTimes")) || {};
    const savedIntervalIds =
        JSON.parse(localStorage.getItem("intervalIds")) || {};

    timers = savedTimers;
    startTimes = savedStartTimes;
    intervalIds = savedIntervalIds;

    function updateTimerDisplay(chamadoId) {
        if (timers[chamadoId] !== undefined && !isNaN(timers[chamadoId])) {
            document.getElementById(`timer_${chamadoId}`).innerText =
                formatTime(timers[chamadoId]);
        } else {
            document.getElementById(`timer_${chamadoId}`).innerText = "00:00";
        }
    }

    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${String(minutes).padStart(
            2,
            "0"
        )}:${String(secs).padStart(2, "0")}`;
    }

    function startTimer(chamadoId) {
        if (!startTimes[chamadoId]) {
            startTimes[chamadoId] = new Date().getTime();
        }

        intervalIds[chamadoId] = setInterval(() => {
            const currentTime = new Date().getTime();
            timers[chamadoId] = Math.floor(
                (currentTime - startTimes[chamadoId]) / 1000
            );
            updateTimerDisplay(chamadoId);

            localStorage.setItem("timers", JSON.stringify(timers));
            localStorage.setItem("startTimes", JSON.stringify(startTimes));
            localStorage.setItem("intervalIds", JSON.stringify(intervalIds));
        }, 1000);
    }

    function stopTimer(chamadoId) {
        clearInterval(intervalIds[chamadoId]);

        intervalIds[chamadoId] = null;

        const elapsedTimeInSeconds = timers[chamadoId];
        const horaInicio = new Date(
            startTimes[chamadoId] - new Date().getTimezoneOffset() * 60000
        )
            .toISOString()
            .slice(0, 19);
        const horaFim = new Date(
            startTimes[chamadoId] +
                elapsedTimeInSeconds * 1000 -
                new Date().getTimezoneOffset() * 60000
        )
            .toISOString()
            .slice(0, 19);

        const modal = document.getElementById("modal");
        modal.dataset.chamadoId = chamadoId;

        openModal(chamadoId, horaInicio, horaFim);

        localStorage.setItem("timers", JSON.stringify(timers));
        localStorage.setItem("startTimes", JSON.stringify(startTimes));
    }

    document.querySelectorAll(".play-btn").forEach((button) => {
        const chamadoId = button.id.split("_")[1];

        if (startTimes[chamadoId]) {
            startTimer(chamadoId);
            button.classList.add("hidden");
            document
                .getElementById(`stopBtn_${chamadoId}`)
                .classList.remove("hidden");
        }

        button.addEventListener("click", function () {
            startTimes[chamadoId] = new Date().getTime();
            startTimer(chamadoId);
            this.classList.add("hidden");
            document
                .getElementById(`stopBtn_${chamadoId}`)
                .classList.remove("hidden");
        });
    });

    document.querySelectorAll(".stop-btn").forEach((button) => {
        const chamadoId = button.id.split("_")[1];

        button.addEventListener("click", function () {
            stopTimer(chamadoId);
            this.classList.add("hidden");
            document
                .getElementById(`startBtn_${chamadoId}`)
                .classList.remove("hidden");
        });
    });

    function openModal(chamadoId, horaInicio, horaFim) {
        const modal = document.getElementById("modal");
        modal.classList.remove("hidden");
        const submitButton = document.getElementById("submitPause");
        const cancelButton = document.getElementById("cancelPause");

        submitButton.onclick = function (event) {
            event.preventDefault();
            submitButton.disabled = true;
            cancelButton.disabled = true;

            const modal = document.getElementById("modal");
            const chamadoId = modal.dataset.chamadoId || "";
            this.disabled = true;

            if (!chamadoId) {
                console.error("Erro: chamadoId está indefinido!");
                return;
            }

            const justificativa =
                document.getElementById("justificativa").value || "";
            const status = document.getElementById("status").value || "";
            const motivoId = document.getElementById("motivo").value || 0;

            const atividadeId =
                document.getElementById("atividadeId").value || "";
            const tramiteSolucao =
                document.getElementById("tramiteSolucao").checked;

            const dataAtual = new Date();
            const deslocamento = dataAtual.getTimezoneOffset() * 60000;
            const dataLocal = new Date(dataAtual.getTime() - deslocamento);
            const dataISO = dataLocal.toISOString();

            const horaInicio = startTimes[chamadoId]
                ? new Date(startTimes[chamadoId] - deslocamento)
                      .toISOString()
                      .slice(0, 19)
                : "";

            if (!horaInicio) {
                console.error("Erro: horaInicio está indefinida!");
                return;
            }

            const requestData = {
                tramiteId: 0,
                chamadoId: chamadoId,
                status: status,
                origem: "Normal",
                motivoId: motivoId,
                atividadeId: atividadeId,
                data: dataISO,
                horaInicio: horaInicio,
                horaFim: horaFim,
                descricao: justificativa,
                tramiteSolucao: tramiteSolucao,
            };

            fetch("/tramite", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": document
                        .querySelector('meta[name="csrf-token"]')
                        .getAttribute("content"),
                },
                body: JSON.stringify(requestData),
            })
                .then((response) => response.json())
                .then((data) => {
                    clearInterval(intervalIds[chamadoId]);

                    delete timers[chamadoId];
                    delete startTimes[chamadoId];
                    delete intervalIds[chamadoId];

                    localStorage.setItem("timers", JSON.stringify(timers));
                    localStorage.setItem(
                        "startTimes",
                        JSON.stringify(startTimes)
                    );
                    localStorage.setItem(
                        "intervalIds",
                        JSON.stringify(intervalIds)
                    );

                    document
                        .getElementById(`stopBtn_${chamadoId}`)
                        .classList.add("hidden");
                    document
                        .getElementById(`startBtn_${chamadoId}`)
                        .classList.remove("hidden");

                    Toastify({
                        text: "📤Eviando seu trâmite....",
                        duration: 3000,
                        gravity: "bottom",
                        position: "center",
                        backgroundColor: "#FF5A1F",
                    }).showToast();

                    setTimeout(() => {
                        modal.classList.add("hidden");

                        submitButton.disabled = false;
                        cancelButton.disabled = false;

                        location.reload();
                    }, 3000);
                })
                .catch((error) => {
                    console.error("Erro ao enviar os dados:", error);
                    submitButton.disabled = false;
                    cancelButton.disabled = false;
                    if (justificativa.trim() === "") {
                        Toastify({
                            text: "Campo de justificativa não pode ser vazio",
                            duration: 3000,
                            gravity: "bottom",
                            position: "center",
                            backgroundColor: "#FF5A1F",
                        }).showToast();
                    }
                });
        };
    }

    document.getElementById("cancelPause").onclick = function () {
        const modal = document.getElementById("modal");
        modal.classList.add("hidden");

        const chamadoId = modal.dataset.chamadoId;

        if (!chamadoId || !startTimes[chamadoId]) {
            console.error(
                "Erro: chamadoId inválido ou tempo de início não encontrado."
            );
            return;
        }

        if (!intervalIds[chamadoId]) {
            startTimer(chamadoId);
        }

        document
            .getElementById(`stopBtn_${chamadoId}`)
            .classList.remove("hidden");
        document
            .getElementById(`startBtn_${chamadoId}`)
            .classList.add("hidden");
    };

    Object.keys(savedTimers).forEach((chamadoId) => {
        if (startTimes[chamadoId]) {
            const currentTime = new Date().getTime();
            const elapsedTime = Math.floor(
                (currentTime - startTimes[chamadoId]) / 1000
            );
            timers[chamadoId] = elapsedTime;

            updateTimerDisplay(chamadoId);
            startTimer(chamadoId);
        }
    });

    const statusSelect = document.getElementById("status");
    const motivoContainer = document.getElementById("motivoContainer");

    statusSelect.addEventListener("change", function () {
        if (statusSelect.value === "AguardandoTerceiro") {
            motivoContainer.classList.remove("hidden"); // Mostra o campo
        } else {
            motivoContainer.classList.add("hidden"); // Oculta o campo
        }
    });
});
