<script setup>
import { ref, computed, watch } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import { debounce } from 'lodash'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import {
    CheckIcon,
    XMarkIcon,
    FunnelIcon,
    ArrowDownTrayIcon,
    EnvelopeIcon,
    NoSymbolIcon,
    PlayIcon,
    TrashIcon,
    TagIcon,
    ServerStackIcon,
    ArrowsRightLeftIcon,
    CubeIcon,
    ExclamationTriangleIcon,
    MagnifyingGlassIcon,
    AdjustmentsHorizontalIcon,
} from '@heroicons/vue/24/outline'

const props = defineProps({
    accounts:  { type: Object, required: true },
    packages:  { type: Array,  required: true },
    resellers: { type: Array,  required: true },
    stats:     { type: Object, required: true },
    filters:   { type: Object, required: true },
})

// ─── Filter state ─────────────────────────────────────────────────────────
const search     = ref(props.filters.search ?? '')
const status     = ref(props.filters.status ?? '')
const packageId  = ref(props.filters.package_id ?? '')
const resellerId = ref(props.filters.reseller_id ?? '')
const sort       = ref(props.filters.sort ?? 'created_at')
const direction  = ref(props.filters.direction ?? 'desc')

const applyFilters = () => {
    router.get(route('admin.accounts.bulk-modifier.index'), {
        search:      search.value || undefined,
        status:      status.value || undefined,
        package_id:  packageId.value || undefined,
        reseller_id: resellerId.value || undefined,
        sort:        sort.value,
        direction:   direction.value,
    }, { preserveState: true, replace: true })
}

watch(search, debounce(applyFilters, 350))

const exportUrl = computed(() => {
    const params = new URLSearchParams()
    if (search.value)     params.set('search', search.value)
    if (status.value)     params.set('status', status.value)
    if (packageId.value)  params.set('package_id', packageId.value)
    if (resellerId.value) params.set('reseller_id', resellerId.value)
    return route('admin.accounts.bulk-modifier.export') + '?' + params.toString()
})

// ─── Selection ─────────────────────────────────────────────────────────────
const selectedIds = ref([])

const allSelected = computed(
    () => props.accounts.data.length > 0 && props.accounts.data.every(a => selectedIds.value.includes(a.id))
)

const toggleAll = () => {
    if (allSelected.value) {
        selectedIds.value = selectedIds.value.filter(id => !props.accounts.data.find(a => a.id === id))
    } else {
        const newIds = props.accounts.data.map(a => a.id)
        selectedIds.value = [...new Set([...selectedIds.value, ...newIds])]
    }
}

// ─── Action modal ──────────────────────────────────────────────────────────
const showModal       = ref(false)
const activeAction    = ref('')
const packagePayload  = ref('')
const quotaMb         = ref('')
const suspendReason   = ref('')
const terminateConfirm = ref('')
const emailSubject    = ref('')
const emailBody       = ref('')
const tagValue        = ref('')
const newResellerId   = ref('')

const actionDefs = [
    { key: 'change_package',    label: 'Paket Değiştir',       icon: CubeIcon,             color: 'indigo' },
    { key: 'set_quota',         label: 'Kota Ayarla',          icon: ServerStackIcon,      color: 'indigo' },
    { key: 'suspend',           label: 'Askıya Al',            icon: NoSymbolIcon,         color: 'amber'  },
    { key: 'unsuspend',         label: 'Askıdan Çıkar',        icon: PlayIcon,             color: 'emerald'},
    { key: 'terminate',         label: 'Sonlandır (Sil)',      icon: TrashIcon,            color: 'red'    },
    { key: 'send_email',        label: 'E-posta Gönder',       icon: EnvelopeIcon,         color: 'blue'   },
    { key: 'add_tag',           label: 'Etiket Ekle',          icon: TagIcon,              color: 'violet' },
    { key: 'transfer_reseller', label: 'Bayi\'ye Transfer Et', icon: ArrowsRightLeftIcon,  color: 'orange' },
]

const currentActionDef = computed(() => actionDefs.find(a => a.key === activeAction.value))

const openModal = (actionKey) => {
    activeAction.value     = actionKey
    packagePayload.value   = ''
    quotaMb.value          = ''
    suspendReason.value    = ''
    terminateConfirm.value = ''
    emailSubject.value     = ''
    emailBody.value        = ''
    tagValue.value         = ''
    newResellerId.value    = ''
    showModal.value        = true
}

