<script setup lang="ts">
import { Head, Link, useForm } from '@inertiajs/vue3';
import { computed } from 'vue';
import { ArrowLeft } from '@lucide/vue';
import Heading from '@/components/Heading.vue';
import InputError from '@/components/InputError.vue';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { dashboard } from '@/routes';
import type { BreadcrumbItem } from '@/types';

interface Kategori { id: number; nama_kategori: string; }
interface AdPlatform {
    id: number; name: string; slug: string;
    ad_type: string; countries: string | null; is_active: boolean;
}
interface Campaign {
    id: number;
    judul: string;
    url: string;
    jam_tayang_mulai: string;
    jam_tayang_selesai: string;
    kategoris: { id: number; nama_kategori: string }[];
    ad_type: string;
    ad_platform_id: number | null;
    target_country: string | null;
    verification_code: string | null;
    verified_at: string | null;
    budget_harian: number | null;
}

const props = defineProps<{
    campaign: Campaign;
    isAdmin: boolean;
    defaultRate: number;
    kategoris: Kategori[];
    adPlatforms: AdPlatform[];
}>();

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

const adTypes = [
    { value: 'affiliate', label: 'Iklan Affiliate', active: true },
    { value: 'link_website', label: 'Iklan Link Website', active: true },
    { value: 'backlink', label: 'Backlink / PBN', active: false },
    { value: 'press_release', label: 'Press Release Portal Media', active: false },
];

const form = useForm({
    judul: props.campaign.judul,
    url: props.campaign.url,
    jam_tayang_mulai: props.campaign.jam_tayang_mulai.slice(0, 5),
    jam_tayang_selesai: props.campaign.jam_tayang_selesai.slice(0, 5),
    budget_harian: props.campaign.budget_harian ?? 100000,
    kategori_ids: (props.campaign.kategoris ?? []).map(k => k.id),
    ad_type: props.campaign.ad_type ?? 'affiliate',
    ad_platform_id: props.campaign.ad_platform_id ?? '',
    target_country: props.campaign.target_country ?? '',
});

const filteredPlatforms = computed(() =>
    props.adPlatforms.filter((p) => p.ad_type === form.ad_type),
);

const selectedPlatform = computed(() =>
    props.adPlatforms.find((p) => p.id === Number(form.ad_platform_id)),
);

const countryOptions = computed(() => {
    if (! selectedPlatform.value?.countries) return [];
    return selectedPlatform.value.countries.split(',').map((c) => c.trim());
});

const onAdTypeChange = () => {
    form.ad_platform_id = '';
    form.target_country = '';
};

const copyCode = () => {
    if (props.campaign.verification_code) {
        navigator.clipboard.writeText(props.campaign.verification_code);
    }
};

const submit = () => form.put(`/campaigns/${props.campaign.id}`);
</script>

