<template>
    <div class="project">
        <div class="project-header">
            <h2 @click="goToLink">{{ projectName }}</h2>
            <div class="header-actions">
                <div ref="dropdownRef" class="dropdown-wrapper">
                    <button class="contact-button" @click.stop="toggleDropdown">
                        Contact
                    </button>
                    <div
                        v-if="entrepreneurEmails.length > 0"
                        class="contact-dropdown"
                        :class="{ 'dropdown-visible': isDropdownOpen }"
                    >
                        <button @click="contactAll">Contacter tous</button>
                        <button
                            v-for="(email, index) in entrepreneurEmails"
                            :key="index"
                            @click="contactSingle(email)"
                        >
                            {{ email }}
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Toute cette partie est cliquable -->
        <div class="project-body" @click="goToLink">
            <ul>
                <li v-for="(name, index) in listName" :key="index">
                    {{ name }}
                </li>
            </ul>
        </div>
    </div>
</template>

<script setup lang="ts">
import { defineProps, ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { getProjectEntrepreneurs } from "@/services/Apis/Shared.ts";
import UserEntrepreneur from "@/ApiClasses/UserEntrepreneur.ts";

const IS_MOCK_MODE = false;
const dropdownRef = ref<HTMLElement | null>(null);

const props = defineProps<{
    projectName: string;
    listName: string[];
    projectLink: string;
    projectId: number;
}>();

const router = useRouter();

const isDropdownOpen = ref(false);
const entrepreneurEmails = ref<string[]>([]);
const entrepreneurs = ref<UserEntrepreneur[]>([]);

const goToLink = () => {
    if (props.projectLink) {
        router.push(props.projectLink);
    }
};

const toggleDropdown = () => {
    isDropdownOpen.value = !isDropdownOpen.value;
};

const fetchMockEntrepreneurs = () => {
    const mockData = [
        {
            userName: "Doe",
            userSurname: "John",
            primaryMail: "john.doe@example.com",
        },
        {
            userName: "Smith",
            userSurname: "Anna",
            primaryMail: "anna.smith@example.com",
        },
        {
            userName: "Mock",
            userSurname: "User",
            primaryMail: undefined,
        },
    ];

    entrepreneurs.value = mockData.map((item) => new UserEntrepreneur(item));
    entrepreneurEmails.value = entrepreneurs.value
        .map((e) => e.primaryMail)
        .filter((mail): mail is string => !!mail);

    console.log("Mock entrepreneurs chargés :", entrepreneurs.value);
};

const fetchEntrepreneurs = (projectId: number, useMock = false) => {
    if (useMock) {
        fetchMockEntrepreneurs();
    } else {
        getProjectEntrepreneurs(
            projectId,
            (response) => {
                const rawData = response.data as Partial<UserEntrepreneur>[];
                entrepreneurs.value = rawData.map(
                    (item) => new UserEntrepreneur(item)
                );
                entrepreneurEmails.value = entrepreneurs.value
                    .map((e) => e.primaryMail)
                    .filter((mail): mail is string => !!mail);
            },
            (error) => {
                console.error(
                    "Erreur lors de la récupération des entrepreneurs :",
                    error
                );
            }
        );
    }
};

const contactAll = () => {
    const allEmails = entrepreneurEmails.value.join(", ");
    navigator.clipboard
        .writeText(allEmails)
        .then(() => {
            alert("Tous les emails copiés dans le presse-papiers !");
            window.open("https://partage.bordeaux-inp.fr/", "_blank");
        })
        .catch((err) => console.error("Erreur lors de la copie :", err));
};

const contactSingle = (email: string) => {
    navigator.clipboard
        .writeText(email)
        .then(() => {
            alert(`Adresse copiée : ${email}`);
            window.open("https://partage.bordeaux-inp.fr/", "_blank");
        })
        .catch((err) => console.error("Erreur lors de la copie :", err));
};

const handleClickOutside = (event: MouseEvent) => {
    if (
        isDropdownOpen.value &&
        dropdownRef.value &&
        !dropdownRef.value.contains(event.target as Node)
    ) {
        isDropdownOpen.value = false;
    }
};

onMounted(() => {
    fetchEntrepreneurs(props.projectId, IS_MOCK_MODE);
    document.addEventListener("click", handleClickOutside);
});

onBeforeUnmount(() => {
    document.removeEventListener("click", handleClickOutside);
});
</script>

<style scoped>
.project {
    background: linear-gradient(to right, #f8f9fb, #ffffff);
    border: 1px solid #e0e0e0;
    border-radius: 16px;
    padding: 1.5rem;
    margin: 1.5rem 0;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    transition: box-shadow 0.3s ease;
    cursor: pointer;
}

.project:hover {
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
}

.project-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 0.5rem;
}

.project-header h2 {
    font-size: 1.25rem;
    color: #222;
    margin: 0;
    font-weight: 600;
}

.project-buttons {
    display: flex;
    gap: 0.5rem;
}

.contact-btn {
    background-color: #007bff;
    color: #fff;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 8px;
    font-size: 0.9rem;
    font-weight: 500;
    transition:
        background-color 0.2s ease,
        transform 0.2s ease;
}

.contact-btn:hover {
    background-color: #0056b3;
    transform: translateY(-2px);
}

.project-body {
    margin-top: 1rem;
}

.project-body ul {
    list-style-type: disc;
    padding-left: 1.25rem;
    margin: 0;
}

.project-body ul li {
    font-size: 0.95rem;
    color: #555;
    line-height: 1.6;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 30px;
    background-color: #f9f9f9;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.logo {
    height: 50px;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 20px;
    position: relative;
}

.contact-button,
.return-button {
    background-color: #009cde;
    color: white;
    border: none;
    padding: 10px 15px;
    cursor: pointer;
    font-size: 14px;
    border-radius: 5px;
    text-decoration: none;
    transition: background-color 0.2s ease;
    font-family: Arial, sans-serif;
}

.return-button:hover,
.contact-button:hover {
    background-color: #007bad;
}

.contact-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    background-color: #000;
    color: white;
    box-shadow: 0px 4px 8px rgba(255, 255, 255, 0.2);
    border-radius: 8px;
    padding: 10px;
    margin-top: 5px;
    z-index: 1000;
    min-width: 200px;
    display: none;
}

.contact-dropdown button {
    display: block;
    width: 100%;
    padding: 5px;
    text-align: left;
    border: none;
    background: none;
    cursor: pointer;
    color: white;
}

.contact-dropdown button:hover {
    background-color: #009cde;
}

.contact-dropdown.dropdown-visible {
    display: block;
}
</style>
