<script setup>
import ResellerLayout from '@/Layouts/ResellerLayout.vue'
import { useForm, router } from '@inertiajs/vue3'
import { ref, computed } from 'vue'
import axios from 'axios'
import {
    PhotoIcon,
    CheckCircleIcon,
    XCircleIcon,
    ExclamationTriangleIcon,
    ArrowPathIcon,
    ServerStackIcon,
    LockClosedIcon,
    GlobeAltIcon,
    BoltIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    branding: Object,
    status: { type: Object, default: () => null },
})

const form = useForm({
    brand_name:           props.branding.brand_name || '',
    primary_color:        props.branding.primary_color || '#3b82f6',
    support_email:        props.branding.support_email || '',
    support_phone:        props.branding.support_phone || '',
    white_label_hostname: props.branding.white_label_hostname || '',
})

const logoForm = useForm({ logo: null })
const logoPreview = ref(props.branding.logo_url || null)

function onLogoChange(e) {
    const file = e.target.files[0]
    if (!file) return
    logoForm.logo = file
    logoPreview.value = URL.createObjectURL(file)
}

function submitLogo() {
    logoForm.post(route('reseller.branding.logo'), {
        forceFormData: true,
        onSuccess: () => {},
    })
}

function submitBranding() {
    form.patch(route('reseller.branding.update'))
}

// Live preview
const previewName  = computed(() => form.brand_name || 'Bayi Paneli')
const previewColor = computed(() => form.primary_color || '#3b82f6')

// White-label diagnostic
const statusData = ref(props.status || null)
const statusRefreshing = ref(false)

const refreshStatus = async () => {
    statusRefreshing.value = true
    try {
        const res = await axios.get(route('reseller.branding.status'))
        statusData.value = res.data
    } catch {} finally {
        statusRefreshing.value = false
    }
}

const reapply = () => {
    router.post(route('reseller.branding.reapply'), {}, {
        onSuccess: () => refreshStatus(),
    })
}

const overallBadge = computed(() => ({
    ok: { class: 'bg-emerald-100 text-emerald-700', label: 'Aktif & Sağlıklı', icon: CheckCircleIcon },
    partial: { class: 'bg-amber-100 text-amber-700', label: 'Kısmen Hazır', icon: ExclamationTriangleIcon },
    failed: { class: 'bg-red-100 text-red-700', label: 'Başarısız', icon: XCircleIcon },
    no_hostname: { class: 'bg-slate-100 text-slate-600', label: 'Tanımsız', icon: GlobeAltIcon },
}[statusData.value?.overall || 'no_hostname']))
</script>