<template>
    <Head title="Edit 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>
            <Heading :title="`Edit: ${props.campaign.judul}`" description="Ubah data campaign" />
        </div>

        <form @submit.prevent="submit" class="max-w-2xl space-y-6">
            <!-- Jenis Iklan -->
            <div class="grid gap-2">
                <Label>Jenis Iklan</Label>
                <div class="grid gap-2 sm:grid-cols-2">
                    <button
                        v-for="t in adTypes"
                        :key="t.value"
                        type="button"
                        :disabled="!t.active"
                        @click="onAdTypeChange(); form.ad_type = t.value"
                        :class="[
                            'flex items-center justify-between rounded-lg border p-3 text-sm transition',
                            t.active ? 'cursor-pointer hover:border-primary' : 'cursor-not-allowed opacity-50',
                            form.ad_type === t.value ? 'border-primary bg-primary/5 ring-1 ring-primary' : 'border-input',
                        ]"
                    >
                        <span class="font-medium">{{ t.label }}</span>
                        <Badge v-if="!t.active" variant="outline" class="text-xs">Coming Soon</Badge>
                    </button>
                </div>
            </div>

            <div class="grid gap-2">
                <Label for="judul">Judul Iklan <span class="text-destructive">*</span></Label>
                <Input id="judul" v-model="form.judul" required />
                <InputError :message="form.errors.judul" />
            </div>

            <div class="grid gap-2">
                <Label for="url">URL Tujuan <span class="text-destructive">*</span></Label>
                <Input id="url" type="url" v-model="form.url" required />
                <InputError :message="form.errors.url" />
            </div>

            <!-- Platform & Negara -->
            <div class="grid gap-4 sm:grid-cols-2">
                <div class="grid gap-2">
                    <Label for="ad_platform_id">Platform</Label>
                    <select id="ad_platform_id" v-model="form.ad_platform_id" class="mt-1 block w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
                        <option value="">— Pilih Platform —</option>
                        <option v-for="p in filteredPlatforms" :key="p.id" :value="p.id" :disabled="!p.is_active">
                            {{ p.name }}{{ !p.is_active ? ' (Coming Soon)' : '' }}
                        </option>
                    </select>
                    <InputError :message="form.errors.ad_platform_id" />
                </div>
                <div v-if="countryOptions.length > 1" class="grid gap-2">
                    <Label for="target_country">Negara</Label>
                    <select id="target_country" v-model="form.target_country" class="mt-1 block w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
                        <option value="">— Pilih Negara —</option>
                        <option v-for="c in countryOptions" :key="c" :value="c">{{ c }}</option>
                    </select>
                    <InputError :message="form.errors.target_country" />
                </div>
            </div>

            <div class="grid gap-4 sm:grid-cols-2">
                <div class="grid gap-2">
                    <Label for="jam_tayang_mulai">Jam Tayang Mulai <span class="text-destructive">*</span></Label>
                    <Input id="jam_tayang_mulai" type="time" v-model="form.jam_tayang_mulai" required />
                    <InputError :message="form.errors.jam_tayang_mulai" />
                </div>
                <div class="grid gap-2">
                    <Label for="jam_tayang_selesai">Jam Tayang Selesai <span class="text-destructive">*</span></Label>
                    <Input id="jam_tayang_selesai" type="time" v-model="form.jam_tayang_selesai" required />
                    <InputError :message="form.errors.jam_tayang_selesai" />
                </div>
            </div>

            <div class="grid gap-2">
                <Label for="budget_harian">Budget Harian (Rp) <span class="text-destructive">*</span></Label>
                <Input id="budget_harian" type="number" v-model="form.budget_harian" min="1" required />
                <p class="text-xs text-muted-foreground">Dikonversi via rate (Rp {{ props.defaultRate }}/klik). Sisa budget harian roll ke hari berikutnya.</p>
                <InputError :message="form.errors.budget_harian" />
            </div>

            <!-- Kategori: admin bisa pilih, member tidak bisa -->
            <div v-if="isAdmin" class="grid gap-2">
                <Label for="kategori_ids">Kategori</Label>
                <select v-if="isAdmin" id="kategori_ids" v-model="form.kategori_ids" multiple size="5" class="mt-1 block w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
                    <option v-for="k in props.kategoris" :key="k.id" :value="k.id">{{ k.nama_kategori }}</option>
                </select>
                <!-- <div v-else class="flex h-11 items-center rounded-md border border-dashed bg-muted/30 px-3 text-sm text-muted-foreground">
                    Ditentukan admin setelah approval
                </div> -->
                <p v-if="isAdmin" class="text-xs text-muted-foreground">Ctrl+click (Cmd+click Mac) untuk pilih lebih dari satu.</p>
                <InputError :message="form.errors.kategori_ids" />
            </div>

            <!-- Kode verifikasi (read-only, untuk link_website) -->
            <div v-if="props.campaign.verification_code" class="rounded-lg border bg-muted/30 p-4 space-y-2">
                <div class="flex items-center justify-between">
                    <Label class="text-sm">Kode Verifikasi Situs</Label>
                    <Badge :variant="props.campaign.verified_at ? 'default' : 'outline'">
                        {{ props.campaign.verified_at ? 'Terverifikasi' : 'Belum' }}
                    </Badge>
                </div>
                <div class="flex items-center gap-2">
                    <code class="flex-1 rounded-md bg-background px-3 py-2 text-xs">{{ props.campaign.verification_code }}</code>
                    <Button type="button" variant="outline" size="sm" @click="copyCode">Salin</Button>
                </div>
            </div>

            <div class="flex justify-end gap-2">
                <Button as-child variant="outline" type="button">
                    <Link href="/campaigns">Batal</Link>
                </Button>
                <Button type="submit" :disabled="form.processing">Simpan</Button>
            </div>
        </form>
    </div>
</template>
