<script setup lang="ts">
import { Form, Head } from '@inertiajs/vue3';
import { ref } from 'vue';
import AdminSettingController from '@/actions/App/Http/Controllers/Settings/AdminSettingController';
import Heading from '@/components/Heading.vue';
import InputError from '@/components/InputError.vue';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import AppLayout from '@/layouts/AppLayout.vue';

type SecretValue = { is_set: boolean; value: null };

defineProps<{
    smtp: {
        host: string | null;
        port: number | null;
        username: string | null;
        password: SecretValue;
        encryption: string | null;
        from_address: string | null;
        from_name: string | null;
        default: string | null;
    };
    duitku: {
        enabled: boolean;
        merchant_code: string | null;
        api_key: SecretValue;
        base_url: string | null;
        inquiry_path: string | null;
        callback_url: string | null;
        return_url: string | null;
        expiry_period: number | null;
        configured: boolean;
    };
    rate: {
        default_rate: number;
        empty_kategori_url: string;
    };
    website: {
        logo_url: string | null;
        favicon_url: string | null;
    };
    status?: string;
}>();

defineOptions({
    layout: AppLayout,
});

type Tab = 'smtp' | 'duitku' | 'rate' | 'website';
const activeTab = ref<Tab>('smtp');

const tabs: { value: Tab; label: string }[] = [
    { value: 'smtp', label: 'SMTP' },
    { value: 'duitku', label: 'Duitku' },
    { value: 'rate', label: 'Tarif' },
    { value: 'website', label: 'Website' },
];
</script>

