<script setup>
import { ref, computed } from 'vue'
import { Head, router, useForm } from '@inertiajs/vue3'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    CloudIcon,
    PlusIcon,
    KeyIcon,
    PowerIcon,
    TrashIcon,
    XMarkIcon,
    DocumentDuplicateIcon,
    InformationCircleIcon,
    ComputerDesktopIcon,
    CheckIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    webdisks: Array,
    hostname: String,
    account_username: String,
    webdav_port_ssl: Number,
    webdav_port_plain: Number,
})

const showForm = ref(false)
const showPasswordForm = ref(false)
const showInstructions = ref(false)
const editingWebdisk = ref(null)
const copied = ref(null)

const form = useForm({
    username: '',
    password: '',
    home_path: '/',
    permission: 'read_write',
    use_digest_auth: true,
    quota_mb: null,
})

const passwordForm = useForm({ password: '' })

const submit = () => form.post(route('customer.webdisk.store'), {
    preserveScroll: true,
    onSuccess: () => { showForm.value = false; form.reset(); form.permission = 'read_write'; form.use_digest_auth = true },
})

const submitPassword = () => {
    passwordForm.post(route('customer.webdisk.password', editingWebdisk.value.id), {
        preserveScroll: true,
        onSuccess: () => { showPasswordForm.value = false; passwordForm.reset() },
    })
}

const openPasswordForm = (w) => {
    editingWebdisk.value = w
    passwordForm.password = generatePassword()
    showPasswordForm.value = true
}

const showHowTo = (w) => {
    editingWebdisk.value = w
    showInstructions.value = true
}

const remove = async (w) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `'${w.username}' WebDisk hesabı silinecek?`,
        variant: 'danger',
        confirmText: 'Sil',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.delete(route('customer.webdisk.destroy', w.id), { preserveScroll: true })
}

const toggle = (w) => router.post(route('customer.webdisk.toggle', w.id), {}, { preserveScroll: true })

const generatePassword = () => {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    let p = ''
    for (let i = 0; i < 16; i++) p += chars.charAt(Math.floor(Math.random() * chars.length))
    return p
}

const copyText = (text, key) => {
    navigator.clipboard.writeText(text)
    copied.value = key
    setTimeout(() => copied.value = null, 1500)
}
</script>

