<script setup lang="ts">
import { Head, Link, useForm } from '@inertiajs/vue3';
import { computed, ref, watch } 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 { dashboard } from '@/routes';
import type { BreadcrumbItem } from '@/types';

interface Bank { id: number; kode: string; keterangan: string; }
interface UserRow { id: number; name: string; email: string; }

const props = defineProps<{
    banks: Bank[];
    users: UserRow[];
}>();

defineOptions({
    layout: {
        breadcrumbs: [
            { title: 'Dashboard', href: dashboard() },
            { title: 'Billing', href: '/billings' },
            { title: 'Buat Invoice', href: '/billings/create' },
        ] as BreadcrumbItem[],
    },
});

const presets = [50000, 100000, 200000] as const;
const MIN_TOPUP = 50000;

const form = useForm({
    jumlah_credit: 50000,
    rate: 1,
    bank_id: '' as string | number,
    user_id: props.users[0]?.id ?? '',
    payment_method: 'manual',
});

const pilihan = ref<number | 'custom'>(50000);
const customNominal = ref<number>(50000);

// 1 rupiah = 1 credit: jumlah credit = nominal topup.
watch([pilihan, customNominal], () => {
    form.jumlah_credit =
        pilihan.value === 'custom'
            ? Math.max(0, Math.floor(customNominal.value || 0))
            : pilihan.value;
});

const total = computed(() => form.jumlah_credit);

const customInvalid = computed(
    () => pilihan.value === 'custom' && form.jumlah_credit < MIN_TOPUP,
);

const submit = () => {
    if (customInvalid.value) {
        form.setError('jumlah_credit', 'Topup minimal Rp 50.000.');
        return;
    }
    form.clearErrors('jumlah_credit');
    form.post('/billings');
};
</script>

<template>
    <Head title="Buat Invoice Billing" />

    <div class="flex flex-col space-y-6">
        <div>
            <Button as-child variant="ghost" size="sm" class="mb-2">
                <Link href="/billings"><ArrowLeft class="size-4" /> Kembali</Link>
            </Button>
            <Heading title="Buat Invoice Deposit" description="Deposit credit pengguna" />
        </div>

        <form @submit.prevent="submit" class="max-w-2xl space-y-6">
            <div v-if="props.users.length > 0" class="grid gap-2">
                <Label for="user_id">Pengguna <span class="text-destructive">*</span></Label>
                <select id="user_id" v-model="form.user_id" required class="mt-1 block w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
                    <option v-for="u in props.users" :key="u.id" :value="u.id">{{ u.name }} ({{ u.email }})</option>
                </select>
                <InputError :message="form.errors.user_id" />
            </div>

            <div class="grid gap-2">
                <Label>Jumlah Deposit <span class="text-destructive">*</span></Label>
                <div class="grid grid-cols-2 gap-2 sm:grid-cols-4">
                    <button
                        v-for="p in presets"
                        :key="p"
                        type="button"
                        @click="pilihan = p"
                        :class="[
                            'rounded-md border px-3 py-2.5 text-sm font-medium tabular-nums transition-colors',
                            pilihan === p
                                ? 'border-primary bg-primary/10 text-primary'
                                : 'border-input hover:bg-muted',
                        ]"
                    >
                        Rp {{ p.toLocaleString('id-ID') }}
                    </button>
                    <button
                        type="button"
                        @click="pilihan = 'custom'"
                        :class="[
                            'rounded-md border px-3 py-2.5 text-sm font-medium transition-colors',
                            pilihan === 'custom'
                                ? 'border-primary bg-primary/10 text-primary'
                                : 'border-input hover:bg-muted',
                        ]"
                    >
                        Custom
                    </button>
                </div>

                <div v-if="pilihan === 'custom'" class="mt-1">
                    <Input
                        id="custom_nominal"
                        type="number"
                        v-model="customNominal"
                        :min="MIN_TOPUP"
                        step="1000"
                        placeholder="Minimal Rp 50.000"
                    />
                    <p class="mt-1 text-xs text-muted-foreground">Topup minimal Rp 50.000.</p>
                </div>

                <p class="text-xs text-muted-foreground">
                    Credit didapat: <span class="font-semibold text-foreground">{{ form.jumlah_credit.toLocaleString('id-ID') }} credit</span>
                </p>
                <InputError :message="form.errors.jumlah_credit" />
            </div>

            <div class="grid gap-2">
                <Label for="payment_method">Metode Pembayaran</Label>
                <select id="payment_method" v-model="form.payment_method" class="mt-1 block w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
                    <option value="manual">Transfer Manual (konfirmasi admin)</option>
                    <option value="duitku">Duitku (otomatis)</option>
                </select>
                <p v-if="form.payment_method === 'duitku'" class="text-xs text-muted-foreground">
                    Anda akan diarahkan ke halaman pembayaran Duitku. Credit masuk otomatis setelah pembayaran terkonfirmasi.
                </p>
                <InputError :message="form.errors.payment_method" />
            </div>

            <div v-if="form.payment_method === 'manual'" class="grid gap-2">
                <Label for="bank_id">Bank Tujuan</Label>
                <select id="bank_id" v-model="form.bank_id" class="mt-1 block w-full rounded-md border border-input bg-background px-3 py-2 text-sm">
                    <option value="">— Pilih Bank —</option>
                    <option v-for="b in props.banks" :key="b.id" :value="b.id">{{ b.kode }} — {{ b.keterangan }}</option>
                </select>
                <InputError :message="form.errors.bank_id" />
            </div>

            <div class="rounded-lg border bg-muted/30 p-4">
                <div class="flex items-center justify-between text-sm">
                    <span class="text-muted-foreground">Total Pembayaran</span>
                    <span class="text-lg font-bold tabular-nums">Rp {{ total.toLocaleString('id-ID') }}</span>
                </div>
            </div>

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