<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useNavigate } from '../composables/Core/useNavigate'
import { useModal } from '../composables/Core/useModal'
import { usePageTitle } from '../composables/Core/usePageTitle'
import BackButton from '../Components/Core/BackButton.vue'
import LoadingSpinner from '../Components/LoadingSpinner.vue'

const { navigate } = useNavigate()
const modal = useModal()
usePageTitle('Batch Add Users')

const users = ref([
    { username: '', name: '', mobile_number: '', password: 'Password123!', type: 'user', parent_hash: '' }
])

const loading = ref(false)
const saving = ref(false)
const userTypes = ref([])
const parents = ref([])

const addRow = () => {
    users.value.push({ username: '', name: '', mobile_number: '', password: 'Password123!', type: 'user', parent_hash: '' })
}

const removeRow = (index) => {
    if (users.value.length > 1) {
        users.value.splice(index, 1)
    }
}

const fetchData = async () => {
    try {
        const [typeRes, parentRes] = await Promise.all([
            axios.post('/admin/list/usertype/create'),
            axios.post('/admin/user/list/numbers/hash')
        ])

        if (typeRes.data) userTypes.value = typeRes.data
        if (parentRes.data) parents.value = parentRes.data
    } catch (err) {
        console.error('Error fetching user metadata:', err)
    }
}

const saveUsers = async () => {
    const invalid = users.value.some(u => !u.username || !u.name || !u.mobile_number || !u.password || !u.type)
    if (invalid) {
        modal.open({
            title: 'Validation Error',
            body: 'Please fill in all required fields (Username, Name, Mobile, Password, Type) for all rows.'
        })
        return
    }

    saving.value = true
    try {
        const response = await axios.post('/admin/batch/users', { users: users.value })
        if (response.data && response.data.success) {
            modal.open({
                title: 'Success',
                body: `Successfully added ${response.data.count} users.`,
                onClose: () => navigate({ page: 'UserList' })
            })
        }
    } catch (err) {
        console.error('Error saving batch users:', err)
        const errorMessage = err.response?.data?.errors
            ? err.response.data.errors.join('<br>')
            : (err.response?.data?.message || 'Failed to save users.')

        modal.open({
            title: 'Error',
            body: errorMessage
        })
    } finally {
        saving.value = false
    }
}

onMounted(() => {
    fetchData()
})
</script>

<template>
    <div class="batch-add-page pb-5">
        <div class="tf-container mt-4">
            <div class="mb-3">
                <BackButton to="UserList" />
            </div>

            <div class="mb-4">
                <h3 class="fw_6 mb-1">Batch Add Users</h3>
                <p class="text-muted small mb-0">Efficiently register multiple accounts. All passwords default to "Password123!" if not changed.</p>
            </div>

            <div class="d-grid mb-3">
                <button @click="addRow" class="btn btn-outline-primary rounded-pill">
                    <i class="fas fa-plus-circle me-2"></i> Add User
                </button>
            </div>

            <div class="row g-4">
                <div v-for="(user, index) in users" :key="index" class="col-md-6 col-lg-4">
                    <div class="leaf-card p-3 bg-white rounded-3 border position-relative h-100">
                        <div class="d-flex justify-content-between align-items-center mb-3 pb-2 border-bottom">
                            <span class="badge bg-primary rounded-pill">#{{ index + 1 }}</span>
                            <button @click="removeRow(index)" class="btn btn-link text-danger p-0 border-0"
                                :disabled="users.length <= 1"><i class="fas fa-times-circle"></i></button>
                        </div>

                        <div class="row g-2 mb-2">
                            <div class="col-6">
                                <label class="form-label small fw-bold text-muted mb-1">Username *</label>
                                <input v-model="user.username" type="text" class="form-control form-control-sm" placeholder="Unique username">
                            </div>
                            <div class="col-6">
                                <label class="form-label small fw-bold text-muted mb-1">Full Name *</label>
                                <input v-model="user.name" type="text" class="form-control form-control-sm" placeholder="User's full name">
                            </div>
                        </div>

                        <div class="row g-2 mb-2">
                            <div class="col-6">
                                <label class="form-label small fw-bold text-muted mb-1">Mobile *</label>
                                <input v-model="user.mobile_number" type="text" class="form-control form-control-sm" placeholder="09xxxxxxxxx">
                            </div>
                            <div class="col-6">
                                <label class="form-label small fw-bold text-muted mb-1">Password *</label>
                                <input v-model="user.password" type="text" class="form-control form-control-sm" placeholder="Password">
                            </div>
                        </div>

                        <div class="mb-2">
                            <label class="form-label small fw-bold text-muted mb-1">Account Type</label>
                            <select v-model="user.type" class="form-select form-select-sm">
                                <option v-for="type in userTypes" :key="type[0]" :value="type[0]">{{ type[1] }}</option>
                            </select>
                        </div>

                        <div class="mb-2">
                            <label class="form-label small fw-bold text-muted mb-1">Parent Account</label>
                            <select v-model="user.parent_hash" class="form-select form-select-sm">
                                <option value="">System Default (Self)</option>
                                <option v-for="p in parents" :key="p.hashkey" :value="p.hashkey">{{ p.name }} ({{ p.username }})</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <div class="d-grid mt-4">
                <button @click="addRow" class="btn btn-outline-primary rounded-pill px-4 fw-semibold">
                    <i class="fas fa-plus-circle me-2"></i> Add Another User
                </button>
            </div>

            <div class="d-grid mt-3 pt-3 border-top">
                <button @click="saveUsers" :disabled="saving" class="btn btn-primary rounded-pill px-4 fw-semibold">
                    <i class="fas fa-save me-2"></i>
                    {{ saving ? 'Saving...' : 'Save All Users' }}
                </button>
            </div>
        </div>
    </div>
</template>

<style scoped>
.batch-add-page {
    background: var(--bg-primary);
    min-height: 100vh;
}
.leaf-card { transition: box-shadow 0.15s ease, transform 0.15s ease; }
.leaf-card:hover { box-shadow: 0 4px 12px rgba(13,110,253,0.08); transform: translateY(-2px); }
:global(.dark-mode) .leaf-card { background-color: var(--bg-secondary) !important; border-color: var(--border-color) !important; }
:global(.dark-mode) .form-control, :global(.dark-mode) .form-select {
    background-color: var(--bg-secondary) !important;
    color: var(--text-primary);
    border-color: var(--border-color);
}
</style>