<template>
    <Head title="Web Disk (WebDAV)" />
    <CustomerLayout>
        <template #header>Web Disk (WebDAV)</template>

        <div class="mb-4 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>Web Disk:</strong> Dosyalarına Windows Explorer, macOS Finder veya Linux Nautilus üzerinden
                    ağ sürücüsü gibi erişebilirsin. WebDAV protokolü kullanır. Birden fazla WebDisk hesabı
                    oluşturup farklı kişilere farklı izinler verebilirsin.
                </div>
            </div>
        </div>

        <div class="mb-4 flex justify-end">
            <button @click="showForm = true" class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">
                <PlusIcon class="h-4 w-4" /> Yeni WebDisk Hesabı
            </button>
        </div>

        <div v-if="webdisks.length === 0" class="rounded-xl border border-dashed border-slate-300 bg-white p-12 text-center">
            <CloudIcon class="mx-auto h-14 w-14 text-slate-300" />
            <h3 class="mt-3 text-lg font-semibold">Henüz WebDisk hesabı yok</h3>
            <p class="mt-1 text-sm text-slate-500">Bilgisayarından dosyalara doğrudan erişmek için bir WebDisk oluştur.</p>
        </div>

        <div v-else class="space-y-3">
            <div v-for="w in webdisks" :key="w.id" class="rounded-xl border border-slate-200 bg-white p-5 shadow-sm hover:shadow-md transition">
                <div class="flex items-start justify-between gap-3 flex-wrap">
                    <div class="flex items-start gap-3">
                        <div class="flex h-12 w-12 items-center justify-center rounded-xl bg-blue-100">
                            <CloudIcon class="h-7 w-7 text-blue-600" />
                        </div>
                        <div>
                            <div class="flex items-center gap-2 flex-wrap">
                                <h3 class="font-mono font-semibold">{{ w.username }}</h3>
                                <span v-if="w.is_active" class="rounded bg-emerald-100 px-1.5 py-0.5 text-[10px] font-semibold text-emerald-700">AKTİF</span>
                                <span v-else class="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-semibold text-slate-500">PASIF</span>
                                <span :class="['rounded px-1.5 py-0.5 text-[10px] font-semibold', w.permission === 'read_write' ? 'bg-blue-100 text-blue-700' : 'bg-amber-100 text-amber-700']">
                                    {{ w.permission === 'read_write' ? 'Okuma+Yazma' : 'Sadece Okuma' }}
                                </span>
                                <span v-if="w.use_digest_auth" class="rounded bg-purple-100 px-1.5 py-0.5 text-[10px] font-semibold text-purple-700">DIGEST AUTH</span>
                            </div>
                            <p class="font-mono text-xs text-slate-500 mt-1">{{ w.home_path }}</p>
                            <p class="text-xs text-slate-400 mt-0.5">
                                {{ w.created_at }}
                                <span v-if="w.last_access_at" class="ml-2">· Son erişim: {{ w.last_access_at }}</span>
                            </p>
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-1">
                        <button @click="showHowTo(w)" class="inline-flex items-center gap-1 rounded-lg border border-indigo-300 bg-indigo-50 px-3 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100">
                            <ComputerDesktopIcon class="h-3.5 w-3.5" /> Kurulum
                        </button>
                        <button @click="openPasswordForm(w)" class="rounded p-1.5 text-amber-600 hover:bg-amber-50" title="Parola değiştir">
                            <KeyIcon class="h-4 w-4" />
                        </button>
                        <button @click="toggle(w)" :class="['rounded p-1.5', w.is_active ? 'text-amber-500 hover:bg-amber-50' : 'text-emerald-500 hover:bg-emerald-50']">
                            <PowerIcon class="h-4 w-4" />
                        </button>
                        <button @click="remove(w)" class="rounded p-1.5 text-red-500 hover:bg-red-50">
                            <TrashIcon class="h-4 w-4" />
                        </button>
                    </div>
                </div>

                <div class="mt-3 rounded-lg bg-slate-50 p-2 flex items-center justify-between gap-2">
                    <code class="font-mono text-xs text-slate-700 truncate flex-1">{{ w.webdav_url }}</code>
                    <button @click="copyText(w.webdav_url, 'url-'+w.id)" class="rounded p-1 hover:bg-slate-200">
                        <CheckIcon v-if="copied === 'url-'+w.id" class="h-3.5 w-3.5 text-emerald-500" />
                        <DocumentDuplicateIcon v-else class="h-3.5 w-3.5 text-slate-500" />
                    </button>
                </div>
            </div>
        </div>

        <!-- Create modal -->
        <div v-if="showForm" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Yeni WebDisk Hesabı</h3>
                    <button @click="showForm = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>
                <form @submit.prevent="submit" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium">Kullanıcı Adı</label>
                        <input v-model="form.username" type="text" placeholder="webuser1"
                               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">Küçük harf + rakam + alt çizgi. Min 3, max 32.</p>
                        <p v-if="form.errors.username" class="text-xs text-red-600">{{ form.errors.username }}</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Parola</label>
                        <div class="mt-1 flex gap-2">
                            <input v-model="form.password" type="text" class="flex-1 rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                            <button type="button" @click="form.password = generatePassword()" class="rounded-lg border border-slate-300 bg-white px-3 hover:bg-slate-50">
                                <KeyIcon class="h-4 w-4" />
                            </button>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Erişim Yolu</label>
                        <input v-model="form.home_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> = tüm ev dizini, <code>/public_html</code> = sadece web kökü
                        </p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">İzinler</label>
                        <select v-model="form.permission" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                            <option value="read_write">Okuma + Yazma (tam yetki)</option>
                            <option value="read">Sadece Okuma</option>
                        </select>
                    </div>
                    <label class="flex items-center gap-2 cursor-pointer text-sm">
                        <input v-model="form.use_digest_auth" type="checkbox" />
                        <span>Digest Auth kullan (önerilen, daha güvenli)</span>
                    </label>
                    <div class="flex justify-end gap-2 border-t pt-3">
                        <button type="button" @click="showForm = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="form.processing" class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">Oluştur</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Password modal -->
        <div v-if="showPasswordForm" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Parola Değiştir</h3>
                    <button @click="showPasswordForm = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>
                <form @submit.prevent="submitPassword" class="space-y-4">
                    <div class="rounded-lg bg-slate-50 p-3 text-sm">
                        <span class="font-mono">{{ editingWebdisk?.username }}</span>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Yeni Parola</label>
                        <div class="mt-1 flex gap-2">
                            <input v-model="passwordForm.password" type="text" class="flex-1 rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                            <button type="button" @click="passwordForm.password = generatePassword()" class="rounded-lg border border-slate-300 bg-white px-3 hover:bg-slate-50">
                                <KeyIcon class="h-4 w-4" />
                            </button>
                        </div>
                    </div>
                    <div class="flex justify-end gap-2 border-t pt-3">
                        <button type="button" @click="showPasswordForm = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="passwordForm.processing" class="rounded-lg bg-amber-600 px-4 py-2 text-sm font-medium text-white hover:bg-amber-700">Değiştir</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Mount instructions modal -->
        <div v-if="showInstructions && editingWebdisk" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-2xl rounded-xl bg-white p-6 shadow-xl max-h-[90vh] overflow-y-auto">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Kurulum Talimatları</h3>
                    <button @click="showInstructions = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>

                <div class="rounded-lg bg-indigo-50 p-3 text-sm mb-4">
                    <strong>{{ editingWebdisk.username }}</strong> için WebDAV URL'i:
                    <code class="block mt-1 font-mono text-xs">{{ editingWebdisk.webdav_url }}</code>
                </div>

                <div class="space-y-4">
                    <!-- Windows -->
                    <div class="rounded-lg border border-slate-200 p-4">
                        <div class="flex items-center gap-2 mb-2">
                            <span class="text-2xl">🪟</span>
                            <h4 class="font-semibold">Windows 10/11</h4>
                        </div>
                        <ol class="text-xs space-y-1 list-decimal list-inside text-slate-700">
                            <li>"Bu PC" aç → Üst menüde <strong>"Ağ sürücüsü bağla"</strong></li>
                            <li>Sürücü harfi seç (örn: <code>W:</code>)</li>
                            <li>Klasör: <code class="bg-slate-100 px-1">{{ editingWebdisk.webdav_url }}</code></li>
                            <li>"Farklı kimlik bilgileri kullanarak bağlan" işaretle</li>
                            <li>Kullanıcı: <code>{{ editingWebdisk.username }}</code>, Parola: WebDisk parolası</li>
                        </ol>
                    </div>

                    <!-- macOS -->
                    <div class="rounded-lg border border-slate-200 p-4">
                        <div class="flex items-center gap-2 mb-2">
                            <span class="text-2xl">🍎</span>
                            <h4 class="font-semibold">macOS</h4>
                        </div>
                        <ol class="text-xs space-y-1 list-decimal list-inside text-slate-700">
                            <li>Finder aç → <strong>Cmd+K</strong> (veya Git → Sunucuya Bağlan)</li>
                            <li>Sunucu adresi: <code class="bg-slate-100 px-1">{{ editingWebdisk.webdav_url }}</code></li>
                            <li>"Bağlan" tıkla → Kayıtlı kullanıcı seç</li>
                            <li>Kullanıcı: <code>{{ editingWebdisk.username }}</code>, Parola gir</li>
                        </ol>
                    </div>

                    <!-- Linux -->
                    <div class="rounded-lg border border-slate-200 p-4">
                        <div class="flex items-center gap-2 mb-2">
                            <span class="text-2xl">🐧</span>
                            <h4 class="font-semibold">Linux (Ubuntu/GNOME)</h4>
                        </div>
                        <ol class="text-xs space-y-1 list-decimal list-inside text-slate-700">
                            <li>Nautilus aç → "Diğer Konumlar"</li>
                            <li>Alt kısımda "Sunucuya Bağlan"</li>
                            <li>URL: <code class="bg-slate-100 px-1">davs://{{ hostname }}:{{ webdav_port_ssl }}/webdav/{{ account_username }}</code></li>
                            <li>Auth: <code>{{ editingWebdisk.username }}</code></li>
                        </ol>
                        <details class="mt-2">
                            <summary class="text-xs cursor-pointer text-slate-600">CLI ile mount (davfs2)</summary>
                            <pre class="mt-2 rounded bg-slate-900 p-2 font-mono text-xs text-slate-200 overflow-x-auto">sudo apt install davfs2
sudo mkdir /mnt/webdisk
sudo mount -t davfs {{ editingWebdisk.webdav_url }} /mnt/webdisk</pre>
                        </details>
                    </div>

                    <!-- Mobile -->
                    <div class="rounded-lg border border-slate-200 p-4">
                        <div class="flex items-center gap-2 mb-2">
                            <span class="text-2xl">📱</span>
                            <h4 class="font-semibold">Mobil</h4>
                        </div>
                        <ul class="text-xs space-y-1 text-slate-700">
                            <li>• <strong>iOS:</strong> Files app → Connect Server → URL gir</li>
                            <li>• <strong>Android:</strong> CX File Explorer veya FE File Explorer → WebDAV add</li>
                            <li>• Solid Explorer, RaiDrive (Win), Cyberduck — popüler WebDAV client'lar</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </CustomerLayout>
</template>
