<template>
    <Head title="Forms" />
    <AppLayout>
        <div class="page-header">
            <div class="page-header__left">
                <h1>Forms</h1>
                <p>Build embeddable subscription forms with drag-and-drop.</p>
            </div>
            <div class="page-header__actions">
                <button class="btn btn-primary" style="display:inline-flex;align-items:center;gap:6px" @click="showTypeModal = true">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="14" height="14">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
                    </svg>
                    Create form
                </button>
            </div>
        </div>

        <div class="table-wrap">
            <div class="table-toolbar" :class="{ 'has-selection': selected.length > 0 }">
                <div v-if="selected.length === 0" class="table-toolbar-left">
                    <div class="table-search">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" /></svg>
                        <input type="search" v-model="search" placeholder="Search forms…" @input="onSearch">
                    </div>
                    <select v-model="typeFilter" class="table-filter-select" @change="onSearch">
                        <option value="">All types</option>
                        <option value="inline">Inline / Embedded</option>
                        <option value="popup">Popup</option>
                    </select>
                    <select v-model="statusFilter" class="table-filter-select" @change="onSearch">
                        <option value="">All statuses</option>
                        <option value="draft">Draft</option>
                        <option value="active">Active</option>
                        <option value="paused">Paused</option>
                    </select>
                </div>
                <div v-else class="table-toolbar-left">
                    <div class="selection-status">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" width="16" height="16" style="color: var(--active-text);"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                        <span class="selection-count">{{ selected.length }} form{{ selected.length === 1 ? '' : 's' }} selected</span>
                    </div>
                </div>
                <div class="table-toolbar-right">
                    <template v-if="selected.length > 0">
                        <button class="btn btn-outline btn-sm" @click="bulkStatus('active')">Activate</button>
                        <button class="btn btn-outline btn-sm" @click="bulkStatus('paused')">Pause</button>
                        <button class="btn btn-outline btn-sm" style="color:var(--danger);border-color:var(--danger-border)" @click="showBulkDelete = true">Delete</button>
                        <button class="btn btn-outline btn-sm" @click="selected = []">Cancel</button>
                    </template>
                    <template v-else>
                        <span class="cw-pagination-info">{{ forms.from ?? 0 }}–{{ forms.to ?? 0 }} of {{ forms.total }}</span>
                        <button class="cw-pg-btn" :disabled="!forms.prev_page_url" @click="goPage(forms.current_page - 1)">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="14" height="14"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" /></svg>
                        </button>
                        <button class="cw-pg-btn" :disabled="!forms.next_page_url" @click="goPage(forms.current_page + 1)">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="14" height="14"><path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" /></svg>
                        </button>
                    </template>
                </div>
            </div>

            <div class="table-scroll">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th style="width:40px"><input type="checkbox" class="table-checkbox" :checked="allSelected" @change="toggleAll"></th>
                            <th>Name</th>
                            <th>Views</th>
                            <th>Submissions</th>
                            <th>Rate</th>
                            <th>Status</th>
                            <th style="width:170px">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="forms.data.length === 0">
                            <td colspan="7" style="text-align:center;padding:48px 24px;color:#9ca3af">
                                No forms yet. <button class="link-btn" @click="showTypeModal = true">Create your first form.</button>
                            </td>
                        </tr>
                        <tr v-for="f in forms.data" :key="f.id" :class="{ 'is-selected': selected.includes(f.id) }">
                            <td class="cell-checkbox"><input type="checkbox" class="table-checkbox" :value="f.id" v-model="selected"></td>
                            <td data-label="Name" class="cell-name cell-title">
                                <div class="automation-title-container">
                                    <Link :href="route('forms.show', f.id)" class="automation-title-link">{{ f.name }}</Link>
                                </div>
                                <span class="forms-type-badge" :class="f.type === 'popup' ? 'forms-type-badge--popup' : 'forms-type-badge--inline'">
                                    {{ f.type === 'popup' ? 'Popup Form' : 'Inline / Embedded Form' }}
                                </span>
                                <div class="automation-title-sub" v-if="f.lists?.length">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z" /></svg>
                                    {{ f.lists.map(l => l.title).join(', ') }}
                                </div>
                            </td>
                            <td data-label="Views" style="font-size:13px">{{ f.total_views.toLocaleString() }}</td>
                            <td data-label="Submissions" style="font-size:13px">{{ f.total_submissions.toLocaleString() }}</td>
                            <td data-label="Rate" style="font-size:13px">{{ f.submission_rate }}%</td>
                            <td data-label="Status">
                                <span :class="['badge', statusBadgeClass(f.status)]">{{ statusLabel(f.status) }}</span>
                            </td>
                            <td class="cell-actions" data-label="">
                                <div style="display:flex;gap:6px">
                                    <Link :href="route('forms.show', f.id)" class="re-action-btn" title="View Report">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#0f766e"><path stroke-linecap="round" stroke-linejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v5.25c0 .621-.504 1.125-1.125 1.125h-2.25A1.125 1.125 0 013 18.375v-5.25zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125v-9.75zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v14.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z"/></svg>
                                    </Link>
                                    <Link :href="route('forms.edit', f.id)" class="re-action-btn" title="Edit Form">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#2563eb"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931z"/></svg>
                                    </Link>
                                    <button class="re-action-btn" title="Embed Code" @click="openEmbed(f)">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#7c3aed"><path stroke-linecap="round" stroke-linejoin="round" d="M17.25 6.75L22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3l-4.5 16.5"/></svg>
                                    </button>
                                    <button class="re-action-btn" title="Duplicate" @click="duplicate(f)">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#6b7280"><path stroke-linecap="round" stroke-linejoin="round" d="M15.666 3.888A2.25 2.25 0 0013.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 01-.75.75H9a.75.75 0 01-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 01-2.25 2.25H6.75A2.25 2.25 0 014.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 011.927-.184"/></svg>
                                    </button>
                                    <button class="re-action-btn" title="Delete" @click="confirmDelete(f)">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="#ef4444"><path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"/></svg>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <SelectFormTypeModal :open="showTypeModal" @close="showTypeModal = false" />
        <EmbedCodeModal :open="showEmbedModal" :embed="embedData" @close="showEmbedModal = false" @activate="activateEmbedForm" />

        <ConfirmModal
            v-if="showConfirmModal"
            title="Delete Form"
            :message="`Are you sure you want to delete &quot;${pendingDelete?.name}&quot;? This cannot be undone.`"
            confirmText="Delete"
            :isDestructive="true"
            @resolve="val => val ? destroyForm() : (showConfirmModal = false)"
        />

        <ConfirmModal
            v-if="showBulkDelete"
            title="Delete Forms"
            :message="`Are you sure you want to delete the ${selected.length} selected form${selected.length === 1 ? '' : 's'}? This cannot be undone.`"
            confirmText="Delete"
            :isDestructive="true"
            @resolve="val => val ? bulkDelete() : (showBulkDelete = false)"
        />
    </AppLayout>
