<script setup lang="ts">
import { Head, Link, usePage } from '@inertiajs/vue3';
import { toast } from 'vue-sonner';
import { ArrowLeft } from '@lucide/vue';
import Heading from '@/components/Heading.vue';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { dashboard } from '@/routes';
import type { BreadcrumbItem } from '@/types';

interface Campaign {
    id: number;
    judul: string;
    url: string;
    jam_tayang_mulai: string;
    jam_tayang_selesai: string;
    budget_harian: number | null;
    klik_hari_ini: number;
    rollover_klik: number;
    klik: number;
    muncul: number;
    status: number;
    tgl_aktif: string | null;
    created_at: string;
    ad_type: string;
    target_country: string | null;
    verification_code: string | null;
    verified_at: string | null;
    is_paused: boolean;
    pause_reason: string | null;
    kategoris?: { id: number; nama_kategori: string }[];
    user?: { name: string } | null;
    ad_platform?: { name: string } | null;
}

const props = defineProps<{
    campaign: Campaign;
    defaultRate: number;
}>();

const isAdmin = usePage().props.auth.user?.is_admin ?? false;

// Cap klik efektif hari ini = base cap (budget/rate) + rollover.
const effectiveCap = Math.floor((props.campaign.budget_harian ?? 0) / props.defaultRate) + props.campaign.rollover_klik;

defineOptions({
    layout: {
        breadcrumbs: [
            { title: 'Dashboard', href: dashboard() },
            { title: 'Campaign', href: '/campaigns' },
            { title: 'Detail', href: '/campaigns' },
        ] as BreadcrumbItem[],
    },
});

const statusLabel: Record<number, string> = {
    0: 'Menunggu Approve',
    1: 'Aktif',
    2: 'Batal',
    3: 'Selesai',
    4: 'Draft',
};

const adTypeLabels: Record<string, string> = {
    affiliate: 'Iklan Affiliate',
    link_website: 'Iklan Link Website',
    backlink: 'Backlink / PBN',
    press_release: 'Press Release Portal Media',
};

const copyCode = () => {
    if (props.campaign.verification_code) {
        navigator.clipboard.writeText(props.campaign.verification_code);
        toast.success('Kode verifikasi disalin.');
    }
};
</script>

