import { Form, Head } from '@inertiajs/react';
import { useState, useRef } from 'react';
import { Camera, User } from 'lucide-react';

import InputError from '@/components/input-error';
import TextLink from '@/components/text-link';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import AuthLayout from '@/layouts/auth-layout';
import { login } from '@/routes';
import { store } from '@/routes/register';
import { SocialLoginSection } from '@/components/auth/social-login';

export default function Register() {
    return (
        <AuthLayout
            title="Crear una cuenta"
            description="Ingresa tus datos para registrarte en Ser Ajayu"
        >
            <Head title="Registrarse" />
            <Form
                {...store.form()}
                resetOnSuccess={['password', 'password_confirmation']}
                disableWhileProcessing
                className="flex flex-col gap-6"
            >
                {({ processing, errors, setData, data, clearErrors, setError }: any) => {
                    const [preview, setPreview] = useState<string | null>(null);
                    const fileInputRef = useRef<HTMLInputElement>(null);

                    const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
                        const file = e.target.files?.[0];
                        clearErrors('avatar');
                        
                        if (file) {
                            if (file.size > 2 * 1024 * 1024) {
                                setError('avatar', 'La imagen no debe pesar más de 2MB.');
                                e.target.value = '';
                                return;
                            }
                            
                            setData('avatar', file);
                            setPreview(URL.createObjectURL(file));
                        }
                    };

                    const triggerFileInput = () => {
                        fileInputRef.current?.click();
                    };

                    return (
                        <>
                            <div className="grid gap-5">
                                {/* Avatar Upload */}
                                <div className="flex flex-col items-center gap-2 mb-2">
                                    <div className="relative group cursor-pointer" onClick={triggerFileInput}>
                                        <Avatar className="h-24 w-24 border-2 border-border group-hover:border-forest transition-colors">
                                            <AvatarImage src={preview || ''} className="object-cover" />
                                            <AvatarFallback className="bg-muted text-muted-foreground">
                                                <User className="h-10 w-10" />
                                            </AvatarFallback>
                                        </Avatar>
                                        <div className="absolute inset-0 flex items-center justify-center bg-black/40 rounded-full opacity-0 group-hover:opacity-100 transition-opacity">
                                            <Camera className="h-8 w-8 text-white" />
                                        </div>
                                        <input
                                            type="file"
                                            ref={fileInputRef}
                                            className="hidden"
                                            accept="image/png, image/jpeg, image/jpg, image/webp"
                                            onChange={handleAvatarChange}
                                        />
                                    </div>
                                    <span className="text-sm text-muted-foreground cursor-pointer hover:text-forest" onClick={triggerFileInput}>
                                        {preview ? 'Cambiar foto' : 'Agregar foto de perfil'}
                                    </span>
                                    <InputError message={errors.avatar} />
                                </div>

                                {/* Name */}
                                <div className="grid gap-2">
                                    <Label htmlFor="name">Nombre completo *</Label>
                                    <Input
                                        id="name"
                                        type="text"
                                        required
                                        autoFocus
                                        tabIndex={1}
                                        autoComplete="name"
                                        name="name"
                                        placeholder="Tu nombre completo"
                                    />
                                    <InputError message={errors.name} />
                                </div>

                                {/* Email */}
                                <div className="grid gap-2">
                                    <Label htmlFor="email">Correo electrónico *</Label>
                                    <Input
                                        id="email"
                                        type="email"
                                        required
                                        tabIndex={2}
                                        autoComplete="email"
                                        name="email"
                                        placeholder="correo@ejemplo.com"
                                    />
                                    <InputError message={errors.email} />
                                </div>

                                {/* Age and Gender Row */}
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="grid gap-2">
                                        <Label htmlFor="age">Edad</Label>
                                        <Input
                                            id="age"
                                            type="number"
                                            min={18}
                                            max={120}
                                            tabIndex={3}
                                            name="age"
                                            placeholder="25"
                                        />
                                        <InputError message={errors.age} />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="gender">Género</Label>
                                        <Select name="gender">
                                            <SelectTrigger tabIndex={4}>
                                                <SelectValue placeholder="Seleccionar" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="male">Masculino</SelectItem>
                                                <SelectItem value="female">Femenino</SelectItem>
                                                <SelectItem value="other">Otro</SelectItem>
                                                <SelectItem value="prefer_not_to_say">Prefiero no decir</SelectItem>
                                            </SelectContent>
                                        </Select>
                                        <InputError message={errors.gender} />
                                    </div>
                                </div>

                                {/* Country */}
                                <div className="grid gap-2">
                                    <Label htmlFor="country">País de residencia</Label>
                                    <Input
                                        id="country"
                                        type="text"
                                        tabIndex={5}
                                        name="country"
                                        placeholder="Bolivia, Perú, Ecuador..."
                                    />
                                    <InputError message={errors.country} />
                                </div>

                                {/* Entheogen Activity */}
                                <div className="grid gap-2">
                                    <Label htmlFor="entheogen_activity">
                                        Actividad relacionada con enteógenos
                                    </Label>
                                    <Textarea
                                        id="entheogen_activity"
                                        tabIndex={6}
                                        name="entheogen_activity"
                                        placeholder="Describe brevemente tu experiencia o interés con prácticas enteógenas (ej: investigación, ceremonia, terapia, etc.)"
                                        className="min-h-[80px] resize-none"
                                    />
                                    <InputError message={errors.entheogen_activity} />
                                    <p className="text-xs text-muted-foreground">
                                        Esta información es opcional y confidencial.
                                    </p>
                                </div>

                                {/* Password */}
                                <div className="grid gap-2">
                                    <Label htmlFor="password">Contraseña *</Label>
                                    <PasswordInput
                                        id="password"
                                        required
                                        tabIndex={7}
                                        autoComplete="new-password"
                                        name="password"
                                        placeholder="Mínimo 8 caracteres"
                                    />
                                    <InputError message={errors.password} />
                                </div>

                                {/* Confirm Password */}
                                <div className="grid gap-2">
                                    <Label htmlFor="password_confirmation">
                                        Confirmar contraseña *
                                    </Label>
                                    <PasswordInput
                                        id="password_confirmation"
                                        required
                                        tabIndex={8}
                                        autoComplete="new-password"
                                        name="password_confirmation"
                                        placeholder="Repite tu contraseña"
                                    />
                                    <InputError message={errors.password_confirmation} />
                                </div>

                                <Button
                                    type="submit"
                                    className="mt-2 w-full bg-forest hover:bg-forest-light"
                                    tabIndex={9}
                                    data-test="register-user-button"
                                >
                                    {processing && <Spinner />}
                                    Crear cuenta
                                </Button>
                            </div>

                            {/* Social Login */}
                            <SocialLoginSection providers={['google']} />

                            <div className="text-center text-sm text-muted-foreground">
                                ¿Ya tienes una cuenta?{' '}
                                <TextLink href={login()} tabIndex={10}>
                                    Iniciar sesión
                                </TextLink>
                            </div>
                        </>
                    );
                }}
            </Form>
        </AuthLayout>
    );
}
