<script setup lang="ts">
import { ref, watch } from 'vue';
import { Head, useForm, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Search, Users, Plus, Edit2, Trash2, Award, Mail, Phone, Calendar, X } from 'lucide-vue-next';

interface CustomerData {
    id: number;
    name: string;
    phone: string | null;
    email: string | null;
    is_member: boolean;
    loyalty_points: number;
    created_at: string;
}

interface PaginatedCustomers {
    data: CustomerData[];
    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<{
    customers: PaginatedCustomers;
    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('customers.index'),
            { search: search.value },
            { preserveState: true, replace: true }
        );
    }, 400);
});

// Modal state
const isFormModalOpen = ref(false);
const editingCustomer = ref<CustomerData | null>(null);

// Form config
const form = useForm({
    name: '',
    phone: '',
    email: '',
    is_member: false,
    loyalty_points: 0,
});

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

const openEditModal = (customer: CustomerData) => {
    editingCustomer.value = customer;
    form.clearErrors();
    form.name = customer.name;
    form.phone = customer.phone || '';
    form.email = customer.email || '';
    form.is_member = customer.is_member;
    form.loyalty_points = customer.loyalty_points;
    isFormModalOpen.value = true;
};

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

const deleteCustomer = (customer: CustomerData) => {
    if (confirm(`Apakah Anda yakin ingin menghapus pelanggan ${customer.name}?`)) {
        router.delete(route('customers.destroy', customer.id));
    }
};
</script>