const isDestructive = computed(() => activeAction.value === 'terminate')

const terminateReady = computed(() => terminateConfirm.value === 'EVET KESIN SIL')

const canSubmit = computed(() => {
    if (selectedIds.value.length === 0) return false
    switch (activeAction.value) {
        case 'change_package':    return !!packagePayload.value
        case 'set_quota':         return quotaMb.value !== '' && Number(quotaMb.value) >= 0
        case 'terminate':         return terminateReady.value
        case 'send_email':        return !!emailSubject.value && !!emailBody.value
        case 'add_tag':           return !!tagValue.value
        case 'transfer_reseller': return !!newResellerId.value
        default:                  return true
    }
})

const truncatedSelected = computed(() => {
    const data  = props.accounts.data.filter(a => selectedIds.value.includes(a.id))
    const first = data.slice(0, 10)
    const rest  = selectedIds.value.length - first.length
    return { first, rest }
})

const submitAction = () => {
    const payload = {
        account_ids: selectedIds.value,
        action:      activeAction.value,
    }

    switch (activeAction.value) {
        case 'change_package':    payload.package_id      = packagePayload.value;    break
        case 'set_quota':         payload.quota_mb         = Number(quotaMb.value);   break
        case 'suspend':           payload.reason           = suspendReason.value;     break
        case 'terminate':         payload.confirm_string   = terminateConfirm.value;  break
        case 'send_email':        payload.subject          = emailSubject.value;
                                  payload.body             = emailBody.value;         break
        case 'add_tag':           payload.tag              = tagValue.value;          break
        case 'transfer_reseller': payload.new_reseller_id  = newResellerId.value;     break
    }

    router.post(route('admin.accounts.bulk-modifier.apply'), payload, {
        preserveScroll: true,
        onSuccess: () => {
            showModal.value   = false
            selectedIds.value = []
        },
    })
}

// ─── Helpers ───────────────────────────────────────────────────────────────
const statusBadge = (color) => ({
    green:  'bg-emerald-100 text-emerald-700 ring-emerald-200',
    amber:  'bg-amber-100  text-amber-700  ring-amber-200',
    orange: 'bg-amber-100  text-amber-700  ring-amber-200',
    red:    'bg-red-100    text-red-700    ring-red-200',
}[color] ?? 'bg-slate-100 text-slate-700 ring-slate-200')

const quotaBar = (pct) => ({
    width: Math.min(pct ?? 0, 100) + '%',
    class: pct > 90 ? 'bg-red-500' : pct > 70 ? 'bg-amber-500' : 'bg-emerald-500',
})

const fmtMb = (bytes) => {
    if (bytes == null) return '—'
    const mb = bytes / 1024 / 1024
    return mb >= 1024 ? (mb / 1024).toFixed(1) + ' GB' : Math.round(mb) + ' MB'
}

const btnColor = (color) => ({
    indigo:  'bg-indigo-600 hover:bg-indigo-700',
    amber:   'bg-amber-500  hover:bg-amber-600',
    emerald: 'bg-emerald-600 hover:bg-emerald-700',
    red:     'bg-red-600    hover:bg-red-700',
    blue:    'bg-blue-600   hover:bg-blue-700',
    violet:  'bg-violet-600 hover:bg-violet-700',
    orange:  'bg-orange-500 hover:bg-orange-600',
}[color] ?? 'bg-slate-600 hover:bg-slate-700')
</script>