<template>
    <Head title="Pengaturan" />

    <h1 class="sr-only">Pengaturan</h1>

    <div class="space-y-6">
        <Heading
            variant="small"
            title="Pengaturan"
            description="Kelola SMTP, gateway Duitku, dan tarif credit"
        />

        <div
            v-if="status"
            class="rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-2.5 text-sm font-medium text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950/50 dark:text-emerald-400"
        >
            {{ status }}
        </div>

        <!-- Tab buttons -->
        <div
            class="inline-flex gap-1 rounded-lg bg-neutral-100 p-1 dark:bg-neutral-800"
        >
            <button
                v-for="tab in tabs"
                :key="tab.value"
                type="button"
                @click="activeTab = tab.value"
                :class="[
                    'rounded-md px-4 py-1.5 text-sm font-medium transition-colors',
                    activeTab === tab.value
                        ? 'bg-white shadow-xs dark:bg-neutral-700 dark:text-neutral-100'
                        : 'text-neutral-500 hover:bg-neutral-200/60 hover:text-black dark:text-neutral-400 dark:hover:bg-neutral-700/60',
                ]"
            >
                {{ tab.label }}
            </button>
        </div>

        <!-- SMTP -->
        <div v-show="activeTab === 'smtp'" class="space-y-6">
            <Form
                v-bind="AdminSettingController.update.form()"
                :reset-on-success="['mail_password']"
                v-slot="{ errors, processing }"
                class="space-y-5"
            >
                <input type="hidden" name="tab" value="smtp" />

                <div class="grid gap-4 sm:grid-cols-2">
                    <div class="grid gap-2">
                        <Label for="mail_host">SMTP Host</Label>
                        <Input
                            id="mail_host"
                            name="mail_host"
                            :default-value="smtp.host ?? ''"
                            placeholder="smtp.gmail.com"
                            class="h-10"
                        />
                        <InputError :message="errors.mail_host" />
                    </div>

                    <div class="grid gap-2">
                        <Label for="mail_port">Port</Label>
                        <Input
                            id="mail_port"
                            name="mail_port"
                            type="number"
                            :default-value="smtp.port ?? ''"
                            placeholder="587"
                            class="h-10"
                        />
                        <InputError :message="errors.mail_port" />
                    </div>
                </div>

                <div class="grid gap-4 sm:grid-cols-2">
                    <div class="grid gap-2">
                        <Label for="mail_username">Username</Label>
                        <Input
                            id="mail_username"
                            name="mail_username"
                            :default-value="smtp.username ?? ''"
                            placeholder="user@gmail.com"
                            class="h-10"
                        />
                        <InputError :message="errors.mail_username" />
                    </div>

                    <div class="grid gap-2">
                        <Label for="mail_password">Password</Label>
                        <Input
                            id="mail_password"
                            name="mail_password"
                            type="password"
                            :placeholder="smtp.password.is_set ? '•••••••• (tersimpan)' : 'Kosong = tidak diubah'"
                            class="h-10"
                        />
                        <InputError :message="errors.mail_password" />
                    </div>
                </div>

                <div class="grid gap-4 sm:grid-cols-2">
                    <div class="grid gap-2">
                        <Label for="mail_encryption">Enkripsi</Label>
                        <Select
                            name="mail_encryption"
                            :default-value="smtp.encryption ?? 'tls'"
                        >
                            <SelectTrigger id="mail_encryption" class="h-10 w-full">
                                <SelectValue placeholder="tls" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="tls">TLS</SelectItem>
                                <SelectItem value="ssl">SSL</SelectItem>
                                <SelectItem value="none">Tidak ada</SelectItem>
                            </SelectContent>
                        </Select>
                        <InputError :message="errors.mail_encryption" />
                    </div>

                    <div class="grid gap-2">
                        <Label for="mail_default">Mailer Default</Label>
                        <Select
                            name="mail_default"
                            :default-value="smtp.default ?? 'log'"
                        >
                            <SelectTrigger id="mail_default" class="h-10 w-full">
                                <SelectValue placeholder="log" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="smtp">SMTP</SelectItem>
                                <SelectItem value="log">Log</SelectItem>
                                <SelectItem value="sendmail">Sendmail</SelectItem>
                            </SelectContent>
                        </Select>
                        <InputError :message="errors.mail_default" />
                    </div>
                </div>

                <div class="grid gap-4 sm:grid-cols-2">
                    <div class="grid gap-2">
                        <Label for="mail_from_address">Email Pengirim</Label>
                        <Input
                            id="mail_from_address"
                            name="mail_from_address"
                            type="email"
                            :default-value="smtp.from_address ?? ''"
                            placeholder="noreply@aplikasi.com"
                            class="h-10"
                        />
                        <InputError :message="errors.mail_from_address" />
                    </div>

                    <div class="grid gap-2">
                        <Label for="mail_from_name">Nama Pengirim</Label>
                        <Input
                            id="mail_from_name"
                            name="mail_from_name"
                            :default-value="smtp.from_name ?? ''"
                            placeholder="Aplikasi"
                            class="h-10"
                        />
                        <InputError :message="errors.mail_from_name" />
                    </div>
                </div>

                <Button :disabled="processing" data-test="save-smtp-button">Simpan SMTP</Button>
            </Form>

            <!-- Test email -->
            <div class="space-y-4 border-t border-border pt-6">
                <div>
                    <h3 class="text-sm font-semibold">Uji Coba Kirim Email</h3>
                    <p class="text-sm text-muted-foreground">
                        Kirim email test pakai konfigurasi SMTP saat ini.
                    </p>
                </div>
                <Form
                    v-bind="AdminSettingController.sendTestEmail.form()"
                    v-slot="{ errors, processing }"
                    class="flex flex-col gap-3 sm:flex-row sm:items-end"
                >
                    <div class="grid flex-1 gap-2">
                        <Label for="recipient">Email Penerima</Label>
                        <Input
                            id="recipient"
                            name="recipient"
                            type="email"
                            required
                            placeholder="tujuan@email.com"
                            class="h-10"
                        />
                        <InputError :message="errors.recipient" />
                    </div>
                    <Button :disabled="processing" variant="outline" data-test="test-email-button">
                        Kirim Email Test
                    </Button>
                </Form>
            </div>
        </div>

        <!-- Duitku -->
        <div v-show="activeTab === 'duitku'" class="space-y-6">
            <div class="flex items-center gap-2">
                <span class="text-sm text-muted-foreground">Status gateway:</span>
                <Badge :variant="duitku.configured ? 'default' : 'secondary'">
                    {{ duitku.configured ? 'Terhubung' : 'Belum dikonfigurasi' }}
                </Badge>
            </div>

            <Form
                v-bind="AdminSettingController.update.form()"
                :reset-on-success="['duitku_api_key']"
                v-slot="{ errors, processing }"
                class="space-y-5"
            >
                <input type="hidden" name="tab" value="duitku" />

                <div class="flex items-center gap-3">
                    <Checkbox
                        id="duitku_enabled"
                        name="duitku_enabled"
                        :model-value="duitku.enabled"
                        value="1"
                    />
                    <Label for="duitku_enabled" class="text-sm font-medium">
                        Aktifkan pembayaran Duitku
                    </Label>
                    <InputError :message="errors.duitku_enabled" />
                </div>

                <div class="grid gap-4 sm:grid-cols-2">
                    <div class="grid gap-2">
                        <Label for="duitku_merchant_code">Merchant Code</Label>
                        <Input
                            id="duitku_merchant_code"
                            name="duitku_merchant_code"
                            :default-value="duitku.merchant_code ?? ''"
                            placeholder="DXXXX"
                            class="h-10"
                        />
                        <InputError :message="errors.duitku_merchant_code" />
                    </div>

                    <div class="grid gap-2">
                        <Label for="duitku_api_key">API Key</Label>
                        <Input
                            id="duitku_api_key"
                            name="duitku_api_key"
                            type="password"
                            :placeholder="duitku.api_key.is_set ? '•••••••• (tersimpan)' : 'Kosong = tidak diubah'"
                            class="h-10"
                        />
                        <InputError :message="errors.duitku_api_key" />
                    </div>
                </div>

                <div class="grid gap-4 sm:grid-cols-2">
                    <div class="grid gap-2">
                        <Label for="duitku_base_url">Base URL</Label>
                        <Input
                            id="duitku_base_url"
                            name="duitku_base_url"
                            :default-value="duitku.base_url ?? ''"
                            placeholder="https://api-sandbox.duitku.com"
                            class="h-10"
                        />
                        <InputError :message="errors.duitku_base_url" />
                    </div>

                    <div class="grid gap-2">
                        <Label for="duitku_inquiry_path">Inquiry Path</Label>
                        <Input
                            id="duitku_inquiry_path"
                            name="duitku_inquiry_path"
                            :default-value="duitku.inquiry_path ?? ''"
                            placeholder="/api/merchant/createInvoice"
                            class="h-10"
                        />
                        <InputError :message="errors.duitku_inquiry_path" />
                    </div>
                </div>

                <div class="grid gap-4 sm:grid-cols-2">
                    <div class="grid gap-2">
                        <Label for="duitku_callback_url">Callback URL</Label>
                        <Input
                            id="duitku_callback_url"
                            name="duitku_callback_url"
                            :default-value="duitku.callback_url ?? ''"
                            placeholder="https://domain.com/payments/duitku/callback"
                            class="h-10"
                        />
                        <InputError :message="errors.duitku_callback_url" />
                    </div>

                    <div class="grid gap-2">
                        <Label for="duitku_return_url">Return URL</Label>
                        <Input
                            id="duitku_return_url"
                            name="duitku_return_url"
                            :default-value="duitku.return_url ?? ''"
                            placeholder="https://domain.com/payments/duitku/return"
                            class="h-10"
                        />
                        <InputError :message="errors.duitku_return_url" />
                    </div>
                </div>

                <div class="grid gap-2 sm:max-w-xs">
                    <Label for="duitku_expiry_period">Expiry Period (menit)</Label>
                    <Input
                        id="duitku_expiry_period"
                        name="duitku_expiry_period"
                        type="number"
                        :default-value="duitku.expiry_period ?? 60"
                        class="h-10"
                    />
                    <InputError :message="errors.duitku_expiry_period" />
                </div>

                <Button :disabled="processing" data-test="save-duitku-button">Simpan Duitku</Button>
            </Form>
        </div>

        <!-- Rate -->
        <div v-show="activeTab === 'rate'" class="space-y-6">
            <Alert>
                <AlertDescription>
                    Harga per klik iklan (Rp). Dipakai konversi budget harian
                    campaign menjadi cap klik per hari.
                </AlertDescription>
            </Alert>

            <Form
                v-bind="AdminSettingController.update.form()"
                v-slot="{ errors, processing }"
                class="space-y-5"
            >
                <input type="hidden" name="tab" value="rate" />

                <div class="grid gap-2 sm:max-w-xs">
                    <Label for="default_rate">Rate per Klik Iklan (Rp)</Label>
                    <Input
                        id="default_rate"
                        name="default_rate"
                        type="number"
                        :default-value="rate.default_rate"
                        required
                        min="1"
                        class="h-10"
                    />
                    <InputError :message="errors.default_rate" />
                </div>

                <div class="grid gap-2 sm:max-w-xl">
                    <Label for="empty_kategori_url">Link Fallback Kategori Kosong</Label>
                    <Input
                        id="empty_kategori_url"
                        name="empty_kategori_url"
                        type="url"
                        placeholder="https://contoh.com"
                        :default-value="rate.empty_kategori_url"
                        class="h-10"
                    />
                    <p class="text-xs text-muted-foreground">URL tujuan saat kategori ditemukan tapi tidak ada campaign iklan aktif. Kosongkan untuk pakai default.</p>
                    <InputError :message="errors.empty_kategori_url" />
                </div>

                <p class="text-xs text-muted-foreground">
                    Contoh: rate Rp 100 → budget harian Rp 10.000 = 100 klik/hari.
                </p>

                <Button :disabled="processing" data-test="save-rate-button">Simpan Tarif</Button>
            </Form>
        </div>

        <!-- Website -->
        <div v-show="activeTab === 'website'" class="space-y-6">
            <Alert>
                <AlertDescription>
                    Logo tampil di sidebar aplikasi; favicon tampil di tab browser.
                    Kosongkan input bila tidak ingin mengubah.
                </AlertDescription>
            </Alert>

            <Form
                v-bind="AdminSettingController.update.form()"
                v-slot="{ errors, processing }"
                class="space-y-6"
            >
                <input type="hidden" name="tab" value="website" />

                <div class="grid gap-2 sm:max-w-md">
                    <Label for="logo">Logo Website</Label>
                    <div v-if="website.logo_url" class="flex items-center gap-3">
                        <img :src="website.logo_url" alt="Logo" class="h-10 max-w-40 rounded border border-border object-contain p-1" />
                        <label class="flex items-center gap-2 text-sm text-muted-foreground">
                            <input type="checkbox" name="remove_logo" value="1" class="rounded border-border" />
                            Hapus logo
                        </label>
                    </div>
                    <Input id="logo" name="logo" type="file" accept="image/png,image/jpeg,image/svg+xml,image/webp" class="h-10" />
                    <p class="text-xs text-muted-foreground">PNG/JPG/SVG/WebP, maks 2 MB.</p>
                    <InputError :message="errors.logo" />
                </div>

                <div class="grid gap-2 sm:max-w-md">
                    <Label for="favicon">Favicon</Label>
                    <div v-if="website.favicon_url" class="flex items-center gap-3">
                        <img :src="website.favicon_url" alt="Favicon" class="h-8 w-8 rounded border border-border object-contain p-0.5" />
                        <label class="flex items-center gap-2 text-sm text-muted-foreground">
                            <input type="checkbox" name="remove_favicon" value="1" class="rounded border-border" />
                            Hapus favicon
                        </label>
                    </div>
                    <Input id="favicon" name="favicon" type="file" accept="image/png,image/svg+xml,image/x-icon" class="h-10" />
                    <p class="text-xs text-muted-foreground">PNG/ICO/SVG, maks 512 KB.</p>
                    <InputError :message="errors.favicon" />
                </div>

                <Button :disabled="processing" data-test="save-website-button">Simpan Website</Button>
            </Form>
        </div>
    </div>
</template>
