<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Member/ShareKnowledge/CreateDocument.vue
//  Location: resources/js/Pages/Member/ShareKnowledge/CreateDocument.vue
//
//  Upload a PDF report, template, or guide to Share Knowledge.
//
//  Fields:
//    - File upload (PDF only, max 10MB)
//    - Title EN (required) + Title AR (optional)
//    - Description EN + AR (optional)
//    - Category: report | template | guide | news | other
//    - Hub selector
//    - Sector (optional)
//    - Language toggle
//    - Visibility: all | hub
//    - Tags (optional, max 5)
//
//  File security (Bible):
//    - mimes:pdf enforced by StoreDocumentRequest on the backend
//    - max 10MB enforced on backend
//    - Frontend shows preview of selected file — name + size
//    - Submitted via multipart form (router.post with FormData)
// ══════════════════════════════════════════════════════════════════

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

const props = defineProps({
    allHubs: { type: Array, default: () => [] },
    sectors: { type: Array, default: () => [] },
    errors:  { type: Object, default: () => ({}) },
});

const authStore  = useAuthStore();
const locale     = computed(() => authStore.locale);
const isUploading = ref(false);

// ── Form state ────────────────────────────────────────────────────
const form = ref({
    hub_id:             props.allHubs[0]?.id ?? null,
    sector_id:          null,
    title_en:           '',
    title_ar:           '',
    description_en:     '',
    description_ar:     '',
    document_category:  'report',
    language:           locale.value === 'ar' ? 'ar' : 'en',
    visibility:         'all',
    tags:               [],
});

const selectedFile = ref(null);
const fileError    = ref('');
const tagInput     = ref('');
const dragOver     = ref(false);

const categories = [
    { value: 'report',   en: 'Report',   ar: 'تقرير'  },
    { value: 'template', en: 'Template', ar: 'نموذج'  },
    { value: 'guide',    en: 'Guide',    ar: 'دليل'   },
    { value: 'news',     en: 'News',     ar: 'أخبار'  },
    { value: 'other',    en: 'Other',    ar: 'أخرى'   },
];

// ── File handling ─────────────────────────────────────────────────
function handleFileSelect(event) {
    const file = event.target.files[0];
    validateAndSetFile(file);
}

function handleDrop(event) {
    dragOver.value = false;
    const file = event.dataTransfer.files[0];
    validateAndSetFile(file);
}

function validateAndSetFile(file) {
    fileError.value = '';
    if (!file) return;
    if (file.type !== 'application/pdf') {
        fileError.value = locale.value === 'ar'
            ? 'يجب أن يكون الملف PDF فقط'
            : 'File must be a PDF';
        return;
    }
    if (file.size > 10 * 1024 * 1024) {
        fileError.value = locale.value === 'ar'
            ? 'حجم الملف يجب ألا يتجاوز 10MB'
            : 'File must be under 10MB';
        return;
    }
    selectedFile.value = file;
}

const fileSizeFormatted = computed(() => {
    if (!selectedFile.value) return '';
    const bytes = selectedFile.value.size;
    if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + ' MB';
    return (bytes / 1024).toFixed(0) + ' KB';
});

// ── Tags ──────────────────────────────────────────────────────────
function addTag() {
    const t = tagInput.value.trim();
    if (t && form.value.tags.length < 5 && !form.value.tags.includes(t)) {
        form.value.tags.push(t);
    }
    tagInput.value = '';
}
function removeTag(tag) {
    form.value.tags = form.value.tags.filter(t => t !== tag);
}
function handleTagKeydown(e) {
    if (e.key === 'Enter' || e.key === ',') {
        e.preventDefault();
        addTag();
    }
}

// ── Submit ────────────────────────────────────────────────────────
function submit() {
    if (isUploading.value || !selectedFile.value) return;
    isUploading.value = true;

    // Must use FormData for file upload
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    Object.keys(form.value).forEach(key => {
        const val = form.value[key];
        if (Array.isArray(val)) {
            val.forEach(v => formData.append(`${key}[]`, v));
        } else if (val !== null && val !== '') {
            formData.append(key, val);
        }
    });

    router.post(route('member.share.document.store'), formData, {
        forceFormData: true,
        onError:  () => { isUploading.value = false; },
        onFinish: () => { isUploading.value = false; },
    });
}

function hubName(hub) {
    return locale.value === 'ar' ? hub.name_ar : hub.name_en;
}
function sectorName(sector) {
    return locale.value === 'ar' ? sector.name_ar : sector.name_en;
}
</script>

