import BackToHomeLink from '@/Components/BackToHomeLink';
import { Button, Checkbox, Field } from '@/Components/ui';
import { useForceLightTheme } from '@/lib/theme';
import { CrossMark } from '@/marketing/shared';
import { Head, Link, useForm, usePage } from '@inertiajs/react';
import type { SubmitEvent as ReactSubmitEvent } from 'react';

type RegisterForm = {
    name: string;
    email: string;
    password: string;
    password_confirmation: string;
    invite: string;
    terms: boolean;
};

type Props = {
    isFirstSignup?: boolean;
    invite?: {
        token: string;
        email: string;
        role?: 'editor' | 'viewer' | string;
        workspace?: string | null;
    } | null;
    requireConsent?: boolean;
    termsUrl?: string;
    privacyUrl?: string;
    googleEnabled?: boolean;
    githubEnabled?: boolean;
};

export default function Register({
    isFirstSignup = false,
    invite = null,
    requireConsent = false,
    termsUrl = '/terms',
    privacyUrl = '/privacy',
    googleEnabled = false,
    githubEnabled = false,
}: Props) {
    useForceLightTheme();
    const flash = (usePage().props.flash as { error?: string } | undefined);
    const { data, setData, post, processing, errors, reset } = useForm<RegisterForm>({
        name: '',
        // Register-with-invite (Team Workspaces P3): the email is pre-filled +
        // locked to the invited address, and the invite token rides along so
        // RegisterController joins the team on create.
        email: invite?.email ?? '',
        password: '',
        password_confirmation: '',
        invite: invite?.token ?? '',
        terms: false,
    });

    const submit = (e: ReactSubmitEvent) => {
        e.preventDefault();
        post('/register', {
            onFinish: () => reset('password', 'password_confirmation'),
        });
    };

    return (
        <>
            <Head title="Create account">
            </Head>
            <main className="min-h-screen bg-background font-sans text-foreground antialiased overflow-hidden">
                <div className="relative mx-auto min-h-screen max-w-6xl border-x border-border/60">
                    <CrossMark className="left-0 top-0" />
                    <CrossMark className="left-full top-0" />
                    <CrossMark className="left-0 top-full" />
                    <CrossMark className="left-full top-full" />
                    <div className="mx-auto flex min-h-screen max-w-md flex-col justify-center px-6 py-10">
                        <BackToHomeLink />

                        <div className="ms-card rounded-2xl border border-border bg-card p-6 shadow-sm sm:p-8">
                            <h1 className="font-display text-3xl font-medium leading-[1.1] tracking-tight text-foreground sm:text-4xl">
                                Start your <em className="italic text-accent">workspace</em>.
                            </h1>

                            {flash?.error && (
                                <div className="mt-4 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-3 text-[13px] text-destructive">
                                    {flash.error}
                                </div>
                            )}

                            {(googleEnabled || githubEnabled) && !invite && (
                                <div className="mt-5 space-y-2">
                                    {googleEnabled && (
                                        <a
                                            href="/auth/google"
                                            className="flex h-10 w-full items-center justify-center gap-2.5 rounded-md border border-border bg-card px-4 text-sm font-medium text-foreground transition-colors hover:bg-muted"
                                        >
                                            <GoogleIcon />
                                            Continue with Google
                                        </a>
                                    )}
                                    {githubEnabled && (
                                        <a
                                            href="/auth/github"
                                            className="flex h-10 w-full items-center justify-center gap-2.5 rounded-md border border-border bg-card px-4 text-sm font-medium text-foreground transition-colors hover:bg-muted"
                                        >
                                            <GitHubIcon />
                                            Continue with GitHub
                                        </a>
                                    )}
                                    <div className="relative mt-2 flex items-center gap-3">
                                        <div className="h-px flex-1 bg-border" />
                                        <span className="text-xs text-muted-foreground">or</span>
                                        <div className="h-px flex-1 bg-border" />
                                    </div>
                                </div>
                            )}

                            {invite && (
                                <div
                                    className="mt-6 rounded-lg border border-accent/30 bg-accent/10 px-3 py-3 text-[12px] text-foreground"
                                    data-testid="register-invite-notice"
                                >
                                    <p className="font-medium text-accent">
                                        You're joining {invite.workspace ?? 'a workspace'}
                                    </p>
                                    <p className="mt-1 text-muted-foreground">
                                        Invited as{' '}
                                        {(invite.role ?? 'editor') === 'viewer'
                                            ? 'a viewer'
                                            : (invite.role ?? 'editor') === 'admin'
                                              ? 'an admin'
                                              : 'an editor'}
                                        . Create your account below to accept — your
                                        email is locked to the invited address.
                                    </p>
                                </div>
                            )}

                            {isFirstSignup && (
                                <div
                                    className="mt-6 rounded-lg border border-success/30 bg-success/10 px-3 py-3 text-[12px] text-success"
                                    data-testid="register-first-signup-notice"
                                >
                                    <p className="font-medium">First signup — admin account</p>
                                    <p className="mt-1 text-muted-foreground">
                                        You're the first user on this install. The account
                                        you create here will automatically have admin
                                        access; subsequent signups follow the policy you
                                        configure under <code className="rounded bg-muted px-1 py-0.5 font-mono">/admin/settings</code>.
                                    </p>
                                </div>
                            )}

                            <form onSubmit={submit} className="mt-5 space-y-3">
                                <Field
                                    id="name"
                                    label="Full name"
                                    value={data.name}
                                    onChange={(e) => setData('name', e.target.value)}
                                    error={errors.name}
                                    autoComplete="name"
                                    maxLength={120}
                                    required
                                    autoFocus
                                />
                                <Field
                                    id="email"
                                    label="Email"
                                    type="email"
                                    autoComplete="email"
                                    value={data.email}
                                    onChange={(e) => setData('email', e.target.value)}
                                    error={errors.email}
                                    maxLength={191}
                                    required
                                    readOnly={Boolean(invite)}
                                    disabled={Boolean(invite)}
                                />
                                <Field
                                    id="password"
                                    label="Password"
                                    type="password"
                                    autoComplete="new-password"
                                    value={data.password}
                                    onChange={(e) => setData('password', e.target.value)}
                                    error={errors.password}
                                    maxLength={191}
                                    required
                                />
                                <Field
                                    id="password_confirmation"
                                    label="Confirm password"
                                    type="password"
                                    autoComplete="new-password"
                                    value={data.password_confirmation}
                                    onChange={(e) => setData('password_confirmation', e.target.value)}
                                    maxLength={191}
                                    required
                                />

                                {requireConsent && (
                                    <div>
                                        <label className="flex items-start gap-2.5 text-[13px] text-gray-600">
                                            <Checkbox
                                                checked={data.terms}
                                                onChange={(e) => setData('terms', e.target.checked)}
                                                wrapperClassName="mt-0.5"
                                                required
                                                data-testid="register-consent"
                                            />
                                            <span>
                                                I agree to the{' '}
                                                <a
                                                    href={termsUrl}
                                                    {...(/^https?:\/\//i.test(termsUrl)
                                                        ? { target: '_blank', rel: 'noopener noreferrer' }
                                                        : {})}
                                                    className="font-medium text-accent hover:underline"
                                                >
                                                    Terms of Service
                                                </a>{' '}
                                                and{' '}
                                                <a
                                                    href={privacyUrl}
                                                    {...(/^https?:\/\//i.test(privacyUrl)
                                                        ? { target: '_blank', rel: 'noopener noreferrer' }
                                                        : {})}
                                                    className="font-medium text-accent hover:underline"
                                                >
                                                    Privacy Policy
                                                </a>
                                                .
                                            </span>
                                        </label>
                                        {errors.terms && (
                                            <p className="mt-1 text-xs text-destructive">
                                                {errors.terms}
                                            </p>
                                        )}
                                    </div>
                                )}

                                <Button type="submit" disabled={processing} size="lg" className="w-full">
                                    {processing ? 'Creating account…' : 'Create account'}
                                </Button>
                            </form>

                            <p className="mt-6 text-sm text-muted-foreground">
                                Already have an account?{' '}
                                <Link href="/login" className="font-medium text-accent hover:underline">
                                    Sign in
                                </Link>
                            </p>
                        </div>
                    </div>
                </div>
            </main>
        </>
    );
}