<template>
    <ResellerLayout>
        <template #header>Markalama</template>

        <div class="grid grid-cols-1 gap-6 lg:grid-cols-3">

            <!-- Sol: Form -->
            <div class="lg:col-span-2 space-y-6">

                <!-- Logo yükleme -->
                <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
                    <h2 class="mb-4 font-semibold text-slate-900 dark:text-slate-100">Logo</h2>
                    <div class="flex items-start gap-4">
                        <div class="flex h-20 w-20 flex-shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-slate-50 dark:border-slate-700 dark:bg-slate-800">
                            <img v-if="logoPreview" :src="logoPreview" alt="Logo" class="h-16 w-16 object-contain rounded" />
                            <PhotoIcon v-else class="h-8 w-8 text-slate-300" />
                        </div>
                        <div class="flex-1">
                            <label class="block text-sm text-slate-600 dark:text-slate-400 mb-2">
                                PNG, JPG, WebP — max 2MB
                            </label>
                            <input
                                type="file"
                                accept="image/*"
                                @change="onLogoChange"
                                class="block w-full text-sm text-slate-500 file:mr-4 file:rounded-lg file:border-0 file:bg-blue-50 file:px-4 file:py-2 file:text-sm file:font-medium file:text-blue-700 hover:file:bg-blue-100"
                            />
                            <button
                                v-if="logoForm.logo"
                                @click="submitLogo"
                                :disabled="logoForm.processing"
                                class="mt-2 rounded-lg bg-blue-600 px-4 py-1.5 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-60"
                            >
                                Yükle
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Marka bilgileri formu -->
                <div class="rounded-xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
                    <h2 class="mb-4 font-semibold text-slate-900 dark:text-slate-100">Marka Bilgileri</h2>
                    <form @submit.prevent="submitBranding" class="space-y-4">

                        <!-- Ad + Renk -->
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                                    Marka Adı
                                </label>
                                <input
                                    v-model="form.brand_name"
                                    type="text"
                                    placeholder="Örn: ABC Hosting"
                                    class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200"
                                />
                                <p v-if="form.errors.brand_name" class="mt-1 text-xs text-red-600">{{ form.errors.brand_name }}</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                                    Birincil Renk
                                </label>
                                <div class="flex items-center gap-2">
                                    <input
                                        v-model="form.primary_color"
                                        type="color"
                                        class="h-9 w-12 cursor-pointer rounded border border-slate-300 p-0.5"
                                    />
                                    <input
                                        v-model="form.primary_color"
                                        type="text"
                                        placeholder="#3b82f6"
                                        class="flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200"
                                    />
                                </div>
                                <p v-if="form.errors.primary_color" class="mt-1 text-xs text-red-600">{{ form.errors.primary_color }}</p>
                            </div>
                        </div>

                        <!-- Destek bilgileri -->
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                                    Destek E-posta
                                </label>
                                <input
                                    v-model="form.support_email"
                                    type="email"
                                    placeholder="destek@sirket.com"
                                    class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200"
                                />
                                <p v-if="form.errors.support_email" class="mt-1 text-xs text-red-600">{{ form.errors.support_email }}</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                                    Destek Telefon
                                </label>
                                <input
                                    v-model="form.support_phone"
                                    type="tel"
                                    placeholder="+90 212 000 00 00"
                                    class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200"
                                />
                                <p v-if="form.errors.support_phone" class="mt-1 text-xs text-red-600">{{ form.errors.support_phone }}</p>
                            </div>
                        </div>

                        <!-- White-label hostname -->
                        <div>
                            <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                                White-Label Panel Domain
                                <span class="ml-1 text-xs font-normal text-slate-400">(isteğe bağlı)</span>
                            </label>
                            <input
                                v-model="form.white_label_hostname"
                                type="text"
                                placeholder="panel.firmaniz.com"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800 dark:text-slate-200"
                            />
                            <p class="mt-1 text-xs text-slate-400">
                                Alan adını sunucunun IP'sine A kaydı olarak yönlendirmeniz gerekir. SSL otomatik atanır.
                            </p>
                            <p v-if="form.errors.white_label_hostname" class="mt-1 text-xs text-red-600">{{ form.errors.white_label_hostname }}</p>
                        </div>

                        <!-- White-label diagnostic status -->
                        <div v-if="statusData && statusData.hostname"
                             class="rounded-lg border border-slate-200 bg-slate-50 p-4 dark:border-slate-700 dark:bg-slate-800/50">
                            <div class="mb-3 flex items-center justify-between">
                                <h4 class="flex items-center gap-2 text-sm font-semibold text-slate-800 dark:text-slate-200">
                                    <BoltIcon class="h-4 w-4 text-indigo-500" /> White-Label Durumu
                                </h4>
                                <div class="flex items-center gap-2">
                                    <span :class="['inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium', overallBadge.class]">
                                        <component :is="overallBadge.icon" class="h-3.5 w-3.5" />
                                        {{ overallBadge.label }}
                                    </span>
                                    <button type="button" @click="refreshStatus" :disabled="statusRefreshing"
                                            class="inline-flex items-center gap-1 rounded p-1 text-slate-500 hover:bg-slate-200 hover:text-indigo-600 disabled:opacity-50">
                                        <ArrowPathIcon class="h-3.5 w-3.5" :class="statusRefreshing ? 'animate-spin' : ''" />
                                    </button>
                                </div>
                            </div>

                            <div class="space-y-2 text-xs">
                                <!-- DNS check -->
                                <div class="flex items-start gap-2 rounded bg-white p-2 dark:bg-slate-900">
                                    <GlobeAltIcon :class="['h-4 w-4 mt-0.5 flex-shrink-0', statusData.dns.ok ? 'text-emerald-500' : 'text-red-500']" />
                                    <div class="flex-1">
                                        <p class="font-medium text-slate-800 dark:text-slate-200">
                                            DNS A Record
                                            <CheckCircleIcon v-if="statusData.dns.ok" class="inline h-3.5 w-3.5 text-emerald-600" />
                                            <XCircleIcon v-else class="inline h-3.5 w-3.5 text-red-500" />
                                        </p>
                                        <p class="text-slate-600 dark:text-slate-400">{{ statusData.dns.message }}</p>
                                        <p v-if="!statusData.dns.ok && statusData.dns.expected" class="mt-1 font-mono text-[10px] text-slate-500">
                                            Registrar'a ekleyin: <strong>{{ statusData.hostname }}</strong> A → <strong>{{ statusData.dns.expected }}</strong>
                                        </p>
                                    </div>
                                </div>

                                <!-- Vhost check -->
                                <div class="flex items-start gap-2 rounded bg-white p-2 dark:bg-slate-900">
                                    <ServerStackIcon :class="['h-4 w-4 mt-0.5 flex-shrink-0', statusData.vhost.ok ? 'text-emerald-500' : 'text-amber-500']" />
                                    <div class="flex-1">
                                        <p class="font-medium text-slate-800 dark:text-slate-200">
                                            Apache Vhost
                                            <CheckCircleIcon v-if="statusData.vhost.ok" class="inline h-3.5 w-3.5 text-emerald-600" />
                                            <XCircleIcon v-else class="inline h-3.5 w-3.5 text-amber-500" />
                                        </p>
                                        <p class="text-slate-600 dark:text-slate-400">{{ statusData.vhost.message }}</p>
                                    </div>
                                </div>

                                <!-- SSL check -->
                                <div class="flex items-start gap-2 rounded bg-white p-2 dark:bg-slate-900">
                                    <LockClosedIcon :class="['h-4 w-4 mt-0.5 flex-shrink-0', statusData.ssl.ok ? 'text-emerald-500' : 'text-amber-500']" />
                                    <div class="flex-1">
                                        <p class="font-medium text-slate-800 dark:text-slate-200">
                                            SSL Sertifikası
                                            <CheckCircleIcon v-if="statusData.ssl.ok" class="inline h-3.5 w-3.5 text-emerald-600" />
                                            <XCircleIcon v-else class="inline h-3.5 w-3.5 text-amber-500" />
                                        </p>
                                        <p class="text-slate-600 dark:text-slate-400">{{ statusData.ssl.message }}</p>
                                    </div>
                                </div>
                            </div>

                            <div v-if="statusData.overall !== 'ok'" class="mt-3 flex gap-2">
                                <button type="button" @click="reapply"
                                        class="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-700">
                                    <ArrowPathIcon class="h-3.5 w-3.5" />
                                    Vhost + SSL Yeniden Uygula
                                </button>
                                <span class="text-[10px] self-center text-slate-500">
                                    DNS hazırsa SSL otomatik alınır (1-3 dk)
                                </span>
                            </div>
                        </div>

                        <div class="flex justify-end">
                            <button
                                type="submit"
                                :disabled="form.processing"
                                class="rounded-lg bg-blue-600 px-5 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-60"
                            >
                                Kaydet
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Sağ: Canlı Önizleme -->
            <div class="lg:col-span-1">
                <div class="sticky top-24 rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900 overflow-hidden">
                    <div class="border-b border-slate-200 px-4 py-3 dark:border-slate-700">
                        <h3 class="text-sm font-medium text-slate-600 dark:text-slate-400">Canlı Önizleme</h3>
                    </div>
                    <!-- Mini sidebar preview -->
                    <div class="flex h-56">
                        <div class="w-16 bg-slate-900 flex flex-col items-center py-4 gap-3">
                            <div
                                class="flex h-9 w-9 items-center justify-center rounded-full text-xs font-bold text-white"
                                :style="{ backgroundColor: previewColor }"
                            >
                                {{ previewName.charAt(0).toUpperCase() }}
                            </div>
                            <div class="mt-2 space-y-2 w-10">
                                <div class="h-2 rounded" :style="{ backgroundColor: previewColor }"></div>
                                <div class="h-2 rounded bg-slate-700"></div>
                                <div class="h-2 rounded bg-slate-700"></div>
                                <div class="h-2 rounded bg-slate-700"></div>
                            </div>
                        </div>
                        <div class="flex-1 flex flex-col">
                            <div class="h-10 border-b border-slate-200 dark:border-slate-700 flex items-center px-3">
                                <span class="text-xs font-semibold text-slate-900 dark:text-slate-100">{{ previewName }}</span>
                            </div>
                            <div class="flex-1 p-3 space-y-2">
                                <div class="grid grid-cols-3 gap-1">
                                    <div
                                        v-for="i in 6"
                                        :key="i"
                                        class="h-8 rounded border border-slate-200 dark:border-slate-700"
                                    ></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="px-4 py-3 bg-slate-50 dark:bg-slate-800/50">
                        <div class="text-xs text-slate-500 space-y-0.5">
                            <div v-if="form.support_email">
                                <span class="font-medium">E-posta:</span> {{ form.support_email }}
                            </div>
                            <div v-if="form.support_phone">
                                <span class="font-medium">Tel:</span> {{ form.support_phone }}
                            </div>
                            <div v-if="form.white_label_hostname" class="font-mono">
                                {{ form.white_label_hostname }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </ResellerLayout>
</template>