<template>
    <AppLayout :title="locale === 'ar' ? 'رفع ملف PDF' : 'Upload PDF Report'">
        <Head :title="locale === 'ar' ? 'رفع ملف PDF' : 'Upload PDF Report'" />

        <div class="cd-page">
            <div class="cd-card">

                <!-- Header -->
                <div class="cd-header">
                    <Link :href="route('member.share.index')" class="cd-back">
                        <i class="ti ti-arrow-left"></i>
                    </Link>
                    <div>
                        <h1 class="cd-title">
                            {{ locale === 'ar' ? 'شارك تقرير أو ملف PDF' : 'Share a PDF Report' }}
                        </h1>
                        <p class="cd-sub">
                            {{ locale === 'ar'
                                ? 'ارفع تقرير، نموذج، أو دليل مهني مفيد للأعضاء'
                                : 'Upload a report, template, or professional guide for the community' }}
                        </p>
                    </div>
                </div>

                <!-- File drop zone -->
                <div class="cd-field">
                    <label class="cd-label">
                        {{ locale === 'ar' ? 'الملف (PDF فقط، حتى 10MB)' : 'File (PDF only, max 10MB)' }}
                        <span class="cd-required">*</span>
                    </label>

                    <div
                        class="cd-dropzone"
                        :class="{ 'cd-dropzone--over': dragOver, 'cd-dropzone--filled': selectedFile }"
                        @dragover.prevent="dragOver = true"
                        @dragleave="dragOver = false"
                        @drop.prevent="handleDrop"
                        @click="$refs.fileInput.click()"
                    >
                        <input
                            ref="fileInput"
                            type="file"
                            accept=".pdf,application/pdf"
                            class="cd-file-input"
                            @change="handleFileSelect"
                        />

                        <template v-if="!selectedFile">
                            <i class="ti ti-cloud-upload cd-dropzone__icon"></i>
                            <div class="cd-dropzone__text">
                                {{ locale === 'ar' ? 'اسحب الملف هنا أو اضغط للاختيار' : 'Drag & drop or click to select' }}
                            </div>
                            <div class="cd-dropzone__hint">PDF · Max 10MB</div>
                        </template>

                        <template v-else>
                            <i class="ti ti-file-type-pdf cd-dropzone__icon cd-dropzone__icon--pdf"></i>
                            <div class="cd-dropzone__filename">{{ selectedFile.name }}</div>
                            <div class="cd-dropzone__size">{{ fileSizeFormatted }}</div>
                            <button
                                type="button"
                                class="cd-dropzone__remove"
                                @click.stop="selectedFile = null"
                            >
                                <i class="ti ti-x"></i>
                                {{ locale === 'ar' ? 'إزالة' : 'Remove' }}
                            </button>
                        </template>
                    </div>
                    <span v-if="fileError || errors.file" class="cd-error">
                        {{ fileError || errors.file }}
                    </span>
                </div>

                <!-- Hub selector -->
                <div class="cd-field">
                    <label class="cd-label">{{ locale === 'ar' ? 'المجموعة' : 'Hub' }} <span class="cd-required">*</span></label>
                    <div class="cd-hub-row">
                        <button
                            v-for="hub in allHubs"
                            :key="hub.id"
                            type="button"
                            class="cd-hub-btn"
                            :class="{ 'cd-hub-btn--active': form.hub_id === hub.id }"
                            :style="form.hub_id === hub.id ? `--hub-color: ${hub.color}` : ''"
                            @click="form.hub_id = hub.id"
                        >{{ hubName(hub) }}</button>
                    </div>
                </div>

                <!-- Category -->
                <div class="cd-field">
                    <label class="cd-label">{{ locale === 'ar' ? 'نوع الملف' : 'Category' }} <span class="cd-required">*</span></label>
                    <div class="cd-cat-row">
                        <button
                            v-for="cat in categories"
                            :key="cat.value"
                            type="button"
                            class="cd-cat-btn"
                            :class="{ 'cd-cat-btn--active': form.document_category === cat.value }"
                            @click="form.document_category = cat.value"
                        >{{ locale === 'ar' ? cat.ar : cat.en }}</button>
                    </div>
                    <span v-if="errors.document_category" class="cd-error">{{ errors.document_category }}</span>
                </div>

                <!-- Title EN -->
                <div class="cd-field">
                    <label class="cd-label">{{ locale === 'ar' ? 'العنوان (إنجليزي)' : 'Title (English)' }} <span class="cd-required">*</span></label>
                    <input v-model="form.title_en" type="text" class="cd-input" placeholder="Report title in English..." maxlength="255" />
                    <span v-if="errors.title_en" class="cd-error">{{ errors.title_en }}</span>
                </div>

                <!-- Title AR -->
                <div class="cd-field">
                    <label class="cd-label">{{ locale === 'ar' ? 'العنوان (عربي) — اختياري' : 'Title (Arabic) — optional' }}</label>
                    <input v-model="form.title_ar" type="text" class="cd-input cd-input--rtl" placeholder="عنوان التقرير بالعربية..." dir="rtl" maxlength="255" />
                </div>

                <!-- Description EN -->
                <div class="cd-field">
                    <label class="cd-label">{{ locale === 'ar' ? 'وصف مختصر (إنجليزي) — اختياري' : 'Short description (English) — optional' }}</label>
                    <textarea v-model="form.description_en" class="cd-textarea" rows="3" placeholder="What is this document about..."></textarea>
                </div>

                <!-- Sector + Visibility row -->
                <div class="cd-row">
                    <!-- Sector -->
                    <div class="cd-field cd-field--half">
                        <label class="cd-label">{{ locale === 'ar' ? 'القطاع — اختياري' : 'Sector — optional' }}</label>
                        <select v-model="form.sector_id" class="cd-select">
                            <option :value="null">{{ locale === 'ar' ? 'كل القطاعات' : 'All sectors' }}</option>
                            <option v-for="sector in sectors" :key="sector.id" :value="sector.id">
                                {{ sectorName(sector) }}
                            </option>
                        </select>
                    </div>

                    <!-- Visibility -->
                    <div class="cd-field cd-field--half">
                        <label class="cd-label">{{ locale === 'ar' ? 'الظهور' : 'Visibility' }}</label>
                        <div class="cd-toggle-row">
                            <button type="button" class="cd-toggle-btn" :class="{ 'cd-toggle-btn--active': form.visibility === 'all' }" @click="form.visibility = 'all'">
                                {{ locale === 'ar' ? 'الجميع' : 'All' }}
                            </button>
                            <button type="button" class="cd-toggle-btn" :class="{ 'cd-toggle-btn--active': form.visibility === 'hub' }" @click="form.visibility = 'hub'">
                                {{ locale === 'ar' ? 'المجموعة فقط' : 'Hub only' }}
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Tags -->
                <div class="cd-field">
                    <label class="cd-label">{{ locale === 'ar' ? 'وسوم (اختياري، حتى 5)' : 'Tags (optional, max 5)' }}</label>
                    <div class="cd-tags-input">
                        <span v-for="tag in form.tags" :key="tag" class="cd-tag">
                            {{ tag }}<button type="button" @click="removeTag(tag)">×</button>
                        </span>
                        <input
                            v-if="form.tags.length < 5"
                            v-model="tagInput"
                            type="text"
                            :placeholder="locale === 'ar' ? 'أضف وسمًا...' : 'Add a tag...'"
                            @keydown="handleTagKeydown"
                        />
                    </div>
                </div>

                <!-- Actions -->
                <div class="cd-actions">
                    <Link :href="route('member.share.index')" class="cd-btn-cancel">
                        {{ locale === 'ar' ? 'إلغاء' : 'Cancel' }}
                    </Link>
                    <button
                        type="button"
                        class="cd-btn-submit"
                        :disabled="isUploading || !selectedFile || !form.title_en"
                        @click="submit"
                    >
                        <i v-if="isUploading" class="ti ti-loader cd-spin"></i>
                        <i v-else class="ti ti-upload"></i>
                        {{ locale === 'ar' ? 'رفع الملف' : 'Upload Report' }}
                    </button>
                </div>

            </div>
        </div>
    </AppLayout>
