<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import { FolderOpen } from 'lucide-vue-next';
import BulkActionBar from '@/components/declarations/BulkActionBar.vue';
import NudgePopover from '@/components/declarations/NudgePopover.vue';
import Heading from '@/components/Heading.vue';
import Pagination from '@/components/Pagination.vue';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import AppLayout from '@/layouts/AppLayout.vue';

type Declaration = {
    id: number;
    title: string;
    type: string;
    client_name: string;
    assignee_name: string | null;
    status: string;
    due_date: string | null;
    showUrl: string;
    editUrl: string;
    destroyUrl: string;
    nudgeUrl: string | null;
};

type PaginatedData<T> = {
    data: T[];
    from: number | null;
    to: number | null;
    total: number;
    current_page: number;
    last_page: number;
    per_page: number;
    path: string;
    first_page_url: string;
    prev_page_url: string | null;
    next_page_url: string | null;
    last_page_url: string;
};

type Props = {
    declarations: PaginatedData<Declaration>;
    createUrl: string;
    workspaceName: string;
    canCreate: boolean;
    canEdit: boolean;
    canDelete: boolean;
    canNudge: boolean;
    bulkNotifyUrl?: string;
    canBulkNotify?: boolean;
};

const props = defineProps<Props>();

const selectedIds = ref<number[]>([]);

watch(() => props.declarations.data, () => {
    selectedIds.value = [];
});

const eligibleDeclarations = computed(() =>
    props.declarations.data.filter(
        (d) => d.status === 'en_attente_client',
    ),
);

const allEligibleSelected = computed(
    () =>
        eligibleDeclarations.value.length > 0 &&
        eligibleDeclarations.value.every((d) =>
            selectedIds.value.includes(d.id),
        ),
);

function toggleSelectAll(checked: boolean | 'indeterminate') {
    if (checked === true) {
        const eligibleIds = eligibleDeclarations.value.map((d) => d.id);
        const merged = new Set([...selectedIds.value, ...eligibleIds]);
        selectedIds.value = [...merged];
    } else {
        const eligibleIds = new Set(
            eligibleDeclarations.value.map((d) => d.id),
        );
        selectedIds.value = selectedIds.value.filter(
            (id) => !eligibleIds.has(id),
        );
    }
}

function toggleRow(id: number, checked: boolean | 'indeterminate') {
    if (checked === true) {
        if (!selectedIds.value.includes(id)) {
            selectedIds.value = [...selectedIds.value, id];
        }
    } else {
        selectedIds.value = selectedIds.value.filter((i) => i !== id);
    }
}

function clearSelection() {
    selectedIds.value = [];
}

function destroy(declaration: Declaration) {
    if (
        window.confirm(
            `Êtes-vous sûr de vouloir supprimer « ${declaration.title} » ?`,
        )
    ) {
        router.delete(declaration.destroyUrl);
    }
}

const typeLabels: Record<string, string> = {
    vat: 'TVA',
    vat_monthly: 'TVA mensuelle',
    vat_quarterly: 'TVA trimestrielle',
    corporate_tax: 'IS',
    income_tax: 'IR',
    cnss: 'CNSS',
    annual_balance: 'Bilan',
    other: 'Autre',
};

const statusLabels: Record<string, string> = {
    draft: 'Brouillon',
    waiting_documents: 'En attente documents',
    documents_received: 'Documents reçus',
    processing: 'En cours de traitement',
    additional_documents_requested: 'Pièces complémentaires demandées',
    waiting_client_validation: 'En attente validation client',
    validated: 'Validé',
    closed: 'Clôturé',
    cancelled: 'Annulé',
};

const columnCount = computed(() => (props.canBulkNotify ? 7 : 6));
</script>

