import { Form, Head, usePage } from '@inertiajs/react';
import { useMemo, useState } from 'react';
import ContactNumberInput from '@/components/contact-number-input';
import TurnstileField from '@/components/turnstile-field';
import InputError from '@/components/input-error';
import PasswordInput from '@/components/password-input';
import TextLink from '@/components/text-link';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinner';
import { countryOptions } from '@/lib/countries';
import { login } from '@/routes';
import { store } from '@/routes/register';

type Props = {
    turnstileSiteKey?: string | null;
};

export default function Register({ turnstileSiteKey }: Props) {
    const [country, setCountry] = useState('');
    const [turnstileToken, setTurnstileToken] = useState<string | null>(null);
    const turnstileRequired = Boolean(turnstileSiteKey?.trim());
    const { url } = usePage();
    const referralCode = useMemo(() => {
        const query = url.split('?')[1] ?? '';

        return new URLSearchParams(query).get('ref') ?? '';
    }, [url]);

    return (
        <>
            <Head title="Registro" />
            <Form
                {...store.form()}
                resetOnSuccess={['password', 'password_confirmation']}
                disableWhileProcessing
                className="flex flex-col gap-6"
            >
                {({ processing, errors }) => (
                    <>
                        <div className="grid gap-6">
                            <div className="grid gap-4 sm:grid-cols-2">
                                <div className="grid gap-2">
                                    <Label htmlFor="first_name">Nombre</Label>
                                    <Input
                                        id="first_name"
                                        type="text"
                                        required
                                        autoFocus
                                        tabIndex={1}
                                        autoComplete="given-name"
                                        name="first_name"
                                        placeholder="Nombre"
                                    />
                                    <InputError
                                        message={errors.first_name}
                                        className="mt-2"
                                    />
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="last_name">Apellido</Label>
                                    <Input
                                        id="last_name"
                                        type="text"
                                        required
                                        tabIndex={2}
                                        autoComplete="family-name"
                                        name="last_name"
                                        placeholder="Apellido"
                                    />
                                    <InputError
                                        message={errors.last_name}
                                        className="mt-2"
                                    />
                                </div>
                            </div>

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

                            <div className="grid gap-2">
                                <Label htmlFor="referral_code">
                                    Código de referido{' '}
                                    <span className="text-muted-foreground">
                                        (opcional)
                                    </span>
                                </Label>
                                <Input
                                    id="referral_code"
                                    type="text"
                                    tabIndex={4}
                                    autoComplete="off"
                                    name="referral_code"
                                    defaultValue={referralCode}
                                    placeholder="Código o enlace recibido"
                                />
                                <InputError message={errors.referral_code} />
                            </div>

                            <div className="grid gap-2">
                                <Label htmlFor="country">País</Label>
                                <Select
                                    name="country"
                                    onValueChange={setCountry}
                                    required
                                >
                                    <SelectTrigger
                                        id="country"
                                        className="w-full"
                                        tabIndex={5}
                                    >
                                        <SelectValue placeholder="Selecciona tu país" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {countryOptions.map((country) => (
                                            <SelectItem
                                                key={country.value}
                                                value={country.value}
                                            >
                                                {country.label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <InputError message={errors.country} />
                            </div>

                            <div className="grid gap-2">
                                <Label htmlFor="contact_number">
                                    Número de contacto
                                </Label>
                                <ContactNumberInput
                                    country={country}
                                    id="contact_number"
                                    tabIndex={6}
                                />
                                <InputError message={errors.contact_number} />
                            </div>

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

                            <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 la contraseña"
                                />
                                <InputError
                                    message={errors.password_confirmation}
                                />
                            </div>

                            <TurnstileField
                                siteKey={turnstileSiteKey}
                                message={errors['cf-turnstile-response']}
                                onTokenChange={setTurnstileToken}
                            />

                            <Button
                                type="submit"
                                className="mt-2 w-full"
                                tabIndex={9}
                                disabled={
                                    processing ||
                                    (turnstileRequired && !turnstileToken)
                                }
                                data-test="register-user-button"
                            >
                                {processing && <Spinner />}
                                Crear cuenta
                            </Button>
                        </div>

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

Register.layout = {
    title: 'Crear una cuenta',
    description: 'Completa tus datos para registrarte',
};
