<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Admin/Cases/Index.vue
//  Location: resources/js/Pages/Admin/Cases/Index.vue
//
//  Admin case management table.
//  Actions: create, edit, publish, archive, delete.
//
//  MOBILE  (<768px): Card list view
//  DESKTOP (≥768px): Full table with inline actions
//
//  Rules:
//    - All data from AdminCaseService via Inertia props
//    - Destructive actions (delete) require inline confirmation
//    - Admin layout always uses Navy theme (set by AdminLayout)
//    - Bilingual inline
// ══════════════════════════════════════════════════════════════════

import { ref, computed }              from 'vue';
import { Head, Link, router, useForm } from '@inertiajs/vue3';
import { useAuthStore }               from '@/Stores/useAuthStore';
import AdminLayout                    from '@/Layouts/AdminLayout.vue';

// ── Props — from AdminCaseService ─────────────────────────────────
const props = defineProps({
    cases:   { type: Object, required: true },
    hubs:    { type: Array,  required: true },
    filters: { type: Object, default: () => ({}) },
});

const authStore = useAuthStore();
const locale    = computed(() => authStore.locale);

// ── Filter state ──────────────────────────────────────────────────
const filterHub        = ref(props.filters.hub_id    ?? '');
const filterStatus     = ref(props.filters.status    ?? '');
const filterDifficulty = ref(props.filters.difficulty ?? '');
const filterSearch     = ref(props.filters.search    ?? '');

function applyFilters() {
    router.get(route('admin.cases.index'), {
        hub_id:     filterHub.value     || undefined,
        status:     filterStatus.value  || undefined,
        difficulty: filterDifficulty.value || undefined,
        search:     filterSearch.value  || undefined,
    }, { preserveState: true, replace: true });
}

// ── Confirm delete ────────────────────────────────────────────────
const confirmDeleteId = ref(null);

function confirmDelete(id) { confirmDeleteId.value = id; }
function cancelDelete()    { confirmDeleteId.value = null; }

function deleteCase(id) {
    router.delete(route('admin.cases.destroy', id), {
        onSuccess: () => { confirmDeleteId.value = null; },
    });
}

// ── Publish / Archive ─────────────────────────────────────────────
function publishCase(id) {
    router.patch(route('admin.cases.publish', id));
}

function archiveCase(id) {
    router.patch(route('admin.cases.archive', id));
}

// ── Hub name helper ───────────────────────────────────────────────
function hubName(hub) {
    return locale.value === 'ar' ? hub.name_ar : hub.name_en;
}

// ── Status label + class ──────────────────────────────────────────
function statusLabel(status) {
    const map = {
        draft:     locale.value === 'ar' ? 'مسودة'    : 'Draft',
        review:    locale.value === 'ar' ? 'للمراجعة' : 'Review',
        published: locale.value === 'ar' ? 'منشور'    : 'Published',
        archived:  locale.value === 'ar' ? 'مؤرشف'   : 'Archived',
    };
    return map[status] ?? status;
}

function statusClass(status) {
    return {
        draft:     'status--draft',
        review:    'status--review',
        published: 'status--published',
        archived:  'status--archived',
    }[status] ?? '';
}

function difficultyLabel(level) {
    return {
        beginner:     locale.value === 'ar' ? 'مبتدئ'  : 'Beginner',
        intermediate: locale.value === 'ar' ? 'متوسط'  : 'Intermediate',
        advanced:     locale.value === 'ar' ? 'متقدم'  : 'Advanced',
    }[level] ?? level;
}
</script>