</template>

<script setup>
import { ref, computed } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import ConfirmModal from '@/Components/ConfirmModal.vue';
import SelectFormTypeModal from '@/Components/Forms/SelectFormTypeModal.vue';
import EmbedCodeModal from '@/Components/Forms/EmbedCodeModal.vue';

const props = defineProps({
    forms: { type: Object, required: true },
    filters: { type: Object, default: () => ({}) },
});

const search = ref(props.filters?.search ?? '');
const statusFilter = ref(props.filters?.status ?? '');
const typeFilter = ref(props.filters?.type ?? '');
const showTypeModal = ref(false);
const showEmbedModal = ref(false);
const embedData = ref(null);
const showConfirmModal = ref(false);
const pendingDelete = ref(null);
const activeEmbedForm = ref(null);
const selected = ref([]);
const showBulkDelete = ref(false);

const allSelected = computed(() =>
    props.forms.data.length > 0 &&
    props.forms.data.every(f => selected.value.includes(f.id))
);

function toggleAll(e) {
    selected.value = e.target.checked ? props.forms.data.map(f => f.id) : [];
}

function statusLabel(status) {
    return { draft: 'Draft', active: 'Active', paused: 'Paused' }[status] || status;
}
function statusBadgeClass(status) {
    return { draft: 'badge--gray', active: 'badge--success', paused: 'badge--warning' }[status] || 'badge--gray';
}

let searchTimer = null;
function onSearch() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(doSearch, 350);
}

function doSearch() {
    router.get(route('forms.index'), { search: search.value, status: statusFilter.value, type: typeFilter.value }, { preserveState: true, replace: true });
}

function goPage(page) {
    if (page < 1 || page > props.forms.last_page) return;
    router.get(route('forms.index'), { search: search.value, status: statusFilter.value, type: typeFilter.value, page }, { preserveState: true });
}

async function openEmbed(form) {
    activeEmbedForm.value = form;
    embedData.value = null;
    showEmbedModal.value = true;
    const res = await fetch(route('forms.embed', form.id), { headers: { Accept: 'application/json' } });
    embedData.value = await res.json();
}

function activateEmbedForm() {
    if (!activeEmbedForm.value) return;
    router.post(route('forms.bulk-toggle-status'), { ids: [activeEmbedForm.value.id], status: 'active' }, {
        preserveScroll: true,
        onSuccess: () => openEmbed(activeEmbedForm.value),
    });
}

function bulkStatus(status) {
    router.post(route('forms.bulk-toggle-status'), { ids: selected.value, status }, {
        preserveScroll: true,
        onSuccess: () => { selected.value = []; },
    });
}

function duplicate(form) {
    router.post(route('forms.duplicate', form.id), {}, { preserveScroll: true });
}

function confirmDelete(form) {
    pendingDelete.value = form;
    showConfirmModal.value = true;
}

function destroyForm() {
    showConfirmModal.value = false;
    router.delete(route('forms.destroy', pendingDelete.value.id), { preserveScroll: true });
}

function bulkDelete() {
    router.post(route('forms.bulk-delete'), { ids: selected.value }, {
        preserveScroll: true,
        onSuccess: () => { showBulkDelete.value = false; selected.value = []; },
    });
}
</script>

<style scoped>
.forms-type-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    font-size: 11px;
    font-weight: 600;
    letter-spacing: .02em;
    padding: 3px 8px;
    border-radius: 999px;
}
.forms-type-badge--popup { background: rgba(139, 92, 246, .12); color: #7c3aed; }
.forms-type-badge--inline { background: rgba(66, 133, 244, .12); color: #2563eb; }

.link-btn { background: none; border: none; color: #4285f4; cursor: pointer; font-size: inherit; padding: 0; }

.cw-pagination-info { font-size: 12px; color: var(--text-secondary); }
.cw-pg-btn {
    width: 28px; height: 28px;
    display: flex; align-items: center; justify-content: center;
    border: 1px solid var(--border-color); background: var(--bg-surface);
    border-radius: 6px; cursor: pointer; color: var(--text-primary);
}
.cw-pg-btn:disabled { opacity: 0.4; cursor: not-allowed; }
</style>
