<script setup>
import { computed, reactive, ref } from 'vue';

const props = defineProps({
    payload: {
        type: Object,
        default: () => ({}),
    },
});

const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';

const buildDefaultFilters = () => ({
    q: String(props.payload?.filters?.q || ''),
    type: String(props.payload?.filters?.type || ''),
    status: String(props.payload?.filters?.status || ''),
    priority: String(props.payload?.filters?.priority || ''),
    date_from: String(props.payload?.filters?.date_from || ''),
    date_to: String(props.payload?.filters?.date_to || ''),
    user_id: props.payload?.filters?.user_id ? Number(props.payload.filters.user_id) : null,
});

const buildDefaultSettingsForm = () => ({
    provider: String(props.payload?.settings?.provider || 'internal'),
    is_active: Boolean(props.payload?.settings?.is_active),
    api_base_url: String(props.payload?.settings?.api_base_url || ''),
    api_key: String(props.payload?.settings?.api_key || ''),
    api_secret: String(props.payload?.settings?.api_secret || ''),
    webhook_secret: String(props.payload?.settings?.webhook_secret || ''),
    auto_assign_user_id: props.payload?.settings?.auto_assign_user_id ? Number(props.payload.settings.auto_assign_user_id) : null,
    default_sla_days: Number(props.payload?.settings?.default_sla_days || 3),
    allow_employee_requests: Boolean(props.payload?.settings?.allow_employee_requests ?? true),
    require_approval: Boolean(props.payload?.settings?.require_approval ?? true),
    meta: props.payload?.settings?.meta ? JSON.stringify(props.payload.settings.meta, null, 2) : '',
});

const buildDefaultRequestForm = () => ({
    external_id: '',
    type: 'other',
    status: 'new',
    priority: 'medium',
    title: '',
    description: '',
    requested_date: new Date().toISOString().slice(0, 10),
    due_date: '',
    resolved_date: '',
    employee_user_id: null,
    assignee_user_id: null,
    creator_user_id: null,
    meta: '',
});

const filters = reactive(buildDefaultFilters());
const settingsForm = reactive(buildDefaultSettingsForm());
const requestForm = reactive(buildDefaultRequestForm());

const requests = ref(Array.isArray(props.payload?.requests) ? props.payload.requests : []);
const pagination = ref(props.payload?.pagination || {});
const settings = ref(props.payload?.settings || {});

const loading = ref(false);
const requestSubmitting = ref(false);
const settingsSubmitting = ref(false);
const deletingRequestId = ref(null);
const editingRequestId = ref(null);
const requestEditorOpen = ref(false);

const globalMessage = ref('');
const globalError = ref('');
const validationErrors = ref({});

const options = computed(() => props.payload?.options || {});
const permissions = computed(() => props.payload?.permissions || {});
const urls = computed(() => props.payload?.urls || {});

const typeOptions = computed(() => options.value?.types || {});
const statusOptions = computed(() => options.value?.statuses || {});
const priorityOptions = computed(() => options.value?.priorities || {});
const userOptions = computed(() => (Array.isArray(options.value?.users) ? options.value.users : []));

const selectedUserLabel = (userId) => {
    const id = Number(userId || 0);
    if (!id) {
        return '';
    }

    const user = userOptions.value.find((entry) => Number(entry?.id || 0) === id);

    return user ? `${user.name}${user.job_title ? ` · ${user.job_title}` : ''}` : '';
};

const requestTypeLabel = (value) => typeOptions.value?.[value] || value;
const requestStatusLabel = (value) => statusOptions.value?.[value] || value;
const requestPriorityLabel = (value) => priorityOptions.value?.[value] || value;

const statusBadgeClass = (value) => {
    const key = String(value || '');
    if (key === 'resolved') {
        return 'bg-emerald-100 text-emerald-700';
    }
    if (key === 'waiting_approval') {
        return 'bg-amber-100 text-amber-700';
    }
    if (key === 'in_progress') {
        return 'bg-sky-100 text-sky-700';
    }
    if (key === 'rejected') {
        return 'bg-rose-100 text-rose-700';
    }

    return 'bg-slate-100 text-slate-700';
};

