<template>
    <div>
        <div class="flex items-center justify-between">
            <h1 class="text-2xl font-bold text-neutral-900">Projets</h1>
            <button
                class="rounded-md bg-primary-500 px-4 py-2 text-sm font-semibold text-white hover:bg-secondary-500"
                @click="openCreate"
            >
                + Ajouter un projet
            </button>
        </div>

        <div class="mt-6 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            <div
                v-for="project in projects"
                :key="project.id"
                class="cursor-pointer rounded-lg border border-neutral-200 bg-white shadow-sm transition hover:shadow-md"
                @click="openEdit(project)"
            >
                <div class="h-2 rounded-t-lg" :style="{ backgroundColor: project.color }" />
                <div class="p-4">
                    <h3 class="text-md font-bold text-primary-500">{{ project.name }}</h3>
                    <p class="mt-2 text-sm text-neutral-600 line-clamp-4">
                        {{ project.description ?? '' }}
                    </p>
                </div>
            </div>

            <div
                v-if="projects.length === 0 && !isLoading"
                class="col-span-full py-12 text-center text-neutral-400"
            >
                Aucun projet trouvé.
            </div>
        </div>

        <ProjectDrawer
            v-model="drawerOpen"
            :project="selectedProject"
            :clients="clients"
            @saved="onSaved"
        />
    </div>
</template>

<script setup lang="ts">
import type { Project } from '~/services/dto/project'
import type { Client } from '~/services/dto/client'

useHead({ title: 'Projets' })

const projectService = useProjectService()
const clientService = useClientService()

const projects = ref<Project[]>([])
const clients = ref<Client[]>([])
const isLoading = ref(true)
const drawerOpen = ref(false)
const selectedProject = ref<Project | null>(null)

async function loadData() {
    isLoading.value = true
    try {
        const [p, c] = await Promise.all([
            projectService.getAll(),
            clientService.getAll(),
        ])
        projects.value = p
        clients.value = c
    } finally {
        isLoading.value = false
    }
}

function openCreate() {
    selectedProject.value = null
    drawerOpen.value = true
}

function openEdit(project: Project) {
    selectedProject.value = project
    drawerOpen.value = true
}

async function onSaved() {
    await loadData()
}

onMounted(() => {
    loadData()
})
</script>
