<template>
    <Head :title="__('inventory_management')" />

    <AdminLayout>
        <div class="animate-fade-in space-y-6 pb-8">
            <!-- Header Section -->
            <div class="flex flex-col items-start justify-between gap-4 md:flex-row md:items-center">
                <div class="flex items-center gap-4">
                    <div class="bg-brand-primary/10 rounded-xl p-2.5">
                        <HardDrive class="text-brand-primary h-5 w-5" />
                    </div>
                    <div>
                        <h1 class="text-xl font-extrabold tracking-tight text-slate-900 dark:text-white">
                            {{ __('inventory_management') }}
                        </h1>
                        <p class="mt-0.5 text-sm text-slate-500 dark:text-slate-400">
                            {{ __('track_and_manage_company_hardware_and_assets_with_full_lifecycle_visibility') }}
                        </p>
                    </div>
                </div>
                <div class="flex items-center gap-3">
                    <Link
                        :href="admin.assets.categories.index.url()"
                        class="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-700 shadow-sm transition-all hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200"
                    >
                        <Tag class="h-4 w-4" />
                        {{ __('manage_categories') }}
                    </Link>
                    <Link
                        :href="admin.assets.create.url()"
                        class="inline-flex items-center gap-2 rounded-xl bg-slate-900 px-4 py-2 text-sm font-bold text-white shadow-md shadow-slate-900/20 transition-all hover:bg-slate-800 dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-white"
                    >
                        <Plus class="h-4 w-4" />
                        {{ __('add_new_asset') }}
                    </Link>
                </div>
            </div>

            <!-- Stats Bar (Data Dense) -->
            <div class="grid grid-cols-2 gap-4 md:grid-cols-4">
                <div
                    v-for="(stat, index) in stats"
                    :key="index"
                    class="flex items-center gap-4 rounded-xl border border-slate-100 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-800"
                >
                    <div :class="`rounded-lg p-2 bg-${stat.color}-500/10`">
                        <component :is="stat.icon" :class="`h-4 w-4 text-${stat.color}-500`" />
                    </div>
                    <div>
                        <p class="mb-0.5 text-[10px] font-bold tracking-widest text-slate-400 uppercase">{{ stat.label }}</p>
                        <p class="text-lg font-extrabold text-slate-900 dark:text-white">{{ stat.value }}</p>
                    </div>
                </div>
            </div>

            <!-- Filters Section -->
            <div
                class="overflow-hidden rounded-xl border border-slate-100 bg-white shadow-sm ring-1 ring-slate-200/50 dark:border-slate-700 dark:bg-slate-800 dark:ring-slate-700/50"
            >
                <div class="border-b border-slate-100 bg-slate-50/50 p-5 dark:border-slate-700 dark:bg-slate-900/50">
                    <div class="flex flex-col items-center gap-6 lg:flex-row">
                        <!-- Advanced Search -->
                        <div class="group relative w-full flex-1">
                            <div class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-4">
                                <Search class="group-focus-within:text-brand-primary h-5 w-4 text-slate-400 transition-colors" />
                            </div>
                            <input
                                v-model="filters.search"
                                type="text"
                                :placeholder="__('search_by_name_or_serial_number')"
                                class="focus:ring-brand-primary/10 focus:border-brand-primary w-full rounded-xl border-slate-200 bg-white py-2 pr-4 pl-11 text-sm font-medium shadow-sm transition-all placeholder:text-slate-400 focus:ring-4 dark:border-slate-700 dark:bg-slate-900"
                            />
                        </div>

                        <!-- Filter Controls -->
                        <div class="flex w-full flex-wrap items-center gap-3 lg:w-auto">
                            <div class="relative min-w-[160px] flex-1 lg:flex-none">
                                <SearchableSelect
                                    v-model="filters.category_id"
                                    :options="[{ id: '', name: __('all_categories') }, ...categories]"
                                    value-key="id"
                                    label-key="name"
                                    :placeholder="__('all_categories')"
                                />
                            </div>

                            <div class="relative min-w-[160px] flex-1 lg:flex-none">
                                <SearchableSelect
                                    v-model="filters.status"
                                    :options="[
                                        { id: '', name: __('all_status') },
                                        { id: 'available', name: __('available') },
                                        { id: 'assigned', name: __('assigned') },
                                        { id: 'maintenance', name: __('maintenance') },
                                        { id: 'retired', name: __('retired') },
                                    ]"
                                    value-key="id"
                                    label-key="name"
                                    :placeholder="__('all_status')"
                                />
                            </div>

                            <button
                                @click="resetFilters"
                                class="rounded-xl border border-slate-200 bg-white p-3 text-slate-400 shadow-sm transition-all hover:bg-red-50 hover:text-red-600 dark:border-slate-700 dark:bg-slate-900 dark:hover:bg-red-500/10"
                                :title="__('reset_filters')"
                            >
                                <RotateCcw class="h-4 w-4" />
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Inventory Catalog Card -->
            <div
                class="overflow-hidden rounded-xl border border-slate-100 bg-white shadow-sm ring-1 ring-slate-200/50 dark:border-slate-700 dark:bg-slate-800 dark:ring-slate-700/50"
            >
                <div class="overflow-x-auto">
                    <table class="w-full border-collapse text-left">
                        <thead>
                            <tr class="bg-slate-50/50 dark:bg-slate-900/50">
                                <th
                                    class="border-b border-slate-100 px-5 py-3 text-[10px] font-extrabold tracking-widest text-slate-400 uppercase dark:border-slate-700"
                                >
                                    {{ __('asset_identity') }}
                                </th>
                                <th
                                    class="border-b border-slate-100 px-5 py-3 text-[10px] font-extrabold tracking-widest text-slate-400 uppercase dark:border-slate-700"
                                >
                                    {{ __('category') }}
                                </th>
                                <th
                                    class="border-b border-slate-100 px-5 py-3 text-[10px] font-extrabold tracking-widest text-slate-400 uppercase dark:border-slate-700"
                                >
                                    {{ __('status_lifecycle') }}
                                </th>
                                <th
                                    class="border-b border-slate-100 px-5 py-3 text-[10px] font-extrabold tracking-widest text-slate-400 uppercase dark:border-slate-700"
                                >
                                    {{ __('current_custodian') }}
                                </th>
                                <th
                                    class="border-b border-slate-100 px-5 py-3 text-right text-[10px] font-extrabold tracking-widest text-slate-400 uppercase dark:border-slate-700"
                                >
                                    {{ __('action') }}
                                </th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-50 dark:divide-slate-700/50">
                            <tr
                                v-for="asset in assets.data"
                                :key="asset.id"
                                class="group transition-all hover:bg-slate-50/50 dark:hover:bg-slate-900/30"
                            >
                                <td class="px-5 py-3.5">
                                    <div class="flex items-center gap-3">
                                        <div
                                            class="flex h-9 w-9 items-center justify-center rounded-lg bg-slate-100 shadow-sm transition-colors group-hover:bg-white dark:bg-slate-700 dark:group-hover:bg-slate-600"
                                        >
                                            <HardDrive class="h-4 w-4 text-slate-500 dark:text-slate-400" />
                                        </div>
                                        <div>
                                            <Link
                                                :href="admin.assets.show.url({ asset: asset.id })"
                                                class="hover:text-brand-primary text-sm font-bold text-slate-900 transition-colors dark:text-white"
                                            >
                                                {{ asset.name }}
                                            </Link>
                                            <p class="mt-0.5 font-mono text-[11px] text-slate-400">{{ asset.serial_number }}</p>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-5 py-3.5">
                                    <span
                                        class="inline-flex items-center rounded border border-slate-200/50 bg-slate-100 px-2 py-0.5 text-[11px] font-bold text-slate-600 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-400"
                                    >
                                        {{ asset.category?.name }}
                                    </span>
                                </td>
                                <td class="px-5 py-3.5">
                                    <div class="flex flex-col gap-1.5">
                                        <span
                                            :class="[
                                                'inline-flex w-fit items-center rounded px-2 py-0.5 text-[10px] font-extrabold tracking-tight uppercase',
                                                getStatusClass(asset.status),
                                            ]"
                                        >
                                            <div class="mr-1.5 h-1 w-1 animate-pulse rounded-full bg-current"></div>
                                            {{ __(asset.status) }}
                                        </span>
                                        <p class="text-[10px] text-slate-400 italic">{{ __('updated') }}: {{ asset.updated_at_formatted }}</p>
                                    </div>
                                </td>
                                <td class="px-5 py-3.5">
                                    <div v-if="asset.current_assignment" class="flex items-center gap-2.5">
                                        <div
                                            class="bg-brand-primary/10 border-brand-primary/20 flex h-7 w-7 items-center justify-center rounded-full border"
                                        >
                                            <span class="text-brand-primary text-[10px] font-bold">{{
                                                asset.current_assignment.user?.name.charAt(0)
                                            }}</span>
                                        </div>
                                        <div>
                                            <p class="text-[13px] leading-none font-bold text-slate-700 dark:text-slate-300">
                                                {{ asset.current_assignment.user?.name }}
                                            </p>
                                            <p class="mt-1 text-[10px] text-slate-400">{{ asset.current_assignment.assigned_at_formatted }}</p>
                                        </div>
                                    </div>
                                    <span v-else class="flex items-center gap-1.5 text-[11px] font-medium text-slate-400">
                                        <div class="h-1 w-1 animate-pulse rounded-full bg-slate-300"></div>
                                        {{ __('unassigned') }}
                                    </span>
                                </td>
                                <td class="px-5 py-3.5 text-right">
                                    <div class="flex items-center justify-end gap-1.5 transition-all duration-200">
                                        <button
                                            v-if="asset.status === 'available'"
                                            @click="openQuickAssign(asset)"
                                            class="rounded-lg p-1.5 text-slate-400 transition-all hover:bg-emerald-50 hover:text-emerald-600 dark:hover:bg-emerald-500/10"
                                            :title="__('quick_assign')"
                                        >
                                            <UserPlus class="h-4 w-4" />
                                        </button>
                                        <Link
                                            :href="admin.assets.show.url({ asset: asset.id })"
                                            class="hover:text-brand-primary hover:bg-brand-primary/5 rounded-lg p-1.5 text-slate-400 transition-all"
                                            :title="__('view_details')"
                                        >
                                            <Eye class="h-4 w-4" />
                                        </Link>
                                        <Link
                                            :href="admin.assets.edit.url({ asset: asset.id })"
                                            class="rounded-lg p-1.5 text-slate-400 transition-all hover:bg-amber-50 hover:text-amber-600 dark:hover:bg-amber-500/10"
                                            :title="__('edit_asset')"
                                        >
                                            <Edit2 class="h-4 w-4" />
                                        </Link>
                                    </div>
                                </td>
                            </tr>
                            <tr v-if="assets.data.length === 0">
                                <td colspan="5" class="px-5 py-12 text-center">
                                    <div class="flex flex-col items-center gap-3">
                                        <div class="rounded-full bg-slate-50 p-4 dark:bg-slate-900">
                                            <Info class="h-8 w-8 text-slate-300" />
                                        </div>
                                        <div class="max-w-xs">
                                            <p class="text-sm font-bold text-slate-900 dark:text-white">
                                                {{ __('no_assets_matched_your_criteria') }}
                                            </p>
                                            <p class="mt-1 text-xs text-slate-400">{{ __('reset_filters_and_try_again') }}</p>
                                        </div>
                                        <button @click="resetFilters" class="text-brand-primary mt-2 text-xs font-bold hover:underline">
                                            {{ __('reset_filters') }}
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div
                    v-if="assets.links && assets.links.length > 3"
                    class="flex justify-center border-t border-slate-50 bg-slate-50/30 p-5 dark:border-slate-700"
                >
                    <component
                        :is="link.url ? 'Link' : 'span'"
                        v-for="(link, k) in assets.links"
                        :key="k"
                        :href="link.url"
                        v-html="link.label"
                        class="rounded-lg px-3 py-1 text-xs transition-all"
                        :class="{
                            'bg-brand-primary shadow-brand-primary/20 font-bold text-white shadow-md': link.active,
                            'text-slate-500 hover:bg-white dark:hover:bg-slate-800': link.url && !link.active,
                            'text-slate-300': !link.url,
                        }"
                    />
                </div>
            </div>
        </div>

        <!-- Premium Quick Assign Modal -->
        <Modal :show="showAssignModal" @close="showAssignModal = false" :title="__('quick_assignment')" max-width="md">
            <div
                class="-mx-6 -mt-4 mb-6 flex items-center gap-4 border-b border-emerald-100 bg-emerald-50/50 p-4 dark:border-emerald-500/10 dark:bg-emerald-500/5"
            >
                <div
                    class="flex h-12 w-12 items-center justify-center rounded-2xl border border-emerald-100 bg-white shadow-sm dark:border-emerald-500/20 dark:bg-slate-800"
                >
                    <Monitor class="h-6 w-6 text-emerald-600" />
                </div>
                <div>
                    <h3 class="text-sm leading-tight font-extrabold text-slate-800 dark:text-white">
                        {{ selectedAsset?.name }}
                    </h3>
                    <p class="mt-0.5 text-[11px] font-bold tracking-widest text-emerald-600 uppercase">
                        {{ selectedAsset?.serial_number }}
                    </p>
                </div>
            </div>

            <form @submit.prevent="submitAssignment" class="space-y-6">
                <div class="space-y-2">
                    <label class="flex items-center gap-2 px-1 text-[11px] font-bold tracking-widest text-slate-400 uppercase">
                        <Users class="h-3 w-3" />
                        {{ __('select_employee') }}
                    </label>
                    <div class="relative">
                        <SearchableSelect
                            v-model="assignForm.user_id"
                            :options="users"
                            value-key="id"
                            label-key="name"
                            :placeholder="__('choose_personnel')"
                        />
                    </div>
                </div>

                <div class="space-y-2">
                    <label class="flex items-center gap-2 px-1 text-[11px] font-bold tracking-widest text-slate-400 uppercase">
                        <StickyNote class="h-3 w-3" />
                        {{ __('handover_notes') }}
                    </label>
                    <div class="group relative">
                        <textarea
                            v-model="assignForm.notes"
                            rows="4"
                            class="focus:ring-brand-primary/10 focus:border-brand-primary w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-4 py-2 text-sm font-medium shadow-inner transition-all duration-300 focus:ring-4 dark:border-slate-800 dark:bg-slate-950 dark:text-white"
                            :placeholder="__('e_g_fresh_install_clean_condition')"
                        ></textarea>
                    </div>
                </div>

                <div class="flex items-center justify-end gap-3 border-t border-slate-50 pt-6 dark:border-slate-800/60">
                    <button
                        type="button"
                        @click="showAssignModal = false"
                        class="rounded-xl px-5 py-2.5 text-sm font-bold text-slate-500 transition-all hover:bg-slate-50 hover:text-slate-900 dark:hover:bg-slate-800 dark:hover:text-white"
                    >
                        {{ __('cancel') }}
                    </button>
                    <button
                        type="submit"
                        :disabled="assignForm.processing"
                        class="group/btn relative flex items-center gap-2 overflow-hidden rounded-xl bg-slate-900 px-4 py-2 text-sm font-extrabold text-white shadow-xl shadow-slate-900/20 transition-all hover:bg-slate-800 active:scale-95 disabled:opacity-50 dark:bg-white dark:text-slate-900 dark:hover:bg-slate-100"
                    >
                        <div
                            class="group-hover/btn:animate-shimmer absolute inset-0 -translate-x-full bg-gradient-to-r from-transparent via-white/5 to-transparent"
                        ></div>
                        <CheckCircle class="relative z-10 h-4 w-4" v-if="!assignForm.processing" />
                        <div
                            class="relative z-10 h-4 w-4 animate-spin rounded-full border-2 border-white/20 border-t-white dark:border-slate-900/20 dark:border-t-slate-900"
                            v-else
                        ></div>
                        <span class="relative z-10">{{ __('confirm_deployment') }}</span>
                    </button>
                </div>
            </form>
        </Modal>
    </AdminLayout>
