<template>
    <div class="flex flex-col gap-6 pt-6">
        <!-- Formulaire d'ajout / édition -->
        <div v-if="isAdmin" class="grid grid-cols-2 gap-x-8 gap-y-3 rounded bg-white p-4 shadow">
            <MalioInputText
                class="col-span-2"
                :label="$t('directory.reports.fields.subject')"
                v-model="draft.subject"
            />
            <MalioSelect
                :label="$t('directory.reports.fields.type')"
                v-model="draft.type"
                :options="typeOptions"
                group-class="w-full"
            />
            <MalioDate
                :label="$t('directory.reports.fields.occurredAt')"
                v-model="draft.occurredAt"
            />
            <MalioInputTextArea
                class="col-span-2"
                :label="$t('directory.reports.fields.body')"
                v-model="draft.body"
            />
            <div class="col-span-2 flex justify-end gap-3">
                <MalioButton
                    v-if="editingId"
                    variant="secondary"
                    button-class="w-auto px-4"
                    :label="$t('common.cancel')"
                    @click="resetDraft"
                />
                <MalioButton
                    button-class="w-auto px-4"
                    :label="editingId ? $t('common.save') : $t('directory.reports.add')"
                    :disabled="!draft.subject"
                    @click="save"
                />
            </div>
        </div>

        <!-- Liste des comptes-rendus -->
        <div v-for="report in reports" :key="report.id" class="rounded border border-neutral-200 p-4">
            <div class="flex items-start justify-between">
                <div>
                    <p class="font-semibold text-neutral-800">{{ report.subject }}</p>
                    <p class="text-xs text-neutral-500">
                        {{ formatDate(report.occurredAt) }} · {{ $t(`directory.reports.types.${report.type}`) }}
                        <span v-if="report.author"> · {{ report.author.username }}</span>
                    </p>
                </div>
                <div v-if="isAdmin" class="flex gap-2">
                    <MalioButtonIcon icon="mdi:pencil-outline" :aria-label="$t('common.edit')" @click="edit(report)" />
                    <MalioButtonIcon icon="mdi:trash-can-outline" button-class="!text-red-600" :aria-label="$t('common.delete')" @click="remove(report.id)" />
                </div>
            </div>
            <p v-if="report.body" class="mt-2 whitespace-pre-wrap text-sm text-neutral-700">{{ report.body }}</p>

            <div class="mt-3 flex flex-col gap-2">
                <ReportDocumentList
                    :documents="report.documents ?? []"
                    :is-admin="isAdmin"
                    @delete="(id) => removeDocument(report, id)"
                />
                <ReportDocumentUpload
                    v-if="isAdmin"
                    :report-id="report.id"
                    @uploaded="reload"
                />
            </div>
        </div>

        <p v-if="!reports.length" class="text-sm text-neutral-400">
            {{ $t('directory.reports.empty') }}
        </p>
    </div>
</template>

<script setup lang="ts">
import type { CommercialReport, CommercialReportWrite, ReportType } from '~/modules/directory/services/dto/commercial-report'
import { useCommercialReportService } from '~/modules/directory/services/commercial-reports'
import { useReportDocumentService } from '~/modules/directory/services/report-documents'

const props = defineProps<{
    owner: { client?: string, prospect?: string }
    isAdmin: boolean
}>()

const { t } = useI18n()
const reportService = useCommercialReportService()
const documentService = useReportDocumentService()

const reports = ref<CommercialReport[]>([])
const editingId = ref<number | null>(null)

function emptyDraft(): CommercialReportWrite {
    return {
        subject: '',
        body: null,
        occurredAt: new Date().toISOString().slice(0, 10),
        type: 'note',
        ...props.owner,
    }
}
const draft = ref<CommercialReportWrite>(emptyDraft())

const typeOptions: { label: string, value: ReportType }[] = [
    { label: t('directory.reports.types.call'), value: 'call' },
    { label: t('directory.reports.types.meeting'), value: 'meeting' },
    { label: t('directory.reports.types.email'), value: 'email' },
    { label: t('directory.reports.types.note'), value: 'note' },
]

function formatDate(iso: string): string {
    return new Date(iso).toLocaleDateString('fr-FR')
}

async function reload(): Promise<void> {
    reports.value = await reportService.getByOwner(props.owner)
}

function resetDraft(): void {
    editingId.value = null
    draft.value = emptyDraft()
}

function edit(report: CommercialReport): void {
    editingId.value = report.id
    draft.value = {
        subject: report.subject,
        body: report.body,
        occurredAt: report.occurredAt.slice(0, 10),
        type: report.type,
        ...props.owner,
    }
}

async function save(): Promise<void> {
    if (editingId.value) {
        await reportService.update(editingId.value, draft.value)
    } else {
        await reportService.create(draft.value)
    }
    resetDraft()
    await reload()
}

async function remove(id: number): Promise<void> {
    await reportService.remove(id)
    await reload()
}

async function removeDocument(report: CommercialReport, id: number): Promise<void> {
    await documentService.remove(id)
    await reload()
}

onMounted(reload)
watch(() => props.owner, reload, { deep: true })
</script>