const priorityBadgeClass = (value) => {
    const key = String(value || '');
    if (key === 'urgent') {
        return 'bg-rose-100 text-rose-700';
    }
    if (key === 'high') {
        return 'bg-orange-100 text-orange-700';
    }
    if (key === 'medium') {
        return 'bg-blue-100 text-blue-700';
    }

    return 'bg-slate-100 text-slate-700';
};

const clearMessages = () => {
    globalMessage.value = '';
    globalError.value = '';
};

const clearValidationErrors = () => {
    validationErrors.value = {};
};

const withJsonHeaders = (headers = {}) => ({
    Accept: 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN': csrfToken,
    ...headers,
});

const parseJsonSafe = async (response) => {
    try {
        return await response.json();
    } catch {
        return {};
    }
};

const replaceTemplateId = (template, id) => String(template || '').replace('__ID__', String(id));

const refreshStateFromIndexPayload = (data) => {
    requests.value = Array.isArray(data?.requests) ? data.requests : [];
    pagination.value = data?.pagination || {};
    settings.value = data?.settings || settings.value;

    if (data?.settings && !settingsSubmitting.value) {
        Object.assign(settingsForm, {
            provider: String(data.settings.provider || ''),
            is_active: Boolean(data.settings.is_active),
            api_base_url: String(data.settings.api_base_url || ''),
            api_key: String(data.settings.api_key || ''),
            api_secret: String(data.settings.api_secret || ''),
            webhook_secret: String(data.settings.webhook_secret || ''),
            auto_assign_user_id: data.settings.auto_assign_user_id ? Number(data.settings.auto_assign_user_id) : null,
            default_sla_days: Number(data.settings.default_sla_days || 3),
            allow_employee_requests: Boolean(data.settings.allow_employee_requests ?? true),
            require_approval: Boolean(data.settings.require_approval ?? true),
            meta: data.settings.meta ? JSON.stringify(data.settings.meta, null, 2) : '',
        });
    }
};

const buildQueryParams = () => {
    const params = new URLSearchParams();
    params.set('ajax', '1');

    if (filters.q.trim() !== '') {
        params.set('q', filters.q.trim());
    }
    if (filters.type !== '') {
        params.set('type', filters.type);
    }
    if (filters.status !== '') {
        params.set('status', filters.status);
    }
    if (filters.priority !== '') {
        params.set('priority', filters.priority);
    }
    if (filters.date_from !== '') {
        params.set('date_from', filters.date_from);
    }
    if (filters.date_to !== '') {
        params.set('date_to', filters.date_to);
    }
    if (filters.user_id) {
        params.set('user_id', String(filters.user_id));
    }

    return params;
};

const loadIndexData = async (urlOverride = '') => {
    const indexUrl = String(urls.value?.index || '').trim();
    if (indexUrl === '') {
        return;
    }

    loading.value = true;
    clearMessages();

    try {
        const requestUrl = new URL(urlOverride || indexUrl, window.location.origin);
        if (!urlOverride) {
            requestUrl.search = buildQueryParams().toString();
        } else {
            requestUrl.searchParams.set('ajax', '1');
        }

        const response = await window.fetch(requestUrl.toString(), {
            method: 'GET',
            headers: withJsonHeaders(),
        });

        const json = await parseJsonSafe(response);
        if (!response.ok) {
            throw new Error(String(json?.message || 'Failed to load HR data.'));
        }

        refreshStateFromIndexPayload(json);
    } catch (error) {
        globalError.value = error instanceof Error ? error.message : 'Failed to load HR data.';
    } finally {
        loading.value = false;
    }
};

const applyFilters = () => {
    loadIndexData();
};

const resetFilters = () => {
    Object.assign(filters, {
        q: '',
        type: '',
        status: '',
        priority: '',
        date_from: '',
        date_to: '',
        user_id: null,
    });
    loadIndexData();
};