</template>

<script setup lang="ts">
import Modal from '@/Components/Common/Modal.vue';
import SearchableSelect from '@/Components/Common/SearchableSelect.vue';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import admin from '@/routes/admin';
import { Head, Link, router, useForm } from '@inertiajs/vue3';
import { debounce } from 'lodash';
import {
    Activity,
    CheckCircle,
    Edit2,
    Eye,
    HardDrive,
    Info,
    Monitor,
    Package,
    Plus,
    RotateCcw,
    Search,
    ShieldCheck,
    StickyNote,
    Tag,
    UserPlus,
    Users,
} from 'lucide-vue-next';
import { reactive, ref, watch } from 'vue';

const props = defineProps<{
    assets: {
        data: any[];
        links: any[];
        total: number;
        from: number;
        to: number;
    };
    categories: any[];
    users: any[];
    filters: {
        search?: string;
        category_id?: string;
        status?: string;
    };
}>();

const filters = reactive({
    search: props.filters.search || '',
    category_id: props.filters.category_id || '',
    status: props.filters.status || '',
});

const stats = [
    { label: 'Total Assets', value: props.assets.total, icon: HardDrive, color: 'blue' },
    { label: 'Available', value: props.assets.data.filter((a) => a.status === 'available').length, icon: ShieldCheck, color: 'emerald' },
    { label: 'Decommissioned', value: 0, icon: Package, color: 'slate' },
    { label: 'Maintenance', value: 0, icon: Activity, color: 'amber' },
];

