import { Form, Head } from '@inertiajs/react';
import { useState } from 'react';
import AuthField, {
    AuthFooterLink,
    AuthSubmitButton,
    authInputClasses,
    authLinkClasses,
    errorAttributes,
} from '@/components/auth/auth-field';
import InputError from '@/components/input-error';
import PasswordInput from '@/components/password-input';
import { Checkbox } from '@/components/ui/checkbox';
import { login, termsOfUse } from '@/routes';
import { store } from '@/routes/register';
import { RequiredMark } from '@/components/required-mark';

type Props = {
    passwordRules: string;
    /** The cooperative from the sign-up link (or the only one). */
    business: { name: string; slug: string } | null;
    /** Cooperatives to choose from when the link didn't name one. */
    businesses: { value: string; label: string }[];
};

export default function Register({
    passwordRules,
    business,
    businesses,
}: Props) {
    const [agreed, setAgreed] = useState(false);

    return (
        <>
            <Head title="Open an account" />

            <Form
                {...store.form()}
                resetOnSuccess={['password', 'password_confirmation']}
                disableWhileProcessing
                className="flex flex-col gap-5"
            >
                {({ processing, errors }) => (
                    <>
                        {business ? (
                            <>
                                <input
                                    type="hidden"
                                    name="business"
                                    value={business.slug}
                                />
                                <p className="-mb-1 rounded-landing bg-brand-faint px-3 py-2 text-sm text-ink-700">
                                    Joining{' '}
                                    <span className="font-semibold text-ink">
                                        {business.name}
                                    </span>
                                </p>
                                <InputError message={errors.business} />
                            </>
                        ) : (
                            businesses.length > 0 && (
                                <AuthField
                                    id="business"
                                    required
                                    label="Cooperative"
                                    error={errors.business}
                                >
                                    <select
                                        id="business"
                                        name="business"
                                        required
                                        defaultValue=""
                                        className={authInputClasses}
                                        {...errorAttributes(
                                            'business',
                                            errors.business,
                                        )}
                                    >
                                        <option value="" disabled>
                                            Choose the one you are joining
                                        </option>
                                        {businesses.map((option) => (
                                            <option
                                                key={option.value}
                                                value={option.value}
                                            >
                                                {option.label}
                                            </option>
                                        ))}
                                    </select>
                                </AuthField>
                            )
                        )}

                        <AuthField
                            id="name"
                            required
                            label="Full name"
                            error={errors.name}
                        >
                            <input
                                id="name"
                                type="text"
                                name="name"
                                required
                                autoFocus
                                autoComplete="name"
                                placeholder="As it appears on your ID"
                                className={authInputClasses}
                                {...errorAttributes('name', errors.name)}
                            />
                        </AuthField>

                        <AuthField
                            id="email"
                            required
                            label="Email address"
                            error={errors.email}
                        >
                            <input
                                id="email"
                                type="email"
                                name="email"
                                required
                                autoComplete="email"
                                placeholder="you@example.com"
                                className={authInputClasses}
                                {...errorAttributes('email', errors.email)}
                            />
                        </AuthField>

                        <AuthField
                            id="password"
                            required
                            label="Password"
                            error={errors.password}
                        >
                            <PasswordInput
                                id="password"
                                name="password"
                                required
                                autoComplete="new-password"
                                placeholder="Create a password"
                                passwordrules={passwordRules}
                                className={`${authInputClasses} pr-11`}
                                {...errorAttributes(
                                    'password',
                                    errors.password,
                                )}
                            />
                        </AuthField>

                        <AuthField
                            id="password_confirmation"
                            required
                            label="Confirm password"
                            error={errors.password_confirmation}
                        >
                            <PasswordInput
                                id="password_confirmation"
                                name="password_confirmation"
                                required
                                autoComplete="new-password"
                                placeholder="Re-enter your password"
                                passwordrules={passwordRules}
                                className={`${authInputClasses} pr-11`}
                                {...errorAttributes(
                                    'password_confirmation',
                                    errors.password_confirmation,
                                )}
                            />
                        </AuthField>

                        <div className="flex flex-col gap-2">
                            <div className="flex items-start gap-3">
                                <Checkbox
                                    id="terms"
                                    name="terms"
                                    required
                                    checked={agreed}
                                    onCheckedChange={(checked) =>
                                        setAgreed(checked === true)
                                    }
                                    className="mt-0.5 size-4.5 border-ink-200 bg-white data-[state=checked]:border-brand data-[state=checked]:bg-brand data-[state=checked]:text-white"
                                    {...errorAttributes('terms', errors.terms)}
                                />
                                <label
                                    htmlFor="terms"
                                    className="text-sm leading-relaxed text-ink-500"
                                >
                                    I agree to the{' '}
                                    <a
                                        href={termsOfUse.url()}
                                        target="_blank"
                                        rel="noopener"
                                        className={authLinkClasses}
                                    >
                                        Terms of Service
                                    </a>{' '}
                                    and{' '}
                                    <a
                                        href={`${termsOfUse.url()}#2-membership-and-eligibility`}
                                        target="_blank"
                                        rel="noopener"
                                        className={authLinkClasses}
                                    >
                                        cooperative membership rules
                                    </a>
                                    .
                                    <RequiredMark />
                                </label>
                            </div>
                            {errors.terms && (
                                <p
                                    id="terms-error"
                                    className="text-sm text-red-600"
                                >
                                    {errors.terms}
                                </p>
                            )}
                        </div>

                        <AuthSubmitButton
                            processing={processing}
                            disabled={!agreed}
                            title={
                                agreed
                                    ? undefined
                                    : 'Tick the box to agree to the terms first'
                            }
                            className="mt-2"
                            data-test="register-user-button"
                        >
                            Create account
                        </AuthSubmitButton>

                        <AuthFooterLink
                            prompt="Already a member?"
                            href={login()}
                            label="Sign in"
                        />
                    </>
                )}
            </Form>
        </>
    );
}

Register.layout = {
    title: 'Open your account',
    description:
        'It takes a few minutes. You can verify your identity once you are in.',
};
