<template>
    <mainLayout>
        <!-- Modal Create/Edit Akun -->
        <CreateAkun
            v-if="creatingAkun"
            :isOpen="creatingAkun"
            :akun="detail"
            @close="closeAkun"
        />

        <EditAkun
            v-if="editingAkun"
            :isOpen="editingAkun"
            :akun="detail"
            @close="closeEditAkun"
        />

        <!-- Modal Delete -->
        <ConfirmDeleteModal
            :isOpen="confirmDeleteOpen"
            title="Hapus User"
            message="Apakah Anda yakin ingin menghapus user ini?"
            @confirm="confirmDelete"
            @cancel="closeDeleteModal"
        />

        <div class="p-6 min-h-[75vh]">
            <!-- Header Section -->
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-2xl font-bold text-D">Manajemen Akun</h1>
                <button
                    @click="tambahAkun"
                    class="px-4 py-2 bg-C text-D rounded-md hover:bg-C/80 transition duration-200 flex items-center gap-2"
                >
                    <svg
                        class="w-4 h-4"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                    >
                        <path
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M12 4v16m8-8H4"
                        />
                    </svg>
                    Tambah User
                </button>
            </div>

            <!-- Table Section -->
            <div
                class="bg-white rounded-lg shadow-md border border-D overflow-hidden"
            >
                <table class="w-full">
                    <thead>
                        <tr class="bg-C text-white">
                            <th class="px-6 py-4 text-center text-D border-r border-D">No</th>
                            <th class="px-6 py-4 text-center text-D border-r border-D">Nama</th>
                            <th class="px-6 py-4 text-center text-D border-r border-D">Peran</th>
                            <th class="px-6 py-4 text-center text-D">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="(item, index) in akun"
                            :key="item.id"
                            class="border-b border-D hover:bg-gray-50 transition duration-150"
                            :class="{ 'bg-gray-50': index % 2 === 1 }"
                        >
                            <td class="px-6 py-4 border-r border-D text-center font-medium text-gray-900">
                                {{ index + 1 }}
                            </td>
                            <td class="px-6 py-4 border-r border-D text-D">
                                {{ item.nama }}
                            </td>
                            <td class="px-6 py-4 border-r border-D text-gray-800">
                                {{ item.role }}
                            </td>
                            <td class="px-6 py-4 text-center">
                                <div class="flex justify-center gap-2">
                                    <button
                                        @click="ubahAkun(item)"
                                        class="px-3 py-1 bg-yellow-500 text-white text-sm rounded hover:bg-yellow-600 transition duration-200"
                                    >
                                        Ubah
                                    </button>
                                    <button
                                        @click="hapusAkun(item)"
                                        class="px-3 py-1 bg-red-500 text-white text-sm rounded hover:bg-red-600 transition duration-200"
                                    >
                                        Hapus
                                    </button>
                                </div>
                            </td>
                        </tr>

                        <!-- Empty State -->
                        <tr v-if="akun.length === 0 && !loading">
                            <td colspan="5" class="px-6 py-8 text-center text-gray-500">
                                <div class="flex flex-col items-center">
                                    <svg
                                        class="w-12 h-12 text-gray-400 mb-2"
                                        fill="none"
                                        stroke="currentColor"
                                        viewBox="0 0 24 24"
                                    >
                                        <path
                                            stroke-linecap="round"
                                            stroke-linejoin="round"
                                            stroke-width="2"
                                            d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2 2v-5m16 0h-2M4 13h2"
                                        />
                                    </svg>
                                    <p>Tidak ada data user</p>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Loading State -->
            <div v-if="loading" class="flex justify-center items-center py-8">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-[#c6a77d]"></div>
                <span class="ml-2 text-gray-600">Memuat data...</span>
            </div>
        </div>
    </mainLayout>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import mainLayout from "../layouts/mainLayout.vue";
import ConfirmDeleteModal from "../components/ConfirmDeleteModal.vue";
import CreateAkun from "../components/CreateAkun.vue";
import EditAkun from "../components/EditAkun.vue";

// State
const akun = ref([]);
const loading = ref(false);
const creatingAkun = ref(false);
const detail = ref(null);
const editingAkun = ref(false);
const confirmDeleteOpen = ref(false);
const akunToDelete = ref(null);

// Fetch data dari API
const fetchAkun = async () => {
    loading.value = true;
    try {
        const response = await axios.get("/api/user", {
            headers: {
                Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
        });
        akun.value = response.data;
    } catch (error) {
        console.error("Error fetching akun:", error);
    } finally {
        loading.value = false;
    }
};

// Tambah
const tambahAkun = () => {
    detail.value = null;
    creatingAkun.value = true;
};

// Ubah
const ubahAkun = (item) => {
    detail.value = item;
    editingAkun.value = true;
};

// Hapus
const hapusAkun = (item) => {
    akunToDelete.value = item;
    confirmDeleteOpen.value = true;
};

const confirmDelete = async () => {
    try {
        await axios.delete(`/api/user/${akunToDelete.value.id}`, {
            headers: {
                Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
        });
        fetchAkun();
        confirmDeleteOpen.value = false;
    } catch (error) {
        console.error("Error deleting akun:", error);
    }
};

const closeDeleteModal = () => {
    confirmDeleteOpen.value = false;
    akunToDelete.value = null;
};

// Tutup modal Create/Edit
const closeAkun = () => {
    creatingAkun.value = false;
    fetchAkun();
};

const closeEditAkun = () => {
    editingAkun.value = false;
    fetchAkun();
};

// Lifecycle
onMounted(() => {
    fetchAkun();
});
</script>
