<template>
    <div>
        <header>
            <HeaderCanvas :project-id="projectId" :is-admin="isAdmin_" />
        </header>
    </div>
    <div>
        <h1 class="page-title">PAGE CANVAS</h1>
        <p class="canvas-help-text">
            Cliquez sur un champ du tableau pour afficher son contenu en détail
            ci-dessous.
        </p>
        <LeanCanvas :project-id="projectId" :is-admin="isAdmin_" />
        <div class="info-box">
            <p v-if="admin">
                Responsable :
                <strong>{{ admin.userName }} {{ admin.userSurname }}</strong
                ><br />
                Contact :
                <a :href="`mailto:${admin.primaryMail}`">{{
                    admin.primaryMail
                }}</a>
                |
                <a :href="`tel:${admin.phoneNumber}`">{{
                    admin.phoneNumber
                }}</a>
            </p>
            <p v-else>Chargement des informations du responsable...</p>
        </div>
    </div>
</template>

<script setup lang="ts">
import HeaderCanvas from "../components/canvas/HeaderCanvas.vue";
import LeanCanvas from "../components/canvas/LeanCanvas.vue";
import { ref, onMounted } from "vue";
import { isAdmin } from "@/services/tools.ts";
import { getProjectAdmin } from "@/services/Apis/Shared.ts";
import UserAdmin from "@/ApiClasses/UserAdmin.ts";
import type { AxiosResponse, AxiosError } from "axios";
import { getEntrepreneurProjectId } from "@/services/Apis/Entrepreneurs";

const IS_MOCK_MODE = false;
const isAdmin_ = isAdmin();
const admin = ref<UserAdmin | null>(null);
const projectId = ref<number>(-1);

const mockAdminData = new UserAdmin({
    idUser: 1,
    userSurname: "ALAMI",
    userName: "Adnane",
    primaryMail: "mock.admin@example.com",
    secondaryMail: "admin.backup@example.com",
    phoneNumber: "0600000000",
});

function getProjectId(): Promise<number> {
    return new Promise((resolve) => {
        getEntrepreneurProjectId(
            (response) => {
                const projectIds = response.data;
                if (!Array.isArray(projectIds) || projectIds.length === 0) {
                    console.warn("Aucun projet trouvé pour cet entrepreneur.");
                    resolve(-1);
                    return;
                }
                resolve(projectIds[0]);
            },
            (error) => {
                console.error("Erreur API :", error);
                resolve(-1);
            }
        );
    });
}

async function fetchProjectId() {
    try {
        projectId.value = await getProjectId();
        console.log("ProjectId :", projectId.value);
    } catch (error) {
        console.error("Erreur lors de la récupération du projet :", error);
    }
}

const fetchAdminData = (projectId: number, useMock = IS_MOCK_MODE) => {
    if (useMock) {
        console.log("Utilisation des données mockées pour l'administrateur");
        admin.value = mockAdminData;
        return;
    }

    if (projectId === -1) {
        admin.value = new UserAdmin({
            idUser: 0,
            userSurname: "Erreur",
            userName: "Chargement",
            primaryMail: "N/A",
            secondaryMail: "N/A",
            phoneNumber: "N/A",
        });
        return;
    }

    getProjectAdmin(
        projectId,
        (response: AxiosResponse) => {
            admin.value = new UserAdmin(response.data);
        },
        (error: AxiosError) => {
            console.error(
                "Erreur lors de la récupération des données de l'administrateur :",
                error
            );

            admin.value = new UserAdmin({
                idUser: 0,
                userSurname: "Erreur",
                userName: "Chargement",
                primaryMail: "N/A",
                secondaryMail: "N/A",
                phoneNumber: "N/A",
            });
        }
    );
};

onMounted(() => {
    fetchProjectId();
    fetchAdminData(projectId.value);
});
</script>

<style scoped>
.page-title {
    text-align: center;
    font-size: 2.5rem;
    margin-top: 20px;
}

.canvas-help-text {
    text-align: center;
    font-size: 0.7rem;
    color: #666;
}

.info-box {
    background-color: #f9f9f9;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    font-family: Arial, sans-serif;
    width: 30%;
    max-width: 600px;
    margin: 20px auto;
}

.info-box p {
    font-size: 16px;
    line-height: 1.5;
    color: #333;
}

.info-box a {
    color: #007bff;
    text-decoration: none;
}

.info-box a:hover {
    text-decoration: underline;
}

.canvas-help-text {
    margin-top: 20px;
    margin-bottom: -10px;
}

div:last-child {
    margin-bottom: 60px;
}
</style>
