<script setup>
import GuestLayout from '@/Layouts/GuestLayout.vue';
import InputError from '@/Components/InputError.vue';
import InputLabel from '@/Components/InputLabel.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import TextInput from '@/Components/TextInput.vue';
import { Head, Link, useForm, usePage } from '@inertiajs/vue3';
import { ref, watch, computed, onMounted } from 'vue';
import axios from 'axios';
import debounce from 'lodash/debounce';

const page = usePage();
const features = computed(() => page.props.features || {});

const props = defineProps({
    googleLoginEnabled: {
        type: Boolean,
        default: false,
    },
    selectedPlan: {
        type: Object,
        default: null,
    },
});

// Get referral code from URL if present (?ref=XXX)
const getRefFromUrl = () => {
    const params = new URLSearchParams(window.location.search);
    return params.get('ref') || '';
};

// Get plan from URL if present (?plan=XXX)
const getPlanFromUrl = () => {
    const params = new URLSearchParams(window.location.search);
    return params.get('plan') || '';
};

const form = useForm({
    name: '',
    email: '',
    password: '',
    password_confirmation: '',
    referral_code: getRefFromUrl(),
    plan: getPlanFromUrl(),
});

// Auto-validate referral code from URL on mount
onMounted(() => {
    if (form.referral_code) {
        validateReferralCode(form.referral_code);
    }
});

// Referral code validation state
const referralValidation = ref({
    checking: false,
    valid: null,
    message: '',
});

// Check for Google OAuth errors in URL
const googleError = computed(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get('error');
});

// Format price
const formatPrice = (price) => {
    return new Intl.NumberFormat('es-ES', { 
        style: 'currency', 
        currency: 'USD',
        minimumFractionDigits: 0,
        maximumFractionDigits: 2,
    }).format(price);
};

// Debounced referral code validation
const validateReferralCode = debounce(async (code) => {
    if (!code || code.length < 3) {
        referralValidation.value = { checking: false, valid: null, message: '' };
        return;
    }

    referralValidation.value.checking = true;

    try {
        const response = await axios.post(route('referral.validate'), { code });
        referralValidation.value = {
            checking: false,
            valid: response.data.valid,
            message: response.data.message,
        };
    } catch (error) {
        referralValidation.value = {
            checking: false,
            valid: false,
            message: error.response?.data?.message || 'Código no válido',
        };
    }
}, 500);

// Watch for referral code changes
watch(() => form.referral_code, (newValue) => {
    validateReferralCode(newValue);
});

const submit = () => {
    form.post(route('register'), {
        onFinish: () => form.reset('password', 'password_confirmation'),
    });
};
</script>