</template>

<style scoped>
.cd-page { padding: 16px; display: flex; justify-content: center; }
.cd-card {
    width: 100%; max-width: 720px;
    background: var(--color-surface);
    border-radius: 16px; border: 1.5px solid var(--color-border);
    padding: 24px; display: flex; flex-direction: column; gap: 20px;
}
.cd-header { display: flex; align-items: flex-start; gap: 14px; }
.cd-back {
    display: flex; align-items: center; justify-content: center;
    width: 36px; height: 36px; border-radius: 10px;
    border: 1.5px solid var(--color-border);
    background: transparent; color: var(--color-text-muted);
    text-decoration: none; flex-shrink: 0; transition: all 0.15s;
}
.cd-back:hover { border-color: var(--color-primary); color: var(--color-primary); }
.cd-title { font-size: 18px; font-weight: 700; color: var(--color-text); margin-bottom: 4px; }
.cd-sub   { font-size: 13px; color: var(--color-text-muted); line-height: 1.4; }

.cd-field { display: flex; flex-direction: column; gap: 6px; }
.cd-field--half { flex: 1; }
.cd-row { display: flex; gap: 16px; flex-wrap: wrap; }
.cd-label   { font-size: 13px; font-weight: 600; color: var(--color-text); }
.cd-required { color: #e53e3e; }
.cd-error   { font-size: 12px; color: #e53e3e; }

.cd-dropzone {
    border: 2px dashed var(--color-border);
    border-radius: 12px; padding: 32px 16px;
    display: flex; flex-direction: column; align-items: center; gap: 8px;
    cursor: pointer; transition: all 0.15s; text-align: center;
    background: var(--color-bg);
    position: relative;
}
.cd-dropzone:hover, .cd-dropzone--over {
    border-color: var(--color-primary);
    background: rgba(29,158,117,0.04);
}
.cd-dropzone--filled { border-style: solid; border-color: var(--color-primary); }
.cd-file-input { display: none; }
.cd-dropzone__icon { font-size: 36px; color: var(--color-text-muted); }
.cd-dropzone__icon--pdf { color: #D85A30; }
.cd-dropzone__text { font-size: 14px; font-weight: 600; color: var(--color-text); }
.cd-dropzone__hint, .cd-dropzone__size { font-size: 12px; color: var(--color-text-muted); }
.cd-dropzone__filename { font-size: 14px; font-weight: 600; color: var(--color-text); word-break: break-all; }
.cd-dropzone__remove {
    display: inline-flex; align-items: center; gap: 4px;
    padding: 4px 12px; border-radius: 8px; border: none;
    background: rgba(229,62,62,0.1); color: #e53e3e;
    font-size: 12px; cursor: pointer; margin-top: 4px;
}

.cd-input, .cd-textarea, .cd-select {
    padding: 10px 14px; border-radius: 10px;
    border: 1.5px solid var(--color-border);
    background: var(--color-bg); color: var(--color-text);
    font-size: 14px; outline: none;
    transition: border-color 0.15s; width: 100%; box-sizing: border-box;
}
.cd-input:focus, .cd-textarea:focus, .cd-select:focus { border-color: var(--color-primary); }
.cd-textarea { resize: vertical; font-family: inherit; }
.cd-input--rtl { text-align: right; }

.cd-hub-row, .cd-cat-row { display: flex; gap: 8px; flex-wrap: wrap; }
.cd-hub-btn, .cd-cat-btn {
    padding: 7px 14px; border-radius: 20px;
    border: 1.5px solid var(--color-border);
    background: transparent; color: var(--color-text-muted);
    font-size: 12px; font-weight: 500; cursor: pointer; transition: all 0.15s;
}
.cd-hub-btn--active {
    border-color: var(--hub-color, var(--color-primary));
    color: var(--hub-color, var(--color-primary));
    background: rgba(29,158,117,0.08);
}
.cd-cat-btn--active {
    border-color: var(--color-primary);
    color: var(--color-primary);
    background: rgba(29,158,117,0.08);
}

.cd-toggle-row { display: flex; border-radius: 10px; overflow: hidden; border: 1.5px solid var(--color-border); }
.cd-toggle-btn {
    flex: 1; padding: 8px 12px; border: none;
    background: transparent; color: var(--color-text-muted);
    font-size: 12px; font-weight: 500; cursor: pointer; transition: all 0.15s;
}
.cd-toggle-btn--active { background: var(--color-primary); color: #fff; }

.cd-tags-input {
    display: flex; flex-wrap: wrap; gap: 6px; align-items: center;
    padding: 8px 12px; border-radius: 10px;
    border: 1.5px solid var(--color-border); background: var(--color-bg);
    min-height: 42px;
}
.cd-tag {
    display: inline-flex; align-items: center; gap: 4px;
    padding: 3px 10px; border-radius: 20px;
    background: rgba(29,158,117,0.12); color: var(--color-primary);
    font-size: 12px; font-weight: 500;
}
.cd-tag button { background: none; border: none; cursor: pointer; color: inherit; font-size: 14px; padding: 0; }
.cd-tags-input input {
    border: none; background: transparent; outline: none;
    font-size: 13px; color: var(--color-text); min-width: 100px; flex: 1;
}

.cd-actions { display: flex; gap: 12px; justify-content: flex-end; padding-top: 4px; }
.cd-btn-cancel {
    padding: 10px 20px; border-radius: 10px;
    border: 1.5px solid var(--color-border);
    background: transparent; color: var(--color-text-muted);
    font-size: 13px; font-weight: 600; text-decoration: none;
    display: inline-flex; align-items: center;
}
.cd-btn-submit {
    display: inline-flex; align-items: center; gap: 6px;
    padding: 10px 24px; border-radius: 10px;
    background: var(--color-primary); color: #fff;
    font-size: 13px; font-weight: 700; border: none; cursor: pointer;
    transition: opacity 0.15s;
}
.cd-btn-submit:disabled { opacity: 0.6; cursor: not-allowed; }
@keyframes spin { to { transform: rotate(360deg); } }
.cd-spin { animation: spin 0.8s linear infinite; }

@media (min-width: 768px) {
    .cd-page { padding: 28px; }
    .cd-card { padding: 32px; }
}
</style>