<template>
    <Head title="Detail Campaign" />

    <div class="flex flex-col space-y-6">
        <div>
            <Button as-child variant="ghost" size="sm" class="mb-2">
                <Link href="/campaigns"><ArrowLeft class="size-4" /> Kembali</Link>
            </Button>
            <div class="flex items-center justify-between gap-4">
                <Heading :title="props.campaign.judul" />
                <div class="flex items-center gap-2">
                    <Badge v-if="!(props.campaign.is_paused && props.campaign.status === 1)">{{ statusLabel[props.campaign.status] }}</Badge>
                    <Badge v-if="props.campaign.is_paused && props.campaign.status === 1" variant="secondary">Dijeda</Badge>
                    <Button v-if="props.campaign.status === 1 && !props.campaign.is_paused" as-child variant="outline" size="sm">
                        <Link :href="`/campaigns/${props.campaign.id}/stop`">Stop</Link>
                    </Button>
                    <Button v-if="props.campaign.status === 1 && props.campaign.is_paused" as-child size="sm">
                        <Link :href="`/campaigns/${props.campaign.id}/start`">Start</Link>
                    </Button>
                    <Button v-if="props.campaign.status === 0 || props.campaign.status === 1" as-child variant="outline" size="sm">
                        <Link :href="`/campaigns/${props.campaign.id}/draft`">Jadikan Draft</Link>
                    </Button>
                    <Button v-if="props.campaign.status === 4" as-child size="sm">
                        <Link :href="`/campaigns/${props.campaign.id}/restore`">Aktifkan</Link>
                    </Button>
                    <Button v-if="props.campaign.status === 0 || (props.campaign.status === 1 && props.campaign.is_paused)" as-child variant="ghost" size="sm">
                        <Link :href="`/campaigns/${props.campaign.id}/edit`">Edit</Link>
                    </Button>
                </div>
            </div>
        </div>

        <div class="grid gap-4 sm:grid-cols-3">
            <Card>
                <CardHeader class="pb-2"><CardTitle class="text-sm text-muted-foreground">Budget Harian</CardTitle></CardHeader>
                <CardContent><div class="text-2xl font-bold tabular-nums">Rp {{ (props.campaign.budget_harian ?? 0).toLocaleString('id-ID') }}</div></CardContent>
            </Card>
            <Card>
                <CardHeader class="pb-2"><CardTitle class="text-sm text-muted-foreground">Klik Hari Ini</CardTitle></CardHeader>
                <CardContent><div class="text-2xl font-bold tabular-nums">{{ props.campaign.klik_hari_ini.toLocaleString('id-ID') }} / {{ effectiveCap.toLocaleString('id-ID') }}</div></CardContent>
            </Card>
            <Card>
                <CardHeader class="pb-2"><CardTitle class="text-sm text-muted-foreground">Klik Total</CardTitle></CardHeader>
                <CardContent><div class="text-2xl font-bold tabular-nums">{{ props.campaign.klik.toLocaleString('id-ID') }}</div></CardContent>
            </Card>
        </div>

        <Card>
            <CardHeader><CardTitle>Detail Campaign</CardTitle></CardHeader>
            <CardContent>
                <dl class="divide-y rounded-lg border text-sm">
                    <div class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">Jenis Iklan</dt><dd class="flex-1 text-right font-medium">{{ adTypeLabels[props.campaign.ad_type] ?? props.campaign.ad_type }}</dd></div>
                    <div v-if="props.campaign.ad_type !== 'link_website'" class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">Platform</dt><dd class="flex-1 text-right font-medium">{{ props.campaign.ad_platform?.name ?? '—' }}</dd></div>
                    <div v-if="props.campaign.target_country" class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">Negara</dt><dd class="flex-1 text-right font-medium">{{ props.campaign.target_country }}</dd></div>
                    <div class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">URL Tujuan</dt><dd class="flex-1 truncate text-right"><a :href="props.campaign.url" target="_blank" class="font-medium text-blue-600 hover:underline">{{ props.campaign.url }}</a></dd></div>
                    <div v-if="isAdmin" class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">Kategori</dt><dd class="flex-1 text-right font-medium">{{ props.campaign.kategoris?.map(k => k.nama_kategori).join(', ') || '—' }}</dd></div>
                    <div class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">Pemilik</dt><dd class="flex-1 text-right font-medium">{{ props.campaign.user?.name ?? '—' }}</dd></div>
                    <div class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">Jam Tayang</dt><dd class="flex-1 text-right font-medium">{{ props.campaign.jam_tayang_mulai }} - {{ props.campaign.jam_tayang_selesai }}</dd></div>
                    <div class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">Budget Harian</dt><dd class="flex-1 text-right font-medium tabular-nums">Rp {{ (props.campaign.budget_harian ?? 0).toLocaleString('id-ID') }}</dd></div>
                    <div class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">Rate</dt><dd class="flex-1 text-right font-medium tabular-nums">Rp {{ props.defaultRate.toLocaleString('id-ID') }}/klik</dd></div>
                    <div class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">Rollover Klik</dt><dd class="flex-1 text-right font-medium tabular-nums">{{ props.campaign.rollover_klik.toLocaleString('id-ID') }}</dd></div>
                    <div v-if="props.campaign.ad_type !== 'link_website'" class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">Tayang (muncul)</dt><dd class="flex-1 text-right font-medium tabular-nums">{{ props.campaign.muncul.toLocaleString('id-ID') }}</dd></div>
                    <div v-if="props.campaign.tgl_aktif" class="flex items-center gap-4 px-4 py-2.5"><dt class="w-36 shrink-0 text-muted-foreground">Tgl Aktif</dt><dd class="flex-1 text-right font-medium">{{ new Date(props.campaign.tgl_aktif).toLocaleString('id-ID') }}</dd></div>
                </dl>
            </CardContent>
        </Card>

        <!-- Verifikasi situs (untuk link_website) -->
        <Card v-if="props.campaign.verification_code">
            <CardHeader class="flex flex-row items-center justify-between">
                <CardTitle class="text-base">Verifikasi Situs</CardTitle>
                <Badge :variant="props.campaign.verified_at ? 'default' : 'outline'">
                    {{ props.campaign.verified_at ? 'Terverifikasi' : 'Belum Terverifikasi' }}
                </Badge>
            </CardHeader>
            <CardContent class="space-y-3 text-sm">
                <p class="text-muted-foreground">Pasang kode berikut di halaman situs Anda (meta tag atau HTML), lalu klik Verifikasi:</p>
                <div class="flex items-center gap-2">
                    <code class="flex-1 rounded-md bg-muted px-3 py-2 text-xs">{{ props.campaign.verification_code }}</code>
                    <Button variant="outline" size="sm" @click="copyCode">Salin</Button>
                </div>
                <Button as-child size="sm">
                    <Link :href="`/campaigns/${props.campaign.id}/verify`">Verifikasi Sekarang</Link>
                </Button>
                <p v-if="props.campaign.verified_at" class="text-xs text-emerald-600">Terverifikasi pada {{ new Date(props.campaign.verified_at).toLocaleString('id-ID') }}</p>
            </CardContent>
        </Card>
    </div>
</template>
