<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { Head, useForm, Link, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Search, Store, MapPin, AlignLeft, Edit2, Trash2, UserCheck, Plus, AlertCircle, CheckCircle2, X } from 'lucide-vue-next';

interface CashierUser {
    id: number;
    name: string;
    email: string;
    outlet_id: number | null;
    outlet?: { id: number; name: string } | null;
    roles?: { name: string }[];
}

interface OutletData {
    id: number;
    name: string;
    location: string | null;
    description: string | null;
    users_count: number;
    transactions_count: number;
    created_at: string;
}

interface PaginatedOutlets {
    data: OutletData[];
    current_page: number;
    last_page: number;
    prev_page_url: string | null;
    next_page_url: string | null;
    total: number;
    links: { url: string | null; label: string; active: boolean }[];
}

const props = defineProps<{
    outlets: PaginatedOutlets;
    availableUsers: CashierUser[];
    filters: {
        search?: string;
    };
}>();

const search = ref(props.filters.search || '');

// Debounce search
let timeoutId: ReturnType<typeof setTimeout> | null = null;
watch(search, () => {
    if (timeoutId) clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
        router.get(
            route('outlets.index'),
            { search: search.value },
            { preserveState: true, replace: true }
        );
    }, 400);
});

// Modal state
const isFormModalOpen = ref(false);
const isDeleteModalOpen = ref(false);
const editingOutlet = ref<OutletData | null>(null);
const outletToDelete = ref<OutletData | null>(null);

// Form config
const form = useForm({
    name: '',
    location: '',
    description: '',
    assigned_users: [] as number[],
});

// All available cashiers can be assigned / reassigned
const assignableUsers = computed(() => {
    return props.availableUsers;
});

const openCreateModal = () => {
    editingOutlet.value = null;
    form.clearErrors();
    form.reset();
    isFormModalOpen.value = true;
};

const openEditModal = (outlet: OutletData) => {
    editingOutlet.value = outlet;
    form.clearErrors();
    form.name = outlet.name;
    form.location = outlet.location || '';
    form.description = outlet.description || '';
    
    // Find users currently assigned to this outlet
    form.assigned_users = props.availableUsers
        .filter(u => u.outlet_id === outlet.id)
        .map(u => u.id);

    isFormModalOpen.value = true;
};

