import { Transition } from '@headlessui/react';
import { Form, Head, Link, usePage, useForm, router } from '@inertiajs/react';
import { useRef, useState, useEffect } from 'react';
import { Camera, Trash2, User } from 'lucide-react';

import ProfileController from '@/actions/App/Http/Controllers/Settings/ProfileController';
import DeleteUser from '@/components/delete-user';
import HeadingSmall from '@/components/heading-small';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import PublicLayout from '@/layouts/public-layout';
import { edit } from '@/routes/profile';
import { send } from '@/routes/verification';
import { type BreadcrumbItem, type SharedData } from '@/types';

export default function Profile({
    mustVerifyEmail,
    status,
}: {
    mustVerifyEmail: boolean;
    status?: string;
}) {
    const { auth } = usePage<SharedData>().props;
    const user = auth.user;
    const fileInputRef = useRef<HTMLInputElement>(null);
    const [preview, setPreview] = useState<string | null>(user.profile_photo_url || null);

    const { data: avatarData, setData: setAvatarData, post: postAvatar, delete: destroyAvatar, processing: processingAvatar, errors: errorsAvatar, reset: resetAvatar, recentlySuccessful: recentlySuccessfulAvatar, setError: setAvatarError, clearErrors: clearAvatarErrors } = useForm({
        avatar: null as File | null,
    });

    useEffect(() => {
        setPreview(user.profile_photo_url || null);
    }, [user.profile_photo_url]);

    const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        clearAvatarErrors('avatar');

        if (file) {
            if (file.size > 2 * 1024 * 1024) { // 2MB
                setAvatarError('avatar', 'La imagen no debe pesar más de 2MB.');
                e.target.value = ''; // Reset input
                return;
            }

            setAvatarData('avatar', file);
            setPreview(URL.createObjectURL(file));
        }
    };

    const saveAvatar = (e: React.FormEvent) => {
        e.preventDefault();
        postAvatar('/settings/profile/avatar', {
            onSuccess: () => {
                resetAvatar('avatar');
            }
        });
    };

    const removeAvatar = () => {
        if (confirm('¿Estás seguro de que quieres eliminar tu foto de perfil?')) {
            destroyAvatar('/settings/profile/avatar', {
                onSuccess: () => {
                    setPreview(null);
                    setAvatarData('avatar', null);
                }
            });
        }
    };

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

    return (
        <PublicLayout>
            <Head title="Configuración del perfil" />

            <div className="container py-10 max-w-4xl mx-auto">
                <div className="space-y-6">
                    <h1 className="text-3xl font-bold tracking-tight text-forest">Configuración del perfil</h1>
                    
                    <div className="rounded-xl border bg-card text-card-foreground shadow space-y-8 p-6">
                        {/* Sección Avatar */}
                        <div className="space-y-6 border-b border-border pb-6">
                            <HeadingSmall
                                title="Foto de perfil"
                                description="Actualiza o elimina tu foto de perfil"
                            />
                            
                            <div className="flex items-center gap-6">
                                <div className="relative group">
                                    <Avatar className="h-24 w-24 border-2 border-border">
                                        <AvatarImage src={preview || ''} className="object-cover" />
                                        <AvatarFallback className="bg-muted text-muted-foreground text-2xl">
                                            {user.name.charAt(0)}
                                        </AvatarFallback>
                                    </Avatar>
                                </div>

                                <div className="flex flex-col gap-3">
                                    <div className="flex items-center gap-2">
                                        <Button 
                                            type="button" 
                                            variant="outline" 
                                            size="sm"
                                            onClick={triggerFileInput}
                                            disabled={processingAvatar}
                                        >
                                            <Camera className="mr-2 h-4 w-4" />
                                            Seleccionar nueva foto
                                        </Button>
                                        
                                        {(preview || user.avatar) && (
                                            <Button 
                                                type="button" 
                                                variant="ghost" 
                                                size="icon"
                                                className="text-destructive hover:text-destructive hover:bg-destructive/10"
                                                onClick={removeAvatar}
                                                disabled={processingAvatar}
                                                title="Eliminar foto"
                                            >
                                                <Trash2 className="h-4 w-4" />
                                            </Button>
                                        )}
                                    </div>
                                    <input
                                        type="file"
                                        ref={fileInputRef}
                                        className="hidden"
                                        accept="image/png, image/jpeg, image/jpg, image/webp"
                                        onChange={handleAvatarChange}
                                    />
                                    <div className="text-sm text-muted-foreground">
                                        Max. 2MB (JPG, PNG, WEBP)
                                    </div>
                                    <InputError message={errorsAvatar.avatar} />

                                    {avatarData.avatar && (
                                        <div className="flex items-center gap-2 mt-2">
                                            <Button 
                                                onClick={saveAvatar} 
                                                size="sm" 
                                                disabled={processingAvatar}
                                            >
                                                Guardar cambio
                                            </Button>
                                            <Button 
                                                onClick={() => {
                                                    setAvatarData('avatar', null);
                                                    setPreview(user.profile_photo_url || null);
                                                }} 
                                                variant="ghost" 
                                                size="sm"
                                            >
                                                Cancelar
                                            </Button>
                                        </div>
                                    )}
                                    
                                    <Transition
                                        show={recentlySuccessfulAvatar}
                                        enter="transition ease-in-out"
                                        enterFrom="opacity-0"
                                        leave="transition ease-in-out"
                                        leaveTo="opacity-0"
                                    >
                                        <p className="text-sm text-green-600">
                                            Foto actualizada correctamente.
                                        </p>
                                    </Transition>
                                </div>
                            </div>
                        </div>

                        <HeadingSmall
                            title="Información del perfil"
                            description="Actualiza tu información personal y correo electrónico"
                        />

                        <Form
                            {...ProfileController.update.form()}
                            options={{
                                preserveScroll: true,
                            }}
                            className="space-y-6"
                        >
                            {({ processing, recentlySuccessful, errors }) => (
                                <>
                                    <div className="grid gap-2">
                                        <Label htmlFor="name">Nombre completo</Label>

                                        <Input
                                            id="name"
                                            className="mt-1 block w-full"
                                            defaultValue={auth.user.name}
                                            name="name"
                                            required
                                            autoComplete="name"
                                            placeholder="Tu nombre completo"
                                        />

                                        <InputError
                                            className="mt-2"
                                            message={errors.name}
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="email">Correo electrónico</Label>

                                        <Input
                                            id="email"
                                            type="email"
                                            className="mt-1 block w-full"
                                            defaultValue={auth.user.email}
                                            name="email"
                                            required
                                            autoComplete="username"
                                            placeholder="correo@ejemplo.com"
                                        />

                                        <InputError
                                            className="mt-2"
                                            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}
                                                className="mt-1 block w-full"
                                                defaultValue={auth.user.age || ''}
                                                name="age"
                                                placeholder="25"
                                            />
                                            <InputError className="mt-2" message={errors.age} />
                                        </div>

                                        <div className="grid gap-2">
                                            <Label htmlFor="gender">Género</Label>
                                            <Select name="gender" defaultValue={auth.user.gender || undefined}>
                                                <SelectTrigger className="mt-1">
                                                    <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 className="mt-2" message={errors.gender} />
                                        </div>
                                    </div>

                                    {/* Country */}
                                    <div className="grid gap-2">
                                        <Label htmlFor="country">País de residencia</Label>
                                        <Input
                                            id="country"
                                            type="text"
                                            className="mt-1 block w-full"
                                            defaultValue={auth.user.country || ''}
                                            name="country"
                                            placeholder="Bolivia, Perú, Ecuador..."
                                        />
                                        <InputError className="mt-2" 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"
                                            name="entheogen_activity"
                                            className="mt-1 block w-full min-h-[80px] resize-none"
                                            defaultValue={auth.user.entheogen_activity || ''}
                                            placeholder="Describe brevemente tu experiencia o interés..."
                                        />
                                        <InputError className="mt-2" message={errors.entheogen_activity} />
                                    </div>

                                    {mustVerifyEmail &&
                                        auth.user.email_verified_at === null && (
                                            <div>
                                                <p className="-mt-4 text-sm text-muted-foreground">
                                                    Tu dirección de correo no está verificada.{' '}
                                                    <Link
                                                        href={send()}
                                                        as="button"
                                                        className="text-foreground underline decoration-neutral-300 underline-offset-4 transition-colors duration-300 ease-out hover:decoration-current! dark:decoration-neutral-500"
                                                    >
                                                        Haz clic aquí para re-enviar el correo de verificación.
                                                    </Link>
                                                </p>

                                                {status ===
                                                    'verification-link-sent' && (
                                                    <div className="mt-2 text-sm font-medium text-green-600">
                                                        Un nuevo enlace de verificación ha sido enviado a tu correo.
                                                    </div>
                                                )}
                                            </div>
                                        )}

                                    <div className="flex items-center gap-4">
                                        <Button
                                            disabled={processing}
                                            data-test="update-profile-button"
                                        >
                                            Guardar
                                        </Button>

                                        <Transition
                                            show={recentlySuccessful}
                                            enter="transition ease-in-out"
                                            enterFrom="opacity-0"
                                            leave="transition ease-in-out"
                                            leaveTo="opacity-0"
                                        >
                                            <p className="text-sm text-neutral-600">
                                                Guardado
                                            </p>
                                        </Transition>
                                    </div>
                                </>
                            )}
                        </Form>
                    </div>
                    <DeleteUser />
                </div>
            </div>
        </PublicLayout>
    );
}