<template>
    <AppLayout :breadcrumbs="[{ title: 'Déclarations' }]">
        <Head title="Déclarations" />

        <div class="flex flex-col space-y-6 p-4">
            <div class="flex items-center justify-between">
                <Heading
                    variant="small"
                    title="Déclarations"
                    :description="`Gérer les déclarations du workspace « ${workspaceName} »`"
                />
                <Button v-if="props.canCreate" as-child>
                    <Link :href="createUrl">Nouvelle déclaration</Link>
                </Button>
            </div>

            <div
                class="overflow-hidden rounded-xl border border-sidebar-border/70 dark:border-sidebar-border"
            >
                <div class="overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead
                            class="border-b border-sidebar-border/70 bg-muted/50"
                        >
                            <tr>
                                <th
                                    v-if="props.canBulkNotify"
                                    class="h-10 w-10 px-4 text-center align-middle"
                                >
                                    <Checkbox
                                        :checked="allEligibleSelected"
                                        :disabled="
                                            eligibleDeclarations.length === 0
                                        "
                                        @update:checked="toggleSelectAll"
                                    />
                                </th>
                                <th
                                    class="h-10 px-4 text-left align-middle font-medium"
                                >
                                    Titre
                                </th>
                                <th
                                    class="h-10 px-4 text-left align-middle font-medium"
                                >
                                    Client
                                </th>
                                <th
                                    class="h-10 px-4 text-left align-middle font-medium"
                                >
                                    Type
                                </th>
                                <th
                                    class="h-10 px-4 text-left align-middle font-medium"
                                >
                                    Statut
                                </th>
                                <th
                                    class="h-10 px-4 text-left align-middle font-medium"
                                >
                                    Date limite
                                </th>
                                <th
                                    class="h-10 px-4 text-right align-middle font-medium"
                                >
                                    Actions
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr
                                v-for="declaration in declarations.data"
                                :key="declaration.id"
                                class="border-b border-sidebar-border/50 last:border-0"
                            >
                                <td
                                    v-if="props.canBulkNotify"
                                    class="px-4 py-3 text-center"
                                >
                                    <Checkbox
                                        v-if="
                                            declaration.status ===
                                            'en_attente_client'
                                        "
                                        :checked="
                                            selectedIds.includes(
                                                declaration.id,
                                            )
                                        "
                                        @update:checked="
                                            (v: boolean | 'indeterminate') =>
                                                toggleRow(declaration.id, v)
                                        "
                                    />
                                </td>
                                <td class="px-4 py-3 font-medium">
                                    <Link
                                        :href="declaration.showUrl"
                                        class="hover:underline"
                                    >
                                        {{ declaration.title }}
                                    </Link>
                                </td>
                                <td class="px-4 py-3 text-muted-foreground">
                                    {{ declaration.client_name }}
                                </td>
                                <td class="px-4 py-3 text-muted-foreground">
                                    {{
                                        typeLabels[declaration.type] ??
                                        declaration.type
                                    }}
                                </td>
                                <td class="px-4 py-3 text-muted-foreground">
                                    {{
                                        statusLabels[declaration.status] ??
                                        declaration.status
                                    }}
                                </td>
                                <td class="px-4 py-3 text-muted-foreground">
                                    {{ declaration.due_date || '—' }}
                                </td>
                                <td
                                    class="flex items-center gap-2 px-4 py-3 text-right"
                                >
                                    <NudgePopover
                                        v-if="props.canNudge"
                                        :assignee-name="
                                            declaration.assignee_name
                                        "
                                        :nudge-url="declaration.nudgeUrl"
                                    />
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        as-child
                                    >
                                        <Link :href="declaration.showUrl"
                                            >Voir</Link
                                        >
                                    </Button>
                                    <Button
                                        v-if="props.canEdit"
                                        variant="outline"
                                        size="sm"
                                        as-child
                                    >
                                        <Link :href="declaration.editUrl"
                                            >Modifier</Link
                                        >
                                    </Button>
                                    <Button
                                        v-if="props.canDelete"
                                        variant="destructive"
                                        size="sm"
                                        @click="destroy(declaration)"
                                    >
                                        Supprimer
                                    </Button>
                                </td>
                            </tr>
                            <tr v-if="!declarations.data.length">
                                <td
                                    :colspan="columnCount"
                                    class="px-4 py-8 text-center text-muted-foreground"
                                >
                                    <div
                                        class="flex flex-col items-center gap-2"
                                    >
                                        <FolderOpen class="h-10 w-10" />
                                        <p>
                                            Aucune déclaration pour le moment.
                                        </p>
                                        <Button v-if="props.canCreate" as-child>
                                            <Link :href="createUrl"
                                                >Créer votre première
                                                déclaration</Link
                                            >
                                        </Button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <Pagination
                :pagination="{
                    from: declarations.from ?? 0,
                    to: declarations.to ?? 0,
                    total: declarations.total,
                    current_page: declarations.current_page,
                    last_page: declarations.last_page,
                    per_page: declarations.per_page,
                }"
            />
        </div>

        <BulkActionBar
            v-if="props.canBulkNotify && props.bulkNotifyUrl"
            :selected-ids="selectedIds"
            :bulk-notify-url="props.bulkNotifyUrl"
            @clear="clearSelection"
        />
    </AppLayout>
</template>