const submitForm = () => {
    if (editingOutlet.value) {
        form.put(route('outlets.update', editingOutlet.value.id), {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    } else {
        form.post(route('outlets.store'), {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    }
};

const openDeleteModal = (outlet: OutletData) => {
    outletToDelete.value = outlet;
    isDeleteModalOpen.value = true;
};

const deleteOutlet = () => {
    if (!outletToDelete.value) return;
    router.delete(route('outlets.destroy', outletToDelete.value.id), {
        onSuccess: () => {
            isDeleteModalOpen.value = false;
            outletToDelete.value = null;
        },
    });
};

const toggleUserAssignment = (userId: number) => {
    const idx = form.assigned_users.indexOf(userId);
    if (idx > -1) {
        form.assigned_users.splice(idx, 1);
    } else {
        form.assigned_users.push(userId);
    }
};
</script>

<template>
    <Head title="Outlet Management" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header Section -->
            <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                <div>
                    <h1 class="text-2xl font-bold tracking-tight text-slate-900 dark:text-slate-50">Outlet Management</h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Configure your physical coffee shops, check sales channels, and map cashier accounts.
                    </p>
                </div>
                <button
                    @click="openCreateModal"
                    class="inline-flex items-center justify-center gap-2 px-4 py-2.5 bg-red-600 hover:bg-red-500 text-white rounded-lg text-sm font-semibold shadow-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 transition-all cursor-pointer"
                >
                    <Plus class="h-4 w-4" />
                    <span>Create Outlet</span>
                </button>
            </div>

            <!-- Filters & Cards -->
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-sm overflow-hidden">
                <div class="p-5 border-b border-slate-200 dark:border-slate-800 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                    <div class="relative max-w-md w-full">
                        <Search class="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
                        <input
                            v-model="search"
                            type="text"
                            placeholder="Search outlets name or location..."
                            class="w-full pl-9 pr-4 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all text-slate-900 dark:text-slate-100"
                        />
                    </div>
                </div>

                <!-- Table -->
                <div class="overflow-x-auto">
                    <table class="w-full border-collapse text-left">
                        <thead>
                            <tr class="border-b border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/30">
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Outlet Info</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Location</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 text-center">Cashiers</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 text-center">Transactions</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-200 dark:divide-slate-800">
                            <tr v-if="outlets.data.length === 0">
                                <td colspan="5" class="p-8 text-center text-sm text-slate-500 dark:text-slate-400">
                                    No outlets found. Try creating one!
                                </td>
                            </tr>
                            <tr 
                                v-for="outlet in outlets.data" 
                                :key="outlet.id"
                                class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-colors"
                            >
                                <td class="p-4">
                                    <div class="flex items-center gap-3">
                                        <div class="h-10 w-10 rounded-lg bg-red-50 dark:bg-red-950/30 flex items-center justify-center text-red-600 dark:text-red-400">
                                            <Store class="h-5 w-5" />
                                        </div>
                                        <div>
                                            <p class="text-sm font-semibold text-slate-900 dark:text-slate-100">{{ outlet.name }}</p>
                                            <p class="text-xs text-slate-400 dark:text-slate-500 truncate max-w-xs mt-0.5">{{ outlet.description || 'No description' }}</p>
                                        </div>
                                    </div>
                                </td>
                                <td class="p-4 text-sm text-slate-600 dark:text-slate-300">
                                    <div class="flex items-center gap-1.5">
                                        <MapPin class="h-4 w-4 text-slate-400 flex-shrink-0" />
                                        <span class="truncate max-w-xs">{{ outlet.location || '-' }}</span>
                                    </div>
                                </td>
                                <td class="p-4 text-sm text-slate-600 dark:text-slate-300 text-center">
                                    <span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-blue-50 dark:bg-blue-950/30 text-blue-700 dark:text-blue-400">
                                        {{ outlet.users_count }} Cashier(s)
                                    </span>
                                </td>
                                <td class="p-4 text-sm text-slate-600 dark:text-slate-300 text-center">
                                    <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-emerald-50 dark:bg-emerald-950/30 text-emerald-700 dark:text-emerald-400">
                                        {{ outlet.transactions_count }}
                                    </span>
                                </td>
                                <td class="p-4 text-right">
                                    <div class="flex items-center justify-end gap-2">
                                        <button
                                            @click="openEditModal(outlet)"
                                            class="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-950 text-slate-500 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-100 transition-colors cursor-pointer"
                                            title="Edit Outlet"
                                        >
                                            <Edit2 class="h-4 w-4" />
                                        </button>
                                        <button
                                            @click="openDeleteModal(outlet)"
                                            class="p-2 rounded-lg hover:bg-rose-50 dark:hover:bg-rose-955/20 text-rose-500 hover:text-rose-600 transition-colors cursor-pointer"
                                            title="Delete Outlet"
                                        >
                                            <Trash2 class="h-4 w-4" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <div v-if="outlets.last_page > 1" class="p-4 border-t border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <p class="text-xs text-slate-500">Showing {{ outlets.data.length }} of {{ outlets.total }} outlets</p>
                    <div class="flex gap-2">
                        <Link
                            v-if="outlets.prev_page_url"
                            :href="outlets.prev_page_url"
                            class="px-3 py-1.5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-xs font-semibold hover:bg-slate-50 dark:hover:bg-slate-800 transition-all text-slate-700 dark:text-slate-300 cursor-pointer"
                        >
                            Previous
                        </Link>
                        <Link
                            v-if="outlets.next_page_url"
                            :href="outlets.next_page_url"
                            class="px-3 py-1.5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-xs font-semibold hover:bg-slate-50 dark:hover:bg-slate-800 transition-all text-slate-700 dark:text-slate-300 cursor-pointer"
                        >
                            Next
                        </Link>
                    </div>
                </div>
            </div>
        </div>

        <!-- Create/Edit Modal -->
        <div v-if="isFormModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm">
            <div class="w-full max-w-xl bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200">
                <div class="p-6 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <h3 class="text-lg font-bold text-slate-900 dark:text-slate-50">
                        {{ editingOutlet ? 'Edit Outlet' : 'Create New Outlet' }}
                    </h3>
                    <button @click="isFormModalOpen = false" class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-500 cursor-pointer">
                        <X class="h-5 w-5" />
                    </button>
                </div>

                <form @submit.prevent="submitForm" class="p-6 space-y-6">
                    <div class="space-y-4">
                        <!-- Name -->
                        <div class="space-y-1">
                            <label for="name" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Outlet Name</label>
                            <div class="relative">
                                <Store class="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
                                <input
                                    id="name"
                                    v-model="form.name"
                                    type="text"
                                    required
                                    placeholder="e.g. Outlet Senopati"
                                    class="w-full pl-10 pr-4 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all text-slate-900 dark:text-slate-100"
                                />
                            </div>
                            <p v-if="form.errors.name" class="text-xs text-rose-600 mt-1">{{ form.errors.name }}</p>
                        </div>

                        <!-- Location -->
                        <div class="space-y-1">
                            <label for="location" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Location Address</label>
                            <div class="relative">
                                <MapPin class="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
                                <input
                                    id="location"
                                    v-model="form.location"
                                    type="text"
                                    placeholder="e.g. Jalan Senopati Raya No. 12, Jakarta Selatan"
                                    class="w-full pl-10 pr-4 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all text-slate-900 dark:text-slate-100"
                                />
                            </div>
                            <p v-if="form.errors.location" class="text-xs text-rose-600 mt-1">{{ form.errors.location }}</p>
                        </div>

                        <!-- Description -->
                        <div class="space-y-1">
                            <label for="description" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Description</label>
                            <div class="relative">
                                <AlignLeft class="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
                                <textarea
                                    id="description"
                                    v-model="form.description"
                                    rows="3"
                                    placeholder="Brief details about the outlet operations..."
                                    class="w-full pl-10 pr-4 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all text-slate-900 dark:text-slate-100 resize-none"
                                />
                            </div>
                            <p v-if="form.errors.description" class="text-xs text-rose-600 mt-1">{{ form.errors.description }}</p>
                        </div>

                        <!-- User Assignment Checklist -->
                        <div class="space-y-2 border-t border-slate-100 dark:border-slate-900 pt-4">
                            <label class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400 block mb-2">Assign Staff (Kasir & Kitchen)</label>
                            
                            <div v-if="assignableUsers.length === 0" class="p-4 text-center border border-dashed border-slate-200 dark:border-slate-800 rounded-lg text-slate-400 text-xs">
                                No available staff found. Assign the 'Kasir' or 'Kitchen' role in User Management first.
                            </div>
                            
                            <div v-else class="max-h-40 overflow-y-auto space-y-2 pr-2">
                                <div 
                                    v-for="user in assignableUsers" 
                                    :key="user.id"
                                    @click="toggleUserAssignment(user.id)"
                                    :class="[
                                        'flex items-center justify-between p-3 rounded-lg border text-sm font-medium cursor-pointer transition-all',
                                        form.assigned_users.includes(user.id)
                                            ? 'border-red-500 bg-red-50/30 dark:bg-red-950/10 text-red-600 dark:text-red-400'
                                            : 'border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-900/50'
                                    ]"
                                >
                                    <div class="flex flex-col gap-0.5">
                                        <div class="flex items-center gap-2">
                                            <span>{{ user.name }}</span>
                                            <!-- Role Badge -->
                                            <span
                                                v-if="user.roles && user.roles.length > 0"
                                                :class="[
                                                    'px-1.5 py-0.5 rounded text-[9px] font-extrabold uppercase tracking-wider',
                                                    user.roles[0].name === 'Kitchen'
                                                        ? 'bg-orange-500/10 text-orange-600 dark:text-orange-400 border border-orange-500/20'
                                                        : 'bg-[#8c5a3c]/10 text-[#8c5a3c] border border-[#8c5a3c]/20'
                                                ]"
                                            >
                                                {{ user.roles[0].name }}
                                            </span>
                                        </div>
                                        <span class="text-xs text-slate-400 font-normal">
                                            {{ user.email }}
                                            <span v-if="user.outlet && (!editingOutlet || user.outlet_id !== editingOutlet.id)" class="text-amber-600 dark:text-amber-400 font-bold ml-1.5">
                                                (Assigned to: {{ user.outlet.name }})
                                            </span>
                                        </span>
                                    </div>
                                    <UserCheck 
                                        v-if="form.assigned_users.includes(user.id)"
                                        class="h-4 w-4 text-red-600 dark:text-red-400"
                                    />
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-200 dark:border-slate-800">
                        <button
                            type="button"
                            @click="isFormModalOpen = false"
                            class="px-4 py-2 border border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-sm font-semibold transition-all cursor-pointer"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            :disabled="form.processing"
                            class="px-4 py-2 bg-red-600 hover:bg-red-500 text-white rounded-lg text-sm font-semibold shadow-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 disabled:opacity-50 transition-all cursor-pointer"
                        >
                            {{ form.processing ? 'Saving...' : 'Save Changes' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Delete Confirmation Modal -->
        <div v-if="isDeleteModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm">
            <div class="w-full max-w-md bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl p-6 animate-in zoom-in-95 duration-200 space-y-6">
                <div class="flex items-center gap-3 text-rose-600 dark:text-rose-400">
                    <AlertCircle class="h-6 w-6 flex-shrink-0" />
                    <h3 class="text-lg font-bold">Delete Outlet?</h3>
                </div>

                <p class="text-sm text-slate-500 dark:text-slate-400">
                    Are you sure you want to delete outlet <span class="font-bold text-slate-900 dark:text-slate-100">"{{ outletToDelete?.name }}"</span>? This will unassign any mapped cashiers and delete outlet transaction ties. This action is irreversible.
                </p>

                <div class="flex items-center justify-end gap-3">
                    <button
                        @click="isDeleteModalOpen = false"
                        class="px-4 py-2 border border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-sm font-semibold transition-all cursor-pointer"
                    >
                        Cancel
                    </button>
                    <button
                        @click="deleteOutlet"
                        class="px-4 py-2 bg-rose-600 hover:bg-rose-500 text-white rounded-lg text-sm font-semibold transition-all cursor-pointer"
                    >
                        Confirm Delete
                    </button>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