<template>
    <Head title="Pelanggan & Membership" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header section -->
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                    <h1 class="text-2xl font-extrabold text-slate-900 dark:text-slate-55 tracking-tight">
                        CRM & Membership
                    </h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Kelola data loyalty program, poin member, dan basis data customer walk-in.
                    </p>
                </div>
                <button
                    @click="openCreateModal"
                    class="flex items-center justify-center gap-2 px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-sm font-bold rounded-xl transition-all cursor-pointer shadow-lg shadow-[#8c5a3c]/10"
                >
                    <Plus class="h-4 w-4" />
                    Tambah Pelanggan
                </button>
            </div>

            <!-- Controls row -->
            <div class="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl px-5 py-4 shadow-sm">
                <!-- Search bar -->
                <div class="relative flex-1 max-w-md">
                    <Search class="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
                    <input
                        type="text"
                        v-model="search"
                        placeholder="Cari nama, nomor HP, email..."
                        class="w-full h-9 pl-9 pr-4 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c] text-slate-900 dark:text-slate-100"
                    />
                </div>
            </div>

            <!-- Customers Table -->
            <div v-if="customers.data.length > 0" class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="border-b border-slate-105 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/50">
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Nama Pelanggan</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Kontak</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Status Member</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Poin Loyalty</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Tgl Terdaftar</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider text-right">Aksi</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                            <tr v-for="cust in customers.data" :key="cust.id" class="hover:bg-slate-50/30 dark:hover:bg-slate-800/10">
                                <td class="px-6 py-4">
                                    <div class="flex items-center gap-3">
                                        <div class="h-8 w-8 rounded-full bg-[#8c5a3c]/10 text-[#8c5a3c] flex items-center justify-center font-bold text-xs uppercase">
                                            {{ cust.name.slice(0, 2) }}
                                        </div>
                                        <span class="font-extrabold text-xs text-slate-850 dark:text-slate-100">{{ cust.name }}</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="flex flex-col gap-1 text-[11px] text-slate-500">
                                        <span v-if="cust.phone" class="flex items-center gap-1.5"><Phone class="h-3.5 w-3.5 text-slate-400" /> {{ cust.phone }}</span>
                                        <span v-if="cust.email" class="flex items-center gap-1.5"><Mail class="h-3.5 w-3.5 text-slate-400" /> {{ cust.email }}</span>
                                        <span v-if="!cust.phone && !cust.email" class="text-slate-400 italic">Tidak ada kontak</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <span v-if="cust.is_member" class="px-2.5 py-0.5 border border-[#8c5a3c]/20 bg-[#8c5a3c]/10 text-[#8c5a3c] rounded-full text-[9px] font-extrabold uppercase tracking-wider">
                                        Member
                                    </span>
                                    <span v-else class="px-2.5 py-0.5 border border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-800 text-slate-400 rounded-full text-[9px] font-bold uppercase tracking-wider">
                                        Walk-In
                                    </span>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="flex items-center gap-1.5">
                                        <Award class="h-4 w-4 text-amber-500" />
                                        <span class="font-bold text-xs text-slate-800 dark:text-slate-200">{{ cust.loyalty_points }} pts</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-[11px] text-slate-400">
                                    <span class="flex items-center gap-1.5"><Calendar class="h-3.5 w-3.5" /> {{ new Date(cust.created_at).toLocaleDateString('id-ID') }}</span>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <div class="flex items-center justify-end gap-2">
                                        <button
                                            @click="openEditModal(cust)"
                                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-500 hover:text-slate-800 dark:hover:text-slate-200 rounded-lg cursor-pointer"
                                        >
                                            <Edit2 class="h-3.5 w-3.5" />
                                        </button>
                                        <button
                                            v-if="cust.id !== 1"
                                            @click="deleteCustomer(cust)"
                                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-500 hover:text-rose-600 rounded-lg cursor-pointer"
                                        >
                                            <Trash2 class="h-3.5 w-3.5" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Simple Pagination -->
                <div v-if="customers.last_page > 1" class="px-6 py-4 border-t border-slate-100 dark:border-slate-800 flex items-center justify-between gap-4">
                    <span class="text-xs text-slate-500">Total {{ customers.total }} pelanggan</span>
                    <div class="flex items-center gap-2">
                        <Link
                            v-for="link in customers.links"
                            :key="link.label"
                            :href="link.url || '#'"
                            :class="[
                                'px-3 py-1.5 border rounded-lg text-xs font-semibold cursor-pointer',
                                link.active ? 'bg-[#8c5a3c] text-white border-[#8c5a3c]' : 'border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-350',
                                !link.url ? 'opacity-50 pointer-events-none' : ''
                            ]"
                            v-html="link.label"
                        />
                    </div>
                </div>
            </div>
            <div v-else class="text-center py-16 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm">
                <Users class="h-10 w-10 text-slate-355 dark:text-slate-600 mx-auto mb-3" />
                <h3 class="text-sm font-bold text-slate-800 dark:text-slate-200">Belum ada data customer</h3>
                <p class="text-xs text-slate-400 mt-1">Gunakan tombol di atas untuk mendaftarkan pelanggan pertama.</p>
            </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="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-md overflow-hidden transform transition-all">
                    <!-- Modal Header -->
                    <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                        <h3 class="text-sm font-extrabold text-slate-900 dark:text-slate-100">
                            {{ editingCustomer ? 'Edit Data Pelanggan' : 'Daftar Pelanggan Baru' }}
                        </h3>
                        <button @click="isFormModalOpen = false" class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-400 cursor-pointer">
                            <X class="h-4 w-4" />
                        </button>
                    </div>

                    <!-- Modal Body -->
                    <form @submit.prevent="submitForm" class="p-6 space-y-4">
                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Nama Lengkap</label>
                            <input
                                type="text"
                                v-model="form.name"
                                required
                                placeholder="Masukkan nama pelanggan..."
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c]"
                            />
                        </div>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Nomor HP / Whatsapp</label>
                            <input
                                type="text"
                                v-model="form.phone"
                                placeholder="Contoh: 081234567xxx"
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c]"
                            />
                        </div>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Email</label>
                            <input
                                type="email"
                                v-model="form.email"
                                placeholder="Contoh: nama@domain.com"
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c]"
                            />
                        </div>

                        <div class="flex items-center justify-between border-y border-slate-100 dark:border-slate-800 py-3.5">
                            <div>
                                <span class="block text-xs font-extrabold text-slate-800 dark:text-slate-200">Gabung Membership</span>
                                <span class="block text-[10px] text-slate-450 mt-0.5">Aktifkan untuk mengumpulkan poin belanja.</span>
                            </div>
                            <input
                                type="checkbox"
                                v-model="form.is_member"
                                class="h-4.5 w-4.5 accent-[#8c5a3c] rounded border-slate-300 cursor-pointer"
                            />
                        </div>

                        <div v-if="form.is_member">
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Poin Loyalty Awal</label>
                            <input
                                type="number"
                                v-model="form.loyalty_points"
                                min="0"
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c]"
                            />
                        </div>

                        <!-- Modal Actions Footer -->
                        <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-100 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-350 text-xs font-bold rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 cursor-pointer"
                            >
                                Batal
                            </button>
                            <button
                                type="submit"
                                :disabled="form.processing"
                                class="px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer disabled:opacity-50"
                            >
                                {{ form.processing ? 'Menyimpan...' : 'Simpan' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