const showAssignModal = ref(false);
const selectedAsset = ref<any>(null);

const assignForm = useForm({
    asset_id: null as number | null,
    user_id: '',
    notes: '',
});

const openQuickAssign = (asset: any) => {
    selectedAsset.value = asset;
    assignForm.asset_id = asset.id;
    assignForm.user_id = '';
    assignForm.notes = '';
    showAssignModal.value = true;
};

const submitAssignment = () => {
    assignForm.post(admin.assets.assignments.store.url(), {
        onSuccess: () => {
            showAssignModal.value = false;
        },
    });
};

const handleSearch = debounce(() => {
    router.get(admin.assets.index.url(), filters, { preserveState: true, preserveScroll: true });
}, 300);

watch([() => filters.search, () => filters.category_id, () => filters.status], () => {
    handleSearch();
});

const resetFilters = () => {
    filters.search = '';
    filters.category_id = '';
    filters.status = '';
};

const getStatusClass = (status: string) => {
    switch (status) {
        case 'available':
            return 'bg-emerald-50 text-emerald-700 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20';
        case 'assigned':
            return 'bg-sky-50 text-sky-700 border-sky-100 dark:bg-sky-500/10 dark:text-sky-400 dark:border-sky-500/20';
        case 'maintenance':
            return 'bg-amber-50 text-amber-700 border-amber-100 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/20';
        case 'retired':
            return 'bg-slate-50 text-slate-500 border-slate-200 dark:bg-slate-700/50 dark:text-slate-400 dark:border-slate-600';
        default:
            return 'bg-slate-50 text-slate-500 border-slate-200';
    }
};
</script>

<style scoped>
.animate-fade-in {
    animation: fadeIn 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>