const goToPage = (url) => {
    if (!url) {
        return;
    }

    loadIndexData(String(url));
};

const saveSettings = async () => {
    const updateUrl = String(urls.value?.settings_update || '').trim();
    if (updateUrl === '') {
        return;
    }

    settingsSubmitting.value = true;
    clearMessages();
    clearValidationErrors();

    try {
        const response = await window.fetch(updateUrl, {
            method: 'PATCH',
            headers: withJsonHeaders({
                'Content-Type': 'application/json',
            }),
            body: JSON.stringify({
                provider: settingsForm.provider,
                is_active: settingsForm.is_active,
                api_base_url: settingsForm.api_base_url || null,
                api_key: settingsForm.api_key || null,
                api_secret: settingsForm.api_secret || null,
                webhook_secret: settingsForm.webhook_secret || null,
                auto_assign_user_id: settingsForm.auto_assign_user_id || null,
                default_sla_days: settingsForm.default_sla_days,
                allow_employee_requests: settingsForm.allow_employee_requests,
                require_approval: settingsForm.require_approval,
                meta: settingsForm.meta || null,
            }),
        });

        const json = await parseJsonSafe(response);

        if (!response.ok) {
            if (response.status === 422 && json?.errors) {
                validationErrors.value = json.errors;
            }
            throw new Error(String(json?.message || 'Failed to save HR settings.'));
        }

        if (json?.settings) {
            settings.value = json.settings;
        }
        globalMessage.value = String(json?.message || 'HR settings updated.');
    } catch (error) {
        globalError.value = error instanceof Error ? error.message : 'Failed to save HR settings.';
    } finally {
        settingsSubmitting.value = false;
    }
};

const openCreateRequest = () => {
    Object.assign(requestForm, buildDefaultRequestForm());
    editingRequestId.value = null;
    requestEditorOpen.value = true;
    clearValidationErrors();
};

const openEditRequest = (item) => {
    Object.assign(requestForm, {
        external_id: String(item?.external_id || ''),
        type: String(item?.type || 'other'),
        status: String(item?.status || 'new'),
        priority: String(item?.priority || 'medium'),
        title: String(item?.title || ''),
        description: String(item?.description || ''),
        requested_date: String(item?.requested_date || ''),
        due_date: String(item?.due_date || ''),
        resolved_date: String(item?.resolved_date || ''),
        employee_user_id: item?.employee_user_id ? Number(item.employee_user_id) : null,
        assignee_user_id: item?.assignee_user_id ? Number(item.assignee_user_id) : null,
        creator_user_id: item?.creator_user_id ? Number(item.creator_user_id) : null,
        meta: item?.meta ? JSON.stringify(item.meta, null, 2) : '',
    });

    editingRequestId.value = Number(item?.id || 0);
    requestEditorOpen.value = true;
    clearValidationErrors();
};

const closeEditor = () => {
    requestEditorOpen.value = false;
    editingRequestId.value = null;
};

const submitRequest = async () => {
    const isEdit = Boolean(editingRequestId.value);
    const endpoint = isEdit
        ? replaceTemplateId(urls.value?.request_update_template, editingRequestId.value)
        : String(urls.value?.request_store || '');

    if (!endpoint) {
        return;
    }

    requestSubmitting.value = true;
    clearMessages();
    clearValidationErrors();

    try {
        const response = await window.fetch(endpoint, {
            method: isEdit ? 'PATCH' : 'POST',
            headers: withJsonHeaders({
                'Content-Type': 'application/json',
            }),
            body: JSON.stringify({
                external_id: requestForm.external_id || null,
                type: requestForm.type,
                status: requestForm.status,
                priority: requestForm.priority,
                title: requestForm.title,
                description: requestForm.description || null,
                requested_date: requestForm.requested_date || null,
                due_date: requestForm.due_date || null,
                resolved_date: requestForm.resolved_date || null,
                employee_user_id: requestForm.employee_user_id || null,
                assignee_user_id: requestForm.assignee_user_id || null,
                creator_user_id: requestForm.creator_user_id || null,
                meta: requestForm.meta || null,
            }),
        });

        const json = await parseJsonSafe(response);
        if (!response.ok) {
            if (response.status === 422 && json?.errors) {
                validationErrors.value = json.errors;
            }
            throw new Error(String(json?.message || 'Failed to save HR request.'));
        }

        globalMessage.value = String(json?.message || 'HR request saved.');
        closeEditor();
        await loadIndexData();
    } catch (error) {
        globalError.value = error instanceof Error ? error.message : 'Failed to save HR request.';
    } finally {
        requestSubmitting.value = false;
    }
};

