<script setup lang="ts">
import { Job, JobArtifact, JobInfo, JobInfoType, JobRunArtifact } from "@/types/Jobs/job";
import { router } from "@inertiajs/vue3";
import { onMounted, reactive, ref, watch } from "vue";
import Button from "../../ui/button/Button.vue";
import JobFormField from "./JobFormField.vue";
import LoadingSpinner from "@/Components/ui/feedback/spinner/LoadingSpinner.vue";
import { httpApi } from "@/lib/utils";

const props = withDefaults(defineProps<{
    job: Job;
    error?: string;
}>(), {
    error: "",
});

const isSaving = ref(false);
const isTesting = ref(false);

const errorMessage = ref(props.error);

const jobSuccess = ref(true);

function submit() {
    isSaving.value = true;

    if (!testForm()) {
        isTesting.value = false;
        return;
    }

    router.patch("/jobs/" + props.job.id, {
        is_active: isActiveJobInfo.value.value,
        ...props.job.job_infos.reduce((acc, jobInfo) => {
            acc[jobInfo.id] = jobInfo.value;
            return acc;
        }, {} as Record<number, string | boolean>),
    });
    setTimeout(() => {
        isSaving.value = false;
    }, 200);
}

const isActiveJobInfo = ref<JobInfo>({
    id: 0,
    name: "Activer",
    description: "Activer le job",
    value: props.job.is_active,
    is_required: false,
    job_info_type: { name: "checkbox" } as JobInfoType,
} as JobInfo);

async function testJob() {
    isTesting.value = true;

    submit();

    console.log("Testing job", props.job.id);
    let response;
    try {
        response = await httpApi<{ artifact?: JobRunArtifact }>(
            `/jobs/${props.job.id}/test`
        );
        jobSuccess.value = response.artifact?.success ?? false;
    } catch (e) {
        console.error("Testing the job failed : ", e);
        jobSuccess.value = false;
    } finally {
        isTesting.value = false;
    }

    if (response?.artifact) {
        alert(response.artifact.artifacts[0].name + " : " + response.artifact.artifacts[0].content);
    }
}

function testForm(): boolean {
    console.log("Testing the form validity");
    const jobForm = document.querySelector('form[name="jobForm"]') as HTMLFormElement;
    if (jobForm.checkValidity() == false) {
        console.log("Form is not valid");
        if (jobForm.reportValidity) {
            jobForm.reportValidity()
        }
        else {
            errorMessage.value = "Le formulaire n'est pas valide";
        }
        isTesting.value = false;
        return false;
    }
    return true;
}
</script>
<template>
    <form @submit.prevent="submit" class="flex p-3 flex-col gap-4" name="jobForm">
        <JobFormField v-if="job.id != 1" :jobInfo="isActiveJobInfo" />

        <JobFormField
            :jobInfo="jobInfo"
            v-for="jobInfo of job.job_infos"
            v-key="jobInfo.id"
        />

        <Transition>
            <p v-if="errorMessage" class="text-destructive">{{ errorMessage }}</p>
        </Transition>

        <Button
            type="submit"
            variant="secondary"
            :disabled="isSaving || isTesting"
        >
            Enregistrer
            <LoadingSpinner v-if="isSaving" />
        </Button>

        <Button
            variant="outline"
            :disabled="isSaving || isTesting"
            @click.prevent="testJob"
        >
            Tester
            <LoadingSpinner v-if="isTesting" />
        </Button>
    </form>
</template>

<style lang="scss" scoped>
/* we will explain what these classes do next! */
.v-enter-active,
.v-leave-active {
    transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
    opacity: 0;
}
</style>
