<script setup>
import { ref } from 'vue'
import { Head, Link, useForm } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    ArrowLeftIcon,
    ArrowDownTrayIcon,
    KeyIcon,
    BookOpenIcon,
    InformationCircleIcon,
    GlobeAltIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    app: Object,
    domains: Array,
})

const form = useForm({
    domain_id: props.domains[0]?.id || null,
    install_path: '/',
    version: props.app.latest_version,
    site_title: props.app.fields?.site_title?.default || '',
    admin_username: props.app.fields?.admin_username?.default || 'admin',
    admin_email: '',
    admin_password: '',
    language: props.app.fields?.language?.default || 'tr_TR',
})

const generatePassword = () => {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%'
    let p = ''
    for (let i = 0; i < 16; i++) p += chars.charAt(Math.floor(Math.random() * chars.length))
    form.admin_password = p
}

const submit = () => form.post(route('customer.apps.install', props.app.slug))

const installPreview = () => {
    const d = props.domains.find((x) => x.id === form.domain_id)
    if (!d) return ''
    const path = form.install_path === '/' ? '' : form.install_path
    return `https://${d.name}${path}`
}
</script>

<template>
    <Head :title="`${app.name} Kur`" />
    <CustomerLayout>
        <template #header>{{ app.name }} Kurulumu</template>

        <Link :href="route('customer.apps.catalog')" class="mb-4 inline-flex items-center gap-1 text-sm text-slate-600 hover:text-indigo-700">
            <ArrowLeftIcon class="h-4 w-4" /> Katalog'a Dön
        </Link>

        <div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
            <!-- App info sidebar -->
            <div class="lg:col-span-1">
                <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                    <div class="flex items-center gap-3">
                        <div class="flex h-16 w-16 items-center justify-center rounded-xl text-4xl" :style="{ backgroundColor: app.color + '15' }">
                            {{ app.icon_emoji }}
                        </div>
                        <div>
                            <h2 class="text-xl font-bold text-slate-900">{{ app.name }}</h2>
                            <p class="text-xs text-slate-500">{{ app.category }} · v{{ app.latest_version }}</p>
                        </div>
                    </div>
                    <p class="mt-4 text-sm text-slate-600">{{ app.description }}</p>

                    <dl class="mt-4 space-y-2 border-t border-slate-100 pt-4 text-xs">
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Minimum PHP</dt>
                            <dd class="font-mono font-medium">{{ app.min_php }}+</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Veritabanı</dt>
                            <dd class="font-medium">{{ app.requires_db ? 'MySQL gerekli' : 'Gerekmiyor' }}</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-slate-500">Mevcut versiyonlar</dt>
                            <dd class="font-mono text-right">{{ app.available_versions.join(', ') }}</dd>
                        </div>
                    </dl>

                    <a v-if="app.docs_url" :href="app.docs_url" target="_blank"
                       class="mt-4 inline-flex items-center gap-1 text-xs text-indigo-600 hover:text-indigo-700">
                        <BookOpenIcon class="h-3.5 w-3.5" /> Resmi Dokümantasyon
                    </a>
                </div>
            </div>

            <!-- Install form -->
            <div class="lg:col-span-2">
                <form @submit.prevent="submit" class="space-y-6">
                    <!-- Domain & Path -->
                    <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                        <h3 class="text-base font-semibold flex items-center gap-2">
                            <GlobeAltIcon class="h-5 w-5 text-indigo-500" />
                            Kurulum Konumu
                        </h3>

                        <div v-if="domains.length === 0" class="mt-3 rounded-lg bg-amber-50 p-3 text-sm text-amber-800">
                            ⚠️ Önce bir domain eklemelisiniz.
                            <Link :href="route('customer.domains.index')" class="font-medium underline">Domainler</Link>
                        </div>

                        <div v-else class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium">Domain</label>
                                <select v-model="form.domain_id" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                                    <option v-for="d in domains" :key="d.id" :value="d.id">{{ d.name }}</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium">Yol</label>
                                <input v-model="form.install_path" type="text" placeholder="/" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                                <p class="mt-1 text-xs text-slate-500"><code>/</code> = kök, <code>/blog</code>, <code>/shop</code> alt yol</p>
                            </div>
                        </div>

                        <div v-if="form.domain_id" class="mt-4 rounded-lg bg-indigo-50 px-3 py-2 text-sm text-indigo-900">
                            🌐 Kurulum URL: <span class="font-mono font-semibold">{{ installPreview() }}</span>
                        </div>

                        <div class="mt-4">
                            <label class="block text-sm font-medium">Versiyon</label>
                            <select v-model="form.version" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                                <option v-for="v in app.available_versions" :key="v" :value="v">{{ v }} {{ v === app.latest_version ? '(en güncel)' : '' }}</option>
                            </select>
                        </div>
                    </div>

                    <!-- Site config -->
                    <div v-if="app.fields" class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
                        <h3 class="text-base font-semibold">Site Ayarları</h3>

                        <div class="mt-4 space-y-4">
                            <div v-if="app.fields.site_title">
                                <label class="block text-sm font-medium">{{ app.fields.site_title.label }}</label>
                                <input v-model="form.site_title" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                            </div>

                            <div v-if="app.fields.admin_username" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium">{{ app.fields.admin_username.label }}</label>
                                    <input v-model="form.admin_username" type="text" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                                </div>
                                <div v-if="app.fields.admin_email">
                                    <label class="block text-sm font-medium">{{ app.fields.admin_email.label }}</label>
                                    <input v-model="form.admin_email" type="email" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                                </div>
                            </div>

                            <div v-if="app.fields.admin_password">
                                <label class="block text-sm font-medium">{{ app.fields.admin_password.label }}</label>
                                <div class="mt-1 flex gap-2">
                                    <input v-model="form.admin_password" type="text" class="flex-1 rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                                    <button type="button" @click="generatePassword" class="rounded-lg border border-slate-300 bg-white px-3 hover:bg-slate-50">
                                        <KeyIcon class="h-4 w-4" />
                                    </button>
                                </div>
                                <p class="mt-1 text-xs text-slate-500">Min 8 karakter. Parolayı kaydetmeyi unutmayın — geri gösterilemez.</p>
                            </div>

                            <div v-if="app.fields.language">
                                <label class="block text-sm font-medium">{{ app.fields.language.label }}</label>
                                <select v-model="form.language" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                                    <option v-for="(name, code) in (app.fields.language.options || { tr_TR: 'Türkçe', en_US: 'English' })" :key="code" :value="code">{{ name }}</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Auto provisioning info -->
                    <div class="rounded-xl border border-indigo-200 bg-indigo-50 p-4 text-sm text-indigo-900">
                        <div class="flex gap-3">
                            <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-indigo-600" />
                            <div>
                                <strong>Otomatik Yapılacaklar:</strong>
                                <ul class="mt-1 list-disc list-inside text-xs space-y-0.5">
                                    <li v-if="app.requires_db">Yeni MySQL veritabanı + kullanıcı + ALL grant</li>
                                    <li>Uygulama dosyalarının açılması (wget veya git clone)</li>
                                    <li>{{ app.slug === 'wordpress' ? 'wp-config.php' : app.slug === 'laravel' ? '.env + APP_KEY' : 'Config dosyası' }} üretimi</li>
                                    <li>Dosya izinleri (chown, chmod)</li>
                                    <li>Admin hesabının oluşturulması</li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <!-- Submit -->
                    <div class="flex justify-end gap-3">
                        <Link :href="route('customer.apps.catalog')" class="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                            İptal
                        </Link>
                        <button type="submit" :disabled="form.processing || !form.domain_id"
                                class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-6 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-700 disabled:opacity-50">
                            <ArrowDownTrayIcon class="h-4 w-4" />
                            {{ form.processing ? 'Kuruluyor...' : 'Hemen Kur' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </CustomerLayout>
</template>