const deleteRequest = async (item) => {
    const requestId = Number(item?.id || 0);
    if (!requestId) {
        return;
    }

    const shouldDelete = window.confirm(`Delete request #${requestId}?`);
    if (!shouldDelete) {
        return;
    }

    deletingRequestId.value = requestId;
    clearMessages();
    clearValidationErrors();

    try {
        const endpoint = replaceTemplateId(urls.value?.request_delete_template, requestId);
        const response = await window.fetch(endpoint, {
            method: 'DELETE',
            headers: withJsonHeaders(),
        });

        const json = await parseJsonSafe(response);
        if (!response.ok) {
            throw new Error(String(json?.message || 'Failed to delete HR request.'));
        }

        globalMessage.value = String(json?.message || 'HR request deleted.');
        await loadIndexData();
    } catch (error) {
        globalError.value = error instanceof Error ? error.message : 'Failed to delete HR request.';
    } finally {
        deletingRequestId.value = null;
    }
};
</script>

<template>
    <div class="crm-page-enter space-y-4">
        <section class="grid grid-cols-1 gap-4 2xl:grid-cols-[minmax(0,1fr),minmax(0,1.5fr)]">
            <article class="crm-material-card">
                <div class="mb-4 flex items-start justify-between gap-3">
                    <div>
                        <h3 class="text-base font-semibold text-slate-900">HR settings</h3>
                        <p class="text-sm text-slate-500">Provider and automation defaults for HR requests.</p>
                    </div>
                    <span
                        class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-semibold"
                        :class="settingsForm.is_active ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-600'"
                    >
                        {{ settingsForm.is_active ? 'Active' : 'Disabled' }}
                    </span>
                </div>

                <div class="rounded-xl border border-slate-200 bg-slate-50/80 px-3 py-2 text-xs text-slate-600">
                    <p class="font-semibold text-slate-700">Webhook URL</p>
                    <code class="mt-1 block break-all rounded bg-white px-2 py-1 text-slate-800">{{ urls.webhook || '—' }}</code>
                </div>

                <form class="mt-4 space-y-3" @submit.prevent="saveSettings">
                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                        <label class="space-y-1 text-sm">
                            <span class="text-slate-600">Provider</span>
                            <input v-model="settingsForm.provider" type="text" class="crm-field" />
                        </label>
                        <label class="space-y-1 text-sm">
                            <span class="text-slate-600">Auto assign to</span>
                            <select v-model.number="settingsForm.auto_assign_user_id" class="crm-field">
                                <option :value="null">Not selected</option>
                                <option v-for="member in userOptions" :key="member.id" :value="member.id">
                                    {{ member.name }}
                                </option>
                            </select>
                        </label>
                    </div>

                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                        <label class="space-y-1 text-sm">
                            <span class="text-slate-600">API base URL</span>
                            <input v-model="settingsForm.api_base_url" type="text" class="crm-field" />
                        </label>
                        <label class="space-y-1 text-sm">
                            <span class="text-slate-600">Webhook secret</span>
                            <input v-model="settingsForm.webhook_secret" type="text" class="crm-field" />
                        </label>
                    </div>

                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                        <label class="space-y-1 text-sm">
                            <span class="text-slate-600">API key</span>
                            <input v-model="settingsForm.api_key" type="text" class="crm-field" />
                        </label>
                        <label class="space-y-1 text-sm">
                            <span class="text-slate-600">API secret</span>
                            <input v-model="settingsForm.api_secret" type="text" class="crm-field" />
                        </label>
                    </div>

                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                        <label class="space-y-1 text-sm">
                            <span class="text-slate-600">Default SLA (days)</span>
                            <input v-model.number="settingsForm.default_sla_days" type="number" min="1" max="365" class="crm-field" />
                        </label>
                        <div class="grid grid-cols-1 gap-2 pt-6 text-sm text-slate-600">
                            <label class="inline-flex items-center gap-2">
                                <input v-model="settingsForm.is_active" type="checkbox" class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" />
                                Active integration
                            </label>
                            <label class="inline-flex items-center gap-2">
                                <input v-model="settingsForm.allow_employee_requests" type="checkbox" class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" />
                                Allow employee requests
                            </label>
                            <label class="inline-flex items-center gap-2">
                                <input v-model="settingsForm.require_approval" type="checkbox" class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500" />
                                Require approval
                            </label>
                        </div>
                    </div>

                    <label class="block space-y-1 text-sm">
                        <span class="text-slate-600">Meta JSON</span>
                        <textarea v-model="settingsForm.meta" rows="3" class="crm-field font-mono text-xs"></textarea>
                    </label>

                    <p v-if="validationErrors.provider" class="text-xs text-rose-600">{{ validationErrors.provider[0] }}</p>
                    <p v-if="validationErrors.default_sla_days" class="text-xs text-rose-600">{{ validationErrors.default_sla_days[0] }}</p>

                    <div class="flex justify-end">
                        <button type="submit" class="crm-button-primary" :disabled="settingsSubmitting || !permissions.can_manage_settings">
                            {{ settingsSubmitting ? 'Saving...' : 'Save settings' }}
                        </button>
                    </div>
                </form>
            </article>

            <article class="crm-material-card">
                <div class="mb-3 flex flex-wrap items-center justify-between gap-3">
                    <div>
                        <h3 class="text-base font-semibold text-slate-900">HR requests</h3>
                        <p class="text-sm text-slate-500">Register, track, and resolve employee requests.</p>
                    </div>
                    <div class="flex items-center gap-2">
                        <button v-if="permissions.can_create_request" type="button" class="crm-button-secondary" @click="openCreateRequest">
                            New request
                        </button>
                        <span class="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-semibold text-slate-600">
                            {{ pagination.total || requests.length }} total
                        </span>
                    </div>
                </div>

                <div class="grid grid-cols-1 gap-2 md:grid-cols-3 xl:grid-cols-6">
                    <input v-model="filters.q" type="text" class="crm-field xl:col-span-2" placeholder="Title, external ID, or description" @keyup.enter="applyFilters" />

                    <select v-model="filters.type" class="crm-field">
                        <option value="">All types</option>
                        <option v-for="(label, key) in typeOptions" :key="key" :value="key">{{ label }}</option>
                    </select>

                    <select v-model="filters.status" class="crm-field">
                        <option value="">All statuses</option>
                        <option v-for="(label, key) in statusOptions" :key="key" :value="key">{{ label }}</option>
                    </select>

                    <select v-model="filters.priority" class="crm-field">
                        <option value="">All priorities</option>
                        <option v-for="(label, key) in priorityOptions" :key="key" :value="key">{{ label }}</option>
                    </select>

                    <select v-model.number="filters.user_id" class="crm-field">
                        <option :value="null">All users</option>
                        <option v-for="member in userOptions" :key="member.id" :value="member.id">{{ member.name }}</option>
                    </select>

                    <input v-model="filters.date_from" type="date" class="crm-field" />
                    <input v-model="filters.date_to" type="date" class="crm-field" />

                    <div class="flex items-center gap-2 xl:col-span-2">
                        <button type="button" class="crm-button-secondary" :disabled="loading" @click="applyFilters">Apply</button>
                        <button type="button" class="crm-button-ghost" :disabled="loading" @click="resetFilters">Reset</button>
                    </div>
                </div>

                <div class="mt-3 space-y-2">
                    <p v-if="globalMessage" class="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700">{{ globalMessage }}</p>
                    <p v-if="globalError" class="rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700">{{ globalError }}</p>
                </div>

                <div class="mt-4 overflow-x-auto rounded-xl border border-slate-200">
                    <table class="min-w-full divide-y divide-slate-200 bg-white">
                        <thead class="bg-slate-50 text-left text-xs font-semibold uppercase text-slate-500">
                            <tr>
                                <th class="px-3 py-2">Request</th>
                                <th class="px-3 py-2">Type</th>
                                <th class="px-3 py-2">Status</th>
                                <th class="px-3 py-2">Priority</th>
                                <th class="px-3 py-2">Employee</th>
                                <th class="px-3 py-2">Due date</th>
                                <th class="px-3 py-2">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 text-sm">
                            <tr v-if="loading">
                                <td colspan="7" class="px-3 py-6 text-center text-slate-500">Loading requests...</td>
                            </tr>
                            <tr v-else-if="requests.length === 0">
                                <td colspan="7" class="px-3 py-6 text-center text-slate-500">No HR requests found.</td>
                            </tr>
                            <tr v-for="item in requests" :key="item.id" class="hover:bg-slate-50/70">
                                <td class="px-3 py-2 align-top">
                                    <p class="font-medium text-slate-900">#{{ item.id }} · {{ item.title }}</p>
                                    <p class="text-xs text-slate-500">{{ item.external_id || '—' }}</p>
                                </td>
                                <td class="px-3 py-2 align-top text-slate-700">{{ requestTypeLabel(item.type) }}</td>
                                <td class="px-3 py-2 align-top">
                                    <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold" :class="statusBadgeClass(item.status)">
                                        {{ requestStatusLabel(item.status) }}
                                    </span>
                                </td>
                                <td class="px-3 py-2 align-top">
                                    <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold" :class="priorityBadgeClass(item.priority)">
                                        {{ requestPriorityLabel(item.priority) }}
                                    </span>
                                </td>
                                <td class="px-3 py-2 align-top text-slate-700">
                                    {{ item.employee?.name || selectedUserLabel(item.employee_user_id) || '—' }}
                                </td>
                                <td class="px-3 py-2 align-top text-slate-700">{{ item.due_date || '—' }}</td>
                                <td class="px-3 py-2 align-top">
                                    <div class="flex flex-wrap items-center gap-2">
                                        <button
                                            v-if="permissions.can_update_request"
                                            type="button"
                                            class="text-xs font-medium text-indigo-600 hover:text-indigo-500"
                                            @click="openEditRequest(item)"
                                        >
                                            Edit
                                        </button>
                                        <button
                                            v-if="permissions.can_delete_request"
                                            type="button"
                                            class="text-xs font-medium text-rose-600 hover:text-rose-500"
                                            :disabled="deletingRequestId === item.id"
                                            @click="deleteRequest(item)"
                                        >
                                            {{ deletingRequestId === item.id ? 'Deleting...' : 'Delete' }}
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div v-if="pagination?.links?.length" class="mt-3 flex flex-wrap items-center gap-2">
                    <button
                        v-for="link in pagination.links"
                        :key="link.label"
                        type="button"
                        class="rounded-md border px-2.5 py-1 text-xs"
                        :class="link.active ? 'border-indigo-500 bg-indigo-50 text-indigo-700' : 'border-slate-300 text-slate-600 hover:bg-slate-50'"
                        :disabled="!link.url || loading"
                        @click="goToPage(link.url)"
                        v-html="link.label"
                    ></button>
                </div>
            </article>
        </section>

        <section v-if="requestEditorOpen" class="crm-material-card">
            <div class="mb-3 flex items-center justify-between gap-3">
                <h3 class="text-base font-semibold text-slate-900">{{ editingRequestId ? `Edit request #${editingRequestId}` : 'Create HR request' }}</h3>
                <button type="button" class="rounded-md border border-slate-300 px-2 py-1 text-xs text-slate-600 hover:bg-slate-50" @click="closeEditor">Close</button>
            </div>

            <form class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4" @submit.prevent="submitRequest">
                <label class="space-y-1 text-sm">
                    <span class="text-slate-600">Type</span>
                    <select v-model="requestForm.type" class="crm-field">
                        <option v-for="(label, key) in typeOptions" :key="key" :value="key">{{ label }}</option>
                    </select>
                </label>
                <label class="space-y-1 text-sm">
                    <span class="text-slate-600">Status</span>
                    <select v-model="requestForm.status" class="crm-field">
                        <option v-for="(label, key) in statusOptions" :key="key" :value="key">{{ label }}</option>
                    </select>
                </label>
                <label class="space-y-1 text-sm">
                    <span class="text-slate-600">Priority</span>
                    <select v-model="requestForm.priority" class="crm-field">
                        <option v-for="(label, key) in priorityOptions" :key="key" :value="key">{{ label }}</option>
                    </select>
                </label>
                <label class="space-y-1 text-sm">
                    <span class="text-slate-600">External ID</span>
                    <input v-model="requestForm.external_id" type="text" class="crm-field" />
                </label>

                <label class="space-y-1 text-sm md:col-span-2 xl:col-span-4">
                    <span class="text-slate-600">Title</span>
                    <input v-model="requestForm.title" type="text" class="crm-field" />
                </label>
                <label class="space-y-1 text-sm md:col-span-2 xl:col-span-4">
                    <span class="text-slate-600">Description</span>
                    <textarea v-model="requestForm.description" rows="2" class="crm-field"></textarea>
                </label>

                <label class="space-y-1 text-sm">
                    <span class="text-slate-600">Requested date</span>
                    <input v-model="requestForm.requested_date" type="date" class="crm-field" />
                </label>
                <label class="space-y-1 text-sm">
                    <span class="text-slate-600">Due date</span>
                    <input v-model="requestForm.due_date" type="date" class="crm-field" />
                </label>
                <label class="space-y-1 text-sm">
                    <span class="text-slate-600">Resolved date</span>
                    <input v-model="requestForm.resolved_date" type="date" class="crm-field" />
                </label>
                <label class="space-y-1 text-sm">
                    <span class="text-slate-600">Employee</span>
                    <select v-model.number="requestForm.employee_user_id" class="crm-field">
                        <option :value="null">Not selected</option>
                        <option v-for="member in userOptions" :key="member.id" :value="member.id">{{ member.name }}</option>
                    </select>
                </label>
                <label class="space-y-1 text-sm">
                    <span class="text-slate-600">Assignee</span>
                    <select v-model.number="requestForm.assignee_user_id" class="crm-field">
                        <option :value="null">Not selected</option>
                        <option v-for="member in userOptions" :key="member.id" :value="member.id">{{ member.name }}</option>
                    </select>
                </label>
                <label class="space-y-1 text-sm">
                    <span class="text-slate-600">Creator</span>
                    <select v-model.number="requestForm.creator_user_id" class="crm-field">
                        <option :value="null">Not selected</option>
                        <option v-for="member in userOptions" :key="member.id" :value="member.id">{{ member.name }}</option>
                    </select>
                </label>
                <label class="space-y-1 text-sm md:col-span-2 xl:col-span-4">
                    <span class="text-slate-600">Meta JSON</span>
                    <textarea v-model="requestForm.meta" rows="2" class="crm-field font-mono text-xs"></textarea>
                </label>

                <p v-if="validationErrors.title" class="md:col-span-2 xl:col-span-4 text-xs text-rose-600">{{ validationErrors.title[0] }}</p>
                <p v-if="validationErrors.type" class="md:col-span-2 xl:col-span-4 text-xs text-rose-600">{{ validationErrors.type[0] }}</p>

                <div class="md:col-span-2 xl:col-span-4 flex justify-end">
                    <button type="submit" class="crm-button-primary" :disabled="requestSubmitting">
                        {{ requestSubmitting ? 'Saving...' : (editingRequestId ? 'Save request' : 'Create request') }}
                    </button>
                </div>
            </form>
        </section>
    </div>
</template>
