<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { usePageTitle } from '../composables/Core/usePageTitle';

const props = defineProps({ payload: String, target: String });

usePageTitle('Join Chapter');

const goToLogin = () => { window.location.href = '/login'; };

const chapter = ref(null);
const cooperative = ref(null);
const chapterHash = ref(null);
const loading = ref(true);
const errorMessage = ref('');
const fieldErrors = ref({});
const submitting = ref(false);
const done = ref(false);

const form = ref({ name: '', username: '', mobile_number: '', password: '' });

const mobileError = ref('');
const validateMobile = (val) => {
    if (!val) { mobileError.value = 'Mobile number is required.'; return false; }
    if (!/^(09|\+639)\d{9}$/.test(val)) {
        mobileError.value = 'Must be a valid Philippine mobile number (e.g. 09XXXXXXXXX).';
        return false;
    }
    mobileError.value = '';
    return true;
};

const decodePayload = () => {
    const raw = props.payload || props.target;
    if (!raw) return null;
    try {
        return JSON.parse(atob(raw));
    } catch (e) {
        return null;
    }
};

const fetchChapter = async () => {
    const decoded = decodePayload();
    if (!decoded?.chapter_hash) {
        errorMessage.value = 'Invalid or missing registration link.';
        loading.value = false;
        return;
    }
    chapterHash.value = decoded.chapter_hash;
    try {
        const res = await axios.get(`/api/public/chapter/${decoded.chapter_hash}`);
        if (res.data.success) {
            chapter.value = res.data.chapter;
            cooperative.value = res.data.cooperative;
        } else {
            errorMessage.value = res.data.message || 'Chapter not found.';
        }
    } catch (err) {
        errorMessage.value = err.response?.status === 404
            ? 'Chapter not found. Please check the link.'
            : 'Failed to load chapter information.';
    } finally {
        loading.value = false;
    }
};

const submit = async () => {
    if (submitting.value) return;
    if (!validateMobile(form.value.mobile_number)) return;
    fieldErrors.value = {};
    errorMessage.value = '';
    submitting.value = true;
    try {
        const res = await axios.post('/api/public/chapter/register', {
            ...form.value,
            chapter_hash: chapterHash.value,
        });
        if (res.data.success) {
            done.value = true;
        } else {
            errorMessage.value = res.data.message || 'Registration failed.';
        }
    } catch (err) {
        if (err.response?.data?.errors) fieldErrors.value = err.response.data.errors;
        else errorMessage.value = err.response?.data?.message || 'An error occurred.';
    } finally {
        submitting.value = false;
    }
};

onMounted(fetchChapter);
</script>

<template>
    <div class="container py-4" style="max-width: 560px;">
        <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status"></div>
        </div>

        <div v-else-if="!chapter && errorMessage" class="text-center py-5">
            <i class="fas fa-exclamation-triangle fa-3x text-danger mb-3"></i>
            <p class="text-danger fw-semibold">{{ errorMessage }}</p>
        </div>

        <template v-else-if="chapter">
            <!-- Header -->
            <div class="text-center mb-4">
                <div class="brand-circle rounded-circle d-inline-flex align-items-center justify-content-center mb-2">
                    <i class="fas fa-sitemap fa-lg"></i>
                </div>
                <h5 class="fw-bold mb-0">{{ chapter.name }}</h5>
                <span class="badge rounded-pill level-badge px-3 mt-1 small">{{ (chapter.level || '').toUpperCase() }}</span>
                <p v-if="cooperative?.name" class="text-muted small mt-2 mb-0">
                    <i class="fas fa-handshake me-1"></i>{{ cooperative.name }}
                </p>
            </div>

            <!-- Done -->
            <div v-if="done" class="text-center py-4">
                <i class="fas fa-check-circle fa-4x text-success mb-3"></i>
                <h5 class="fw-bold">Welcome!</h5>
                <p class="text-muted">
                    Welcome to <strong>{{ cooperative?.name || 'the cooperative' }}</strong> —
                    <strong>{{ chapter.name }}</strong>! Your account has been created. Please log in.
                </p>
                <button class="btn btn-primary rounded-pill px-4 mt-2" @click="goToLogin">
                    <i class="fas fa-sign-in-alt me-2"></i> Go to Login
                </button>
            </div>

            <!-- Form -->
            <div v-else class="form-card rounded-4 p-4">
                <h6 class="fw-semibold mb-3">Create your account</h6>
                <div v-if="errorMessage" class="alert alert-danger rounded-3 small py-2">{{ errorMessage }}</div>

                <div class="mb-3">
                    <label class="form-label small fw-semibold">Full Name</label>
                    <input v-model="form.name" type="text" class="form-control rounded-pill"
                        :class="{ 'is-invalid': fieldErrors.name }" placeholder="Juan Dela Cruz" />
                    <div v-if="fieldErrors.name" class="invalid-feedback">{{ fieldErrors.name[0] }}</div>
                </div>

                <div class="mb-3">
                    <label class="form-label small fw-semibold">Username</label>
                    <input v-model="form.username" type="text" class="form-control rounded-pill"
                        :class="{ 'is-invalid': fieldErrors.username }" placeholder="juandelacruz" autocomplete="username" />
                    <div v-if="fieldErrors.username" class="invalid-feedback">{{ fieldErrors.username[0] }}</div>
                </div>

                <div class="mb-3">
                    <label class="form-label small fw-semibold">Mobile Number</label>
                    <input v-model="form.mobile_number" type="tel" class="form-control rounded-pill"
                        :class="{ 'is-invalid': mobileError || fieldErrors.mobile_number }"
                        placeholder="09XXXXXXXXX" @blur="validateMobile(form.mobile_number)" />
                    <div class="invalid-feedback">{{ mobileError || fieldErrors.mobile_number?.[0] }}</div>
                </div>

                <div class="mb-4">
                    <label class="form-label small fw-semibold">Password</label>
                    <input v-model="form.password" type="password" class="form-control rounded-pill"
                        :class="{ 'is-invalid': fieldErrors.password }" placeholder="Min. 6 characters" autocomplete="new-password" />
                    <div v-if="fieldErrors.password" class="invalid-feedback">{{ fieldErrors.password[0] }}</div>
                </div>

                <button class="btn btn-primary rounded-pill w-100 py-2 fw-semibold" :disabled="submitting" @click="submit">
                    <span v-if="submitting" class="spinner-border spinner-border-sm me-2"></span>
                    <i v-else class="fas fa-user-plus me-2"></i>
                    {{ submitting ? 'Creating account...' : 'Join Chapter' }}
                </button>
                <div class="text-center mt-3">
                    <small class="text-muted">Already have an account?
                        <a href="#" @click.prevent="goToLogin" class="fw-semibold" style="color: var(--accent-color);">Log in</a>
                    </small>
                </div>
            </div>
        </template>
    </div>
</template>

<style scoped>
.brand-circle {
    width: 56px;
    height: 56px;
    background: var(--accent-color);
    color: #fff;
}
.level-badge {
    background: var(--accent-color);
    color: #fff;
}
.form-card {
    background: var(--bg-card);
    color: var(--text-primary);
    border: 1px solid rgba(0, 0, 0, 0.06);
}
:global(.dark-mode) .form-card {
    border-color: rgba(255, 255, 255, 0.08);
}
</style>