<template>
    <Head title="Toplu Hesap Düzenleme" />

    <AdminLayout>
        <template #header>Toplu Hesap Düzenleme</template>

        <!-- Stat cards -->
        <div class="mb-5 grid grid-cols-2 gap-3 sm:grid-cols-4">
            <button
                v-for="[key, label, color] in [
                    ['active',     'Aktif',          'emerald'],
                    ['suspended',  'Askıda',          'amber'  ],
                    ['terminated', 'Sonlandırıldı',   'red'    ],
                    ['pending',    'Bekliyor',         'slate'  ],
                ]"
                :key="key"
                @click="status = status === key ? '' : key; applyFilters()"
                :class="[
                    'rounded-xl border p-4 text-left shadow-sm transition-colors',
                    status === key ? 'ring-2 ring-indigo-500' : '',
                    color === 'emerald' ? 'border-emerald-200 bg-emerald-50' :
                    color === 'amber'   ? 'border-amber-200   bg-amber-50'   :
                    color === 'red'     ? 'border-red-200     bg-red-50'     :
                                         'border-slate-200    bg-white',
                ]"
            >
                <div class="text-2xl font-bold text-slate-900">{{ stats[key] ?? 0 }}</div>
                <div class="mt-0.5 text-xs font-medium text-slate-500">{{ label }}</div>
            </button>
        </div>

        <!-- Filter bar (sticky) -->
        <div class="sticky top-16 z-20 mb-4 rounded-xl border border-slate-200 bg-white p-3 shadow-sm">
            <div class="flex flex-wrap items-center gap-2">
                <FunnelIcon class="h-4 w-4 flex-shrink-0 text-slate-400" />

                <!-- Search -->
                <div class="relative min-w-[200px] flex-1">
                    <MagnifyingGlassIcon class="absolute left-2.5 top-2 h-4 w-4 text-slate-400" />
                    <input
                        v-model="search"
                        type="text"
                        placeholder="kullanıcı, e-posta, domain..."
                        class="w-full rounded-lg border border-slate-200 py-1.5 pl-8 pr-3 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                    />
                </div>

                <!-- Status -->
                <select v-model="status" @change="applyFilters"
                    class="rounded-lg border border-slate-200 px-3 py-1.5 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500">
                    <option value="">Tüm durumlar</option>
                    <option value="active">Aktif</option>
                    <option value="suspended">Askıda</option>
                    <option value="terminated">Sonlandırıldı</option>
                    <option value="pending">Bekliyor</option>
                </select>

                <!-- Package -->
                <select v-model="packageId" @change="applyFilters"
                    class="rounded-lg border border-slate-200 px-3 py-1.5 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500">
                    <option value="">Tüm paketler</option>
                    <option v-for="p in packages" :key="p.id" :value="p.id">{{ p.name }}</option>
                </select>

                <!-- Reseller -->
                <select v-model="resellerId" @change="applyFilters"
                    class="rounded-lg border border-slate-200 px-3 py-1.5 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500">
                    <option value="">Tüm bayiler</option>
                    <option v-for="r in resellers" :key="r.id" :value="r.id">{{ r.label }}</option>
                </select>

                <div class="flex items-center gap-2 ml-auto">
                    <button @click="applyFilters"
                        class="inline-flex items-center gap-1 rounded-lg bg-indigo-600 px-4 py-1.5 text-sm font-medium text-white hover:bg-indigo-700">
                        <CheckIcon class="h-3.5 w-3.5" /> Uygula
                    </button>
                    <a :href="exportUrl"
                        class="inline-flex items-center gap-1 rounded-lg border border-slate-200 px-3 py-1.5 text-sm text-slate-600 hover:bg-slate-50">
                        <ArrowDownTrayIcon class="h-4 w-4" /> CSV
                    </a>
                </div>
            </div>
        </div>

        <!-- Bulk action bar -->
        <div v-if="selectedIds.length > 0"
            class="mb-3 sticky top-32 z-10 rounded-xl border-2 border-indigo-300 bg-indigo-50 p-3 shadow-lg">
            <div class="flex flex-wrap items-center justify-between gap-3">
                <div class="flex items-center gap-2">
                    <AdjustmentsHorizontalIcon class="h-5 w-5 text-indigo-600" />
                    <span class="text-sm font-semibold text-indigo-900">
                        <strong>{{ selectedIds.length }}</strong> hesap seçildi
                    </span>
                </div>
                <div class="flex flex-wrap items-center gap-1.5">
                    <button
                        v-for="def in actionDefs"
                        :key="def.key"
                        @click="openModal(def.key)"
                        :class="['inline-flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs font-medium text-white', btnColor(def.color)]"
                    >
                        <component :is="def.icon" class="h-3.5 w-3.5" />
                        {{ def.label }}
                    </button>
                    <button @click="selectedIds = []" class="ml-1 text-xs text-slate-500 hover:underline">Temizle</button>
                </div>
            </div>
        </div>

        <!-- Empty state -->
        <div v-if="accounts.data.length === 0" class="rounded-xl border border-dashed border-slate-300 bg-white p-12 text-center">
            <ServerStackIcon class="mx-auto h-14 w-14 text-slate-300" />
            <h3 class="mt-3 text-lg font-semibold text-slate-900">Hesap bulunamadı</h3>
            <p class="mt-1 text-sm text-slate-500">Filtreyi temizleyin veya farklı kriterle arayın.</p>
        </div>

        <!-- Accounts table -->
        <div v-else class="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
            <table class="min-w-full divide-y divide-slate-200">
                <thead class="bg-slate-50">
                    <tr>
                        <th class="w-10 px-3 py-3">
                            <input type="checkbox" :checked="allSelected" @change="toggleAll"
                                class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" />
                        </th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Kullanıcı</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Sahip</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Paket</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Durum</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Kota / Kullanım</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Domain</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">Oluşturma</th>
                        <th class="px-4 py-3"></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <tr
                        v-for="acc in accounts.data"
                        :key="acc.id"
                        :class="['hover:bg-slate-50 transition-colors', selectedIds.includes(acc.id) ? 'bg-indigo-50' : '']"
                    >
                        <!-- Checkbox -->
                        <td class="px-3 py-3">
                            <input type="checkbox" :value="acc.id" v-model="selectedIds"
                                class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" />
                        </td>

                        <!-- Username -->
                        <td class="whitespace-nowrap px-4 py-3">
                            <div class="font-mono text-sm font-medium text-slate-900">{{ acc.username }}</div>
                            <div class="text-xs text-slate-500">{{ acc.email }}</div>
                            <div v-if="acc.primary_domain" class="text-xs text-indigo-600">{{ acc.primary_domain }}</div>
                        </td>

                        <!-- Owner -->
                        <td class="px-4 py-3">
                            <div class="text-sm text-slate-700">{{ acc.owner_name || '—' }}</div>
                            <div class="text-xs text-slate-400">{{ acc.owner_email }}</div>
                        </td>

                        <!-- Package -->
                        <td class="px-4 py-3">
                            <span v-if="acc.package_name"
                                class="inline-flex rounded-full bg-indigo-50 px-2.5 py-0.5 text-xs font-medium text-indigo-700 ring-1 ring-inset ring-indigo-200">
                                {{ acc.package_name }}
                            </span>
                            <span v-else class="text-xs text-slate-400">—</span>
                        </td>

                        <!-- Status -->
                        <td class="px-4 py-3">
                            <span :class="['inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset', statusBadge(acc.status_color)]">
                                {{ acc.status_label }}
                            </span>
                            <div v-if="acc.status === 'suspended' && acc.suspended_reason"
                                class="mt-0.5 text-[10px] text-amber-700 line-clamp-1">
                                {{ acc.suspended_reason }}
                            </div>
                        </td>

                        <!-- Quota -->
                        <td class="px-4 py-3 text-sm">
                            <template v-if="acc.disk_usage_percent !== null">
                                <div class="flex items-center gap-2">
                                    <div class="h-1.5 w-20 overflow-hidden rounded-full bg-slate-200">
                                        <div
                                            :class="['h-full', quotaBar(acc.disk_usage_percent).class]"
                                            :style="{ width: quotaBar(acc.disk_usage_percent).width }"
                                        />
                                    </div>
                                    <span class="whitespace-nowrap text-xs text-slate-600">
                                        {{ fmtMb(acc.disk_usage_bytes) }} / {{ fmtMb(acc.quota_bytes) }}
                                    </span>
                                </div>
                            </template>
                            <span v-else class="text-xs text-slate-400">
                                {{ fmtMb(acc.disk_usage_bytes) }} / sınırsız
                            </span>
                        </td>

                        <!-- Domain count -->
                        <td class="whitespace-nowrap px-4 py-3 text-sm text-slate-600">
                            {{ acc.domains_count ?? 0 }}
                        </td>

                        <!-- Created -->
                        <td class="whitespace-nowrap px-4 py-3 text-xs text-slate-500">{{ acc.created_at }}</td>

                        <!-- Inline actions -->
                        <td class="whitespace-nowrap px-4 py-3 text-right text-xs">
                            <div class="flex items-center justify-end gap-1">
                                <Link :href="route('admin.accounts.show', acc.id)"
                                    class="rounded px-2 py-1 text-slate-500 hover:bg-slate-100 hover:text-slate-700">
                                    Görüntüle
                                </Link>
                                <button
                                    v-if="acc.status === 'active' || acc.status === 'pending'"
                                    @click="selectedIds = [acc.id]; openModal('suspend')"
                                    class="rounded px-2 py-1 text-amber-600 hover:bg-amber-50">
                                    Askıya Al
                                </button>
                                <button
                                    v-if="acc.status === 'suspended'"
                                    @click="selectedIds = [acc.id]; openModal('unsuspend')"
                                    class="rounded px-2 py-1 text-emerald-600 hover:bg-emerald-50">
                                    Aktifleştir
                                </button>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>

            <!-- Pagination -->
            <div v-if="accounts.last_page > 1"
                class="flex items-center justify-between border-t border-slate-200 bg-slate-50 px-4 py-3">
                <div class="text-sm text-slate-600">
                    {{ accounts.from }}–{{ accounts.to }} / {{ accounts.total }} hesap
                </div>
                <div class="flex flex-wrap gap-1">
                    <Link
                        v-for="link in accounts.links"
                        :key="link.label"
                        :href="link.url || '#'"
                        :class="[
                            'rounded px-3 py-1 text-sm',
                            link.active
                                ? 'bg-indigo-600 text-white'
                                : 'text-slate-600 hover:bg-slate-100',
                            !link.url && 'cursor-not-allowed opacity-40 pointer-events-none',
                        ]"
                        v-html="link.label"
                    />
                </div>
            </div>
        </div>

        <!-- ─── Action Modal ──────────────────────────────────────────────── -->
        <Teleport to="body">
            <div v-if="showModal"
                class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4 backdrop-blur-sm">
                <div class="w-full max-w-lg rounded-2xl bg-white shadow-2xl">

                    <!-- Modal header -->
                    <div :class="[
                        'flex items-center justify-between rounded-t-2xl px-6 py-4',
                        isDestructive ? 'bg-red-600' : 'bg-indigo-600',
                    ]">
                        <div class="flex items-center gap-3">
                            <component :is="currentActionDef?.icon" class="h-5 w-5 text-white" />
                            <h3 class="text-base font-semibold text-white">
                                Toplu İşlem: {{ currentActionDef?.label }}
                            </h3>
                        </div>
                        <button @click="showModal = false" class="rounded p-1 text-white/80 hover:text-white">
                            <XMarkIcon class="h-5 w-5" />
                        </button>
                    </div>

                    <div class="p-6 space-y-4">

                        <!-- Selected accounts preview -->
                        <div class="rounded-lg border border-slate-200 bg-slate-50 p-3">
                            <p class="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-500">
                                Etkilenecek hesaplar ({{ selectedIds.length }})
                            </p>
                            <div class="flex flex-wrap gap-1.5">
                                <span
                                    v-for="acc in truncatedSelected.first"
                                    :key="acc.id"
                                    class="inline-flex rounded bg-white px-2 py-0.5 font-mono text-xs text-slate-700 ring-1 ring-slate-200">
                                    {{ acc.username }}
                                </span>
                                <span v-if="truncatedSelected.rest > 0"
                                    class="inline-flex rounded bg-indigo-50 px-2 py-0.5 text-xs text-indigo-700">
                                    +{{ truncatedSelected.rest }} tane daha
                                </span>
                            </div>
                        </div>

                        <!-- change_package -->
                        <div v-if="activeAction === 'change_package'" class="space-y-2">
                            <label class="block text-sm font-medium text-slate-700">Yeni Paket</label>
                            <select v-model="packagePayload"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500">
                                <option value="">Seçiniz...</option>
                                <option v-for="p in packages" :key="p.id" :value="p.id">
                                    {{ p.name }}
                                </option>
                            </select>
                        </div>

                        <!-- set_quota -->
                        <div v-if="activeAction === 'set_quota'" class="space-y-2">
                            <label class="block text-sm font-medium text-slate-700">Kota (MB) — 0 = sınırsız</label>
                            <input v-model="quotaMb" type="number" min="0" step="128" placeholder="örn: 5120"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                        </div>

                        <!-- suspend -->
                        <div v-if="activeAction === 'suspend'" class="space-y-2">
                            <label class="block text-sm font-medium text-slate-700">Askıya alma sebebi (isteğe bağlı)</label>
                            <input v-model="suspendReason" type="text" maxlength="500" placeholder="örn: Ödeme gecikmesi"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                        </div>

                        <!-- unsuspend — no extra fields needed -->
                        <div v-if="activeAction === 'unsuspend'">
                            <p class="text-sm text-slate-600">Seçili hesaplar <strong>Aktif</strong> duruma alınacak.</p>
                        </div>

                        <!-- terminate -->
                        <div v-if="activeAction === 'terminate'" class="space-y-3">
                            <div class="rounded-lg border border-red-200 bg-red-50 p-3">
                                <div class="flex gap-2">
                                    <ExclamationTriangleIcon class="h-5 w-5 flex-shrink-0 text-red-600" />
                                    <p class="text-sm text-red-800">
                                        <strong>DİKKAT:</strong> {{ selectedIds.length }} hesap <strong>kalıcı olarak sonlandırılacak</strong>.
                                        Tüm dosyalar, veritabanları ve e-postalar silinecek. Bu işlem <u>geri alınamaz</u>.
                                    </p>
                                </div>
                            </div>
                            <div class="space-y-1">
                                <label class="block text-sm font-medium text-slate-700">
                                    Onaylamak için aşağıya tam olarak yazın:
                                    <code class="ml-1 rounded bg-slate-100 px-1.5 py-0.5 text-xs text-red-700">EVET KESIN SIL</code>
                                </label>
                                <input v-model="terminateConfirm" type="text" placeholder="EVET KESIN SIL"
                                    :class="[
                                        'w-full rounded-lg border px-3 py-2 text-sm font-mono focus:ring-1',
                                        terminateReady
                                            ? 'border-red-500 bg-red-50 focus:border-red-500 focus:ring-red-500'
                                            : 'border-slate-300 focus:border-indigo-500 focus:ring-indigo-500',
                                    ]" />
                            </div>
                        </div>

                        <!-- send_email -->
                        <div v-if="activeAction === 'send_email'" class="space-y-3">
                            <div class="rounded-lg border border-blue-200 bg-blue-50 p-2.5 text-xs text-blue-700">
                                İşlem audit log'a kaydedilir.
                            </div>
                            <div class="space-y-1">
                                <label class="block text-sm font-medium text-slate-700">Konu</label>
                                <input v-model="emailSubject" type="text" maxlength="255" placeholder="E-posta konusu"
                                    class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                            </div>
                            <div class="space-y-1">
                                <label class="block text-sm font-medium text-slate-700">Mesaj</label>
                                <textarea v-model="emailBody" rows="4" placeholder="E-posta içeriği..."
                                    class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                            </div>
                        </div>

                        <!-- add_tag -->
                        <div v-if="activeAction === 'add_tag'" class="space-y-2">
                            <div class="rounded-lg border border-amber-200 bg-amber-50 p-2.5 text-xs text-amber-700">
                                Not: Hesap modelinde henüz "tags" kolonu yok. İşlem audit log'a kaydedilir; kolonu ekledikten sonra aktif olur.
                            </div>
                            <label class="block text-sm font-medium text-slate-700">Etiket</label>
                            <input v-model="tagValue" type="text" maxlength="50" placeholder="örn: vip, eski-musteri"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500" />
                        </div>

                        <!-- transfer_reseller -->
                        <div v-if="activeAction === 'transfer_reseller'" class="space-y-2">
                            <label class="block text-sm font-medium text-slate-700">Hedef Bayi</label>
                            <select v-model="newResellerId"
                                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500">
                                <option value="">Seçiniz...</option>
                                <option v-for="r in resellers" :key="r.id" :value="r.id">{{ r.label }}</option>
                            </select>
                        </div>

                        <!-- Footer -->
                        <div class="flex justify-end gap-2 pt-2 border-t border-slate-100">
                            <button @click="showModal = false"
                                class="rounded-lg border border-slate-300 px-4 py-2 text-sm text-slate-600 hover:bg-slate-50">
                                İptal
                            </button>
                            <button
                                :disabled="!canSubmit"
                                @click="submitAction"
                                :class="[
                                    'rounded-lg px-5 py-2 text-sm font-semibold text-white transition-colors',
                                    isDestructive
                                        ? 'bg-red-600 hover:bg-red-700 disabled:bg-red-300'
                                        : 'bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-300',
                                    !canSubmit && 'cursor-not-allowed',
                                ]"
                            >
                                {{ isDestructive ? 'Evet, Sonlandır' : 'Uygula' }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </Teleport>

    </AdminLayout>
</template>