function GoogleIcon() {
    return (
        <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true">
            <path
                d="M17.64 9.205c0-.639-.057-1.252-.164-1.841H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615Z"
                fill="#4285F4"
            />
            <path
                d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18Z"
                fill="#34A853"
            />
            <path
                d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332Z"
                fill="#FBBC05"
            />
            <path
                d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58Z"
                fill="#EA4335"
            />
        </svg>
    );
}

function GitHubIcon() {
    return (
        <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true">
            <path
                fillRule="evenodd"
                clipRule="evenodd"
                d="M9 0C4.025 0 0 4.025 0 9c0 3.977 2.578 7.349 6.154 8.539.45.082.614-.196.614-.43 0-.214-.008-.921-.012-1.668-2.503.544-3.031-1.074-3.031-1.074-.41-1.04-1-1.317-1-1.317-.816-.558.062-.547.062-.547.903.064 1.379.927 1.379.927.802 1.375 2.104.977 2.617.748.08-.581.314-.977.571-1.202-2-.227-4.102-1-4.102-4.449 0-.983.351-1.786.927-2.416-.093-.226-.402-1.142.088-2.381 0 0 .756-.242 2.475.923A8.617 8.617 0 0 1 9 4.25c.765.003 1.535.103 2.254.302 1.718-1.165 2.472-.923 2.472-.923.492 1.239.183 2.155.09 2.381.577.63.926 1.433.926 2.416 0 3.458-2.106 4.22-4.112 4.442.323.279.611.829.611 1.671 0 1.206-.011 2.18-.011 2.476 0 .236.161.516.618.429C15.425 16.347 18 12.976 18 9c0-4.975-4.025-9-9-9Z"
                fill="currentColor"
            />
        </svg>
    );
}