<template>
    <AdminLayout :title="locale === 'ar' ? 'إدارة الحالات' : 'Case Management'">
        <Head :title="locale === 'ar' ? 'إدارة الحالات' : 'Case Management'" />

        <div class="admin-cases">

            <!-- ── Page header ────────────────────────────── -->
            <div class="admin-header">
                <div>
                    <h1 class="admin-title">
                        {{ locale === 'ar' ? 'إدارة الحالات' : 'Case Management' }}
                    </h1>
                    <p class="admin-sub">
                        {{ cases.total }}
                        {{ locale === 'ar' ? 'حالة إجمالاً' : 'total cases' }}
                    </p>
                </div>
                <Link :href="route('admin.cases.create')" class="create-btn">
                    <i class="ti ti-plus" aria-hidden="true"></i>
                    {{ locale === 'ar' ? 'حالة جديدة' : 'New Case' }}
                </Link>
            </div>

            <!-- ── Filters ────────────────────────────────── -->
            <div class="filter-bar">
                <select class="filter-select" v-model="filterHub" @change="applyFilters">
                    <option value="">{{ locale === 'ar' ? 'كل التخصصات' : 'All Hubs' }}</option>
                    <option v-for="hub in hubs" :key="hub.id" :value="hub.id">
                        {{ hubName(hub) }}
                    </option>
                </select>

                <select class="filter-select" v-model="filterStatus" @change="applyFilters">
                    <option value="">{{ locale === 'ar' ? 'كل الحالات' : 'All Statuses' }}</option>
                    <option value="draft">{{ statusLabel('draft') }}</option>
                    <option value="review">{{ statusLabel('review') }}</option>
                    <option value="published">{{ statusLabel('published') }}</option>
                    <option value="archived">{{ statusLabel('archived') }}</option>
                </select>

                <select class="filter-select" v-model="filterDifficulty" @change="applyFilters">
                    <option value="">{{ locale === 'ar' ? 'كل المستويات' : 'All Levels' }}</option>
                    <option value="beginner">{{ difficultyLabel('beginner') }}</option>
                    <option value="intermediate">{{ difficultyLabel('intermediate') }}</option>
                    <option value="advanced">{{ difficultyLabel('advanced') }}</option>
                </select>

                <input
                    v-model="filterSearch"
                    class="filter-input"
                    type="text"
                    :placeholder="locale === 'ar' ? 'بحث بالعنوان...' : 'Search by title...'"
                    @keyup.enter="applyFilters" />
            </div>

            <!-- ── Table (desktop) ───────────────────────── -->
            <div class="table-wrap desktop-only">
                <table class="cases-table">
                    <thead>
                        <tr>
                            <th>{{ locale === 'ar' ? 'العنوان' : 'Title' }}</th>
                            <th>{{ locale === 'ar' ? 'التخصص' : 'Hub' }}</th>
                            <th>{{ locale === 'ar' ? 'الموضوع' : 'Topic' }}</th>
                            <th>{{ locale === 'ar' ? 'المستوى' : 'Difficulty' }}</th>
                            <th>{{ locale === 'ar' ? 'الحالة' : 'Status' }}</th>
                            <th>{{ locale === 'ar' ? 'إجراءات' : 'Actions' }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="cases.data.length === 0">
                            <td colspan="6" class="empty-row">
                                {{ locale === 'ar' ? 'لا توجد حالات' : 'No cases found.' }}
                            </td>
                        </tr>
                        <tr v-for="cas in cases.data" :key="cas.id">
                            <td class="title-cell">
                                <p class="case-title-text">{{ cas.title_en }}</p>
                                <p v-if="cas.title_ar" class="case-title-ar">{{ cas.title_ar }}</p>
                            </td>
                            <td>
                                <span class="hub-dot"
                                      :style="{ background: hubs.find(h => h.id === cas.hub_id)?.color }"></span>
                            </td>
                            <td class="topic-cell">{{ cas.topic_name_en }}</td>
                            <td>
                                <span class="diff-chip diff-chip--{{ cas.difficulty }}">
                                    {{ difficultyLabel(cas.difficulty) }}
                                </span>
                            </td>
                            <td>
                                <span class="status-chip" :class="statusClass(cas.status)">
                                    {{ statusLabel(cas.status) }}
                                </span>
                            </td>
                            <td class="actions-cell">
                                <!-- Edit -->
                                <Link :href="route('admin.cases.edit', cas.id)" class="act-btn act-btn--edit">
                                    <i class="ti ti-pencil" aria-hidden="true"></i>
                                </Link>

                                <!-- Publish (only if draft or review) -->
                                <button
                                    v-if="cas.status === 'draft' || cas.status === 'review'"
                                    class="act-btn act-btn--publish"
                                    :title="locale === 'ar' ? 'نشر' : 'Publish'"
                                    @click="publishCase(cas.id)">
                                    <i class="ti ti-eye" aria-hidden="true"></i>
                                </button>

                                <!-- Archive (only if published) -->
                                <button
                                    v-if="cas.status === 'published'"
                                    class="act-btn act-btn--archive"
                                    :title="locale === 'ar' ? 'أرشفة' : 'Archive'"
                                    @click="archiveCase(cas.id)">
                                    <i class="ti ti-archive" aria-hidden="true"></i>
                                </button>

                                <!-- Delete — confirm inline -->
                                <template v-if="confirmDeleteId === cas.id">
                                    <span class="confirm-text">
                                        {{ locale === 'ar' ? 'متأكد؟' : 'Sure?' }}
                                    </span>
                                    <button class="act-btn act-btn--confirm-del" @click="deleteCase(cas.id)">
                                        <i class="ti ti-check" aria-hidden="true"></i>
                                    </button>
                                    <button class="act-btn act-btn--cancel" @click="cancelDelete">
                                        <i class="ti ti-x" aria-hidden="true"></i>
                                    </button>
                                </template>
                                <button v-else class="act-btn act-btn--delete" @click="confirmDelete(cas.id)">
                                    <i class="ti ti-trash" aria-hidden="true"></i>
                                </button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- ── Card list (mobile) ─────────────────────── -->
            <div class="card-list mobile-only">
                <div v-if="cases.data.length === 0" class="empty-state">
                    {{ locale === 'ar' ? 'لا توجد حالات' : 'No cases found.' }}
                </div>
                <div v-for="cas in cases.data" :key="cas.id" class="admin-case-card">
                    <div class="admin-case-card__head">
                        <span class="status-chip" :class="statusClass(cas.status)">
                            {{ statusLabel(cas.status) }}
                        </span>
                        <span class="diff-chip">{{ difficultyLabel(cas.difficulty) }}</span>
                    </div>
                    <p class="admin-case-card__title">{{ cas.title_en }}</p>
                    <p class="admin-case-card__topic">{{ cas.topic_name_en }}</p>
                    <div class="admin-case-card__actions">
                        <Link :href="route('admin.cases.edit', cas.id)" class="act-btn act-btn--edit">
                            <i class="ti ti-pencil" aria-hidden="true"></i>
                            {{ locale === 'ar' ? 'تعديل' : 'Edit' }}
                        </Link>
                        <button
                            v-if="cas.status === 'draft' || cas.status === 'review'"
                            class="act-btn act-btn--publish"
                            @click="publishCase(cas.id)">
                            <i class="ti ti-eye" aria-hidden="true"></i>
                            {{ locale === 'ar' ? 'نشر' : 'Publish' }}
                        </button>
                        <button
                            v-if="cas.status === 'published'"
                            class="act-btn act-btn--archive"
                            @click="archiveCase(cas.id)">
                            <i class="ti ti-archive" aria-hidden="true"></i>
                            {{ locale === 'ar' ? 'أرشفة' : 'Archive' }}
                        </button>
                    </div>
                </div>
            </div>

            <!-- ── Pagination ─────────────────────────────── -->
            <div v-if="cases.last_page > 1" class="pagination">
                <Link v-if="cases.prev_page_url" :href="cases.prev_page_url" class="page-btn">
                    {{ locale === 'ar' ? 'السابق' : 'Prev' }}
                </Link>
                <span class="page-info">{{ cases.current_page }} / {{ cases.last_page }}</span>
                <Link v-if="cases.next_page_url" :href="cases.next_page_url" class="page-btn">
                    {{ locale === 'ar' ? 'التالي' : 'Next' }}
                </Link>
            </div>

        </div>
    </AdminLayout>
</template>

<style scoped>
.admin-cases { padding: 16px; display: flex; flex-direction: column; gap: 14px; }

.mobile-only  { display: flex; flex-direction: column; }
.desktop-only { display: none; }

/* Header */
.admin-header {
    display: flex; align-items: flex-start;
    justify-content: space-between; gap: 10px;
}

.admin-title { font-size: 18px; font-weight: 700; color: var(--color-text-primary); }
.admin-sub   { font-size: 11px; color: var(--color-text-muted); margin-top: 2px; }

.create-btn {
    display: inline-flex; align-items: center; gap: 5px;
    background: var(--color-primary); color: #fff;
    border: none; border-radius: var(--radius-md);
    padding: 8px 14px; font-size: 12px; font-weight: 600;
    text-decoration: none; white-space: nowrap;
    transition: background var(--transition-fast);
}
.create-btn:hover { background: var(--color-primary-light); }

/* Filter bar */
.filter-bar { display: flex; flex-wrap: wrap; gap: 7px; }

.filter-select, .filter-input {
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    padding: 7px 10px; font-size: 11px;
    color: var(--color-text-secondary);
    outline: none;
}

.filter-select:focus, .filter-input:focus { border-color: var(--color-primary); }
.filter-input { flex: 1; min-width: 140px; }

/* Status chips */
.status-chip {
    font-size: 9px; font-weight: 700; padding: 2px 7px;
    border-radius: var(--radius-pill);
}
.status--draft     { background: #f3f4f6; color: #374151; }
.status--review    { background: #fef3c7; color: #92400e; }
.status--published { background: #dcfce7; color: #166534; }
.status--archived  { background: #fee2e2; color: #991b1b; }

[data-theme="dark"] .status--draft     { background: #1f2937; color: #d1d5db; }
[data-theme="dark"] .status--review    { background: #2d1700; color: #fcd34d; }
[data-theme="dark"] .status--published { background: #052e16; color: #86efac; }
[data-theme="dark"] .status--archived  { background: #2d0000; color: #fca5a5; }

/* Diff chip */
.diff-chip { font-size: 9px; color: var(--color-text-muted); }

/* Action buttons */
.act-btn {
    display: inline-flex; align-items: center; gap: 4px;
    padding: 5px 8px; border-radius: var(--radius-sm);
    font-size: 11px; font-weight: 600; cursor: pointer;
    border: 1px solid var(--color-border);
    background: var(--color-surface-alt);
    color: var(--color-text-secondary);
    text-decoration: none;
    transition: background var(--transition-fast);
}
.act-btn--edit    { color: var(--color-primary); border-color: var(--color-primary); }
.act-btn--publish { color: #166534; border-color: #86efac; background: #dcfce7; }
.act-btn--archive { color: #92400e; border-color: #fcd34d; background: #fef3c7; }
.act-btn--delete  { color: #991b1b; border-color: #fca5a5; background: #fee2e2; }
.act-btn--confirm-del { color: #fff; background: #dc2626; border-color: #dc2626; }
.act-btn--cancel  { color: var(--color-text-muted); }
.confirm-text { font-size: 10px; font-weight: 700; color: #dc2626; }

/* Table */
.table-wrap { overflow-x: auto; border-radius: var(--radius-md); border: 0.5px solid var(--color-border); }
.cases-table { width: 100%; border-collapse: collapse; }
.cases-table th {
    background: var(--color-surface-alt);
    padding: 10px 12px; font-size: 10px; font-weight: 700;
    color: var(--color-text-muted); text-align: left;
    border-bottom: 1px solid var(--color-border);
    white-space: nowrap;
}
.cases-table td {
    padding: 10px 12px; font-size: 11px;
    color: var(--color-text-secondary);
    border-bottom: 0.5px solid var(--color-border-light);
    vertical-align: middle;
}
.cases-table tr:last-child td { border-bottom: none; }
.cases-table tr:hover td { background: var(--color-surface-alt); }

.title-cell { max-width: 220px; }
.case-title-text { font-weight: 600; color: var(--color-text-primary); font-size: 12px; }
.case-title-ar   { font-size: 10px; color: var(--color-text-muted); margin-top: 1px; }
.topic-cell { font-size: 10px; color: var(--color-text-muted); }
.actions-cell { display: flex; gap: 5px; align-items: center; flex-wrap: wrap; }
.empty-row { text-align: center; padding: 24px; color: var(--color-text-muted); font-size: 12px; }

.hub-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; }

/* Mobile cards */
.admin-case-card {
    background: var(--color-surface);
    border: 0.5px solid var(--color-border);
    border-radius: var(--radius-md);
    padding: 12px; display: flex; flex-direction: column; gap: 6px;
    box-shadow: var(--shadow-card);
}
.admin-case-card__head { display: flex; gap: 6px; align-items: center; }
.admin-case-card__title { font-size: 13px; font-weight: 600; color: var(--color-text-primary); }
.admin-case-card__topic { font-size: 10px; color: var(--color-text-muted); }
.admin-case-card__actions { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 4px; }

.empty-state { padding: 30px 16px; text-align: center; color: var(--color-text-muted); font-size: 12px; }

/* Pagination */
.pagination { display: flex; align-items: center; justify-content: center; gap: 12px; padding-top: 4px; }
.page-btn {
    display: inline-flex; align-items: center;
    background: var(--color-surface); border: 1px solid var(--color-border);
    border-radius: var(--radius-md); padding: 6px 12px;
    font-size: 11px; font-weight: 600; color: var(--color-text-secondary);
    text-decoration: none;
}
.page-btn:hover { border-color: var(--color-primary); color: var(--color-primary); }
.page-info { font-size: 11px; color: var(--color-text-muted); }

@media (min-width: 768px) {
    .mobile-only  { display: none; }
    .desktop-only { display: block; }
    .admin-cases  { padding: 20px 20px 24px; }
    .admin-title  { font-size: 20px; }
}
</style>