<template>
    <GuestLayout>
        <Head title="Registro" />

        <div class="mb-6 text-center">
            <h2 class="text-2xl font-bold text-gray-900 dark:text-white">Crear Cuenta</h2>
            <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">Únete a nuestra plataforma y comienza a crecer</p>
        </div>

        <!-- Selected Plan Banner -->
        <div v-if="selectedPlan" class="mb-6 p-4 bg-gradient-to-r from-orange-50 to-amber-50 dark:from-orange-900/20 dark:to-amber-900/20 border border-orange-200 dark:border-orange-800 rounded-lg">
            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <div class="flex-shrink-0 p-2 bg-orange-500 rounded-lg">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" />
                        </svg>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-orange-800 dark:text-orange-200">
                            Plan seleccionado: <span class="font-bold">{{ selectedPlan.name }}</span>
                        </p>
                        <p class="text-xs text-orange-600 dark:text-orange-400">
                            <template v-if="selectedPlan.price > 0">
                                {{ formatPrice(selectedPlan.price) }} / {{ selectedPlan.duration_days }} días
                                - Completa tu registro para continuar al pago
                            </template>
                            <template v-else>
                                Gratis por {{ selectedPlan.duration_days }} días
                            </template>
                        </p>
                    </div>
                </div>
                <Link 
                    :href="route('home')"
                    class="text-xs text-orange-600 hover:text-orange-700 dark:text-orange-400 dark:hover:text-orange-300 underline"
                >
                    Cambiar plan
                </Link>
            </div>
        </div>

        <!-- Google OAuth Error Message -->
        <div v-if="googleError" class="mb-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
            <div class="flex items-center">
                <svg class="w-5 h-5 text-red-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <span class="text-sm text-red-700 dark:text-red-400">
                    {{ googleError === 'google_disabled' ? 'El registro con Google no está disponible.' : 
                       googleError === 'google_error' ? 'Error al conectar con Google. Inténtalo de nuevo.' : 
                       googleError === 'email_exists' ? 'Este correo ya está registrado. Intenta iniciar sesión.' :
                       'Ha ocurrido un error. Inténtalo de nuevo.' }}
                </span>
            </div>
        </div>

        <!-- Google Login Button -->
        <div v-if="googleLoginEnabled" class="mb-6">
            <a 
                :href="route('auth.google')"
                class="w-full inline-flex items-center justify-center px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg shadow-sm bg-white dark:bg-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#39FF14] transition-colors"
            >
                <svg class="w-5 h-5 mr-3" viewBox="0 0 24 24">
                    <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
                    <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
                    <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
                    <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
                </svg>
                Registrarse con Google
            </a>
            
            <!-- Divider -->
            <div class="relative mt-6">
                <div class="absolute inset-0 flex items-center">
                    <div class="w-full border-t border-gray-300 dark:border-gray-600"></div>
                </div>
                <div class="relative flex justify-center text-sm">
                    <span class="px-2 bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400">o con tu correo</span>
                </div>
            </div>
        </div>

        <form @submit.prevent="submit">
            <div>
                <InputLabel for="name" value="Nombre Completo" />

                <TextInput
                    id="name"
                    type="text"
                    class="mt-1 block w-full"
                    v-model="form.name"
                    required
                    autofocus
                    autocomplete="name"
                    placeholder="Juan Pérez"
                />

                <InputError class="mt-2" :message="form.errors.name" />
            </div>

            <div class="mt-4">
                <InputLabel for="email" value="Correo Electrónico" />

                <TextInput
                    id="email"
                    type="email"
                    class="mt-1 block w-full"
                    v-model="form.email"
                    required
                    autocomplete="username"
                    placeholder="tu@email.com"
                />

                <InputError class="mt-2" :message="form.errors.email" />
            </div>

            <div class="mt-4">
                <InputLabel for="password" value="Contraseña" />

                <TextInput
                    id="password"
                    type="password"
                    class="mt-1 block w-full"
                    v-model="form.password"
                    required
                    autocomplete="new-password"
                    placeholder="Mínimo 8 caracteres"
                />

                <InputError class="mt-2" :message="form.errors.password" />
            </div>

            <div class="mt-4">
                <InputLabel
                    for="password_confirmation"
                    value="Confirmar Contraseña"
                />

                <TextInput
                    id="password_confirmation"
                    type="password"
                    class="mt-1 block w-full"
                    v-model="form.password_confirmation"
                    required
                    autocomplete="new-password"
                    placeholder="Repite tu contraseña"
                />

                <InputError
                    class="mt-2"
                    :message="form.errors.password_confirmation"
                />
            </div>

            <div v-if="features.feature_referrals" class="mt-4">
                <InputLabel for="referral_code" value="Código de Referido (Opcional)" />

                <div class="relative">
                    <TextInput
                        id="referral_code"
                        type="text"
                        class="mt-1 block w-full pr-10"
                        :class="{
                            'border-green-500 focus:border-green-500 focus:ring-green-500': referralValidation.valid === true,
                            'border-red-500 focus:border-red-500 focus:ring-red-500': referralValidation.valid === false,
                        }"
                        v-model="form.referral_code"
                        placeholder="Ingresa el código si tienes uno"
                        @input="form.referral_code = form.referral_code.toUpperCase()"
                    />
                    
                    <!-- Validation indicator -->
                    <div class="absolute inset-y-0 right-0 flex items-center pr-3 mt-1">
                        <!-- Loading spinner -->
                        <svg v-if="referralValidation.checking" class="w-5 h-5 text-gray-400 animate-spin" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        <!-- Valid checkmark -->
                        <svg v-else-if="referralValidation.valid === true" class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                        </svg>
                        <!-- Invalid X -->
                        <svg v-else-if="referralValidation.valid === false" class="w-5 h-5 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </div>
                </div>

                <!-- Validation message -->
                <p v-if="referralValidation.message" 
                   class="mt-1 text-sm"
                   :class="referralValidation.valid ? 'text-green-600' : 'text-red-600'">
                    {{ referralValidation.message }}
                </p>

                <InputError class="mt-2" :message="form.errors.referral_code" />
            </div>

            <div class="mt-6">
                <PrimaryButton
                    class="w-full justify-center py-3 bg-gradient-to-r from-[#39FF14] to-[#00D4FF] hover:from-[#32e012] hover:to-[#00b8d4] text-black font-bold"
                    :class="{ 'opacity-25': form.processing }"
                    :disabled="form.processing"
                >
                    Crear Cuenta
                </PrimaryButton>
            </div>

            <div class="mt-6 text-center">
                <p class="text-sm text-gray-600 dark:text-gray-400">
                    ¿Ya tienes una cuenta?
                    <Link :href="route('login')" class="font-medium text-[#39FF14] hover:text-[#32e012]">
                        Inicia sesión
                    </Link>
                </p>
            </div>
        </form>
    </GuestLayout>
</template>
