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 { Label } from '@/components/ui/label';
import AuthLayout from '@/layouts/auth-layout';
import { Head, useForm } from '@inertiajs/react';
import { LoaderCircle } from 'lucide-react';
import { FormEventHandler } from 'react';

function slugify(value: string): string {
    return value
        .toLowerCase()
        .normalize('NFKD')
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '')
        .slice(0, 32);
}

export default function Signup({ domain, trialDays }: { domain: string; trialDays: number }) {
    const form = useForm({
        company: '',
        subdomain: '',
        name: '',
        email: '',
        password: '',
        password_confirmation: '',
        subdomainTouched: false as boolean,
    });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        form.transform(({ subdomainTouched: _unused, ...data }) => data);
        form.post(route('signup.store'), { onFinish: () => form.reset('password', 'password_confirmation') });
    };

    return (
        <AuthLayout title="Create your workspace" description={`Free for ${trialDays} days. No card needed.`}>
            <Head title="Sign up" />
            <form className="flex flex-col gap-5" onSubmit={submit}>
                <div className="grid gap-2">
                    <Label htmlFor="company">Company name</Label>
                    <Input
                        id="company"
                        required
                        autoFocus
                        value={form.data.company}
                        onChange={(e) =>
                            form.setData((d) => ({
                                ...d,
                                company: e.target.value,
                                subdomain: d.subdomainTouched ? d.subdomain : slugify(e.target.value),
                            }))
                        }
                        placeholder="Acme Inc"
                    />
                    <InputError message={form.errors.company} />
                </div>

                <div className="grid gap-2">
                    <Label htmlFor="subdomain">Workspace address</Label>
                    <div className="border-input focus-within:ring-ring/50 flex items-center rounded-md border shadow-xs focus-within:ring-[3px]">
                        <input
                            id="subdomain"
                            required
                            value={form.data.subdomain}
                            onChange={(e) => form.setData((d) => ({ ...d, subdomain: slugify(e.target.value), subdomainTouched: true }))}
                            className="h-9 min-w-0 flex-1 bg-transparent px-3 text-sm outline-none"
                            placeholder="acme"
                        />
                        <span className="text-muted-foreground pr-3 text-sm">.{domain}</span>
                    </div>
                    <InputError message={form.errors.subdomain} />
                </div>

                <div className="grid gap-2">
                    <Label htmlFor="name">Your name</Label>
                    <Input id="name" required value={form.data.name} onChange={(e) => form.setData('name', e.target.value)} autoComplete="name" />
                    <InputError message={form.errors.name} />
                </div>

                <div className="grid gap-2">
                    <Label htmlFor="email">Work email</Label>
                    <Input id="email" type="email" required value={form.data.email} onChange={(e) => form.setData('email', e.target.value)} autoComplete="email" />
                    <InputError message={form.errors.email} />
                </div>

                <div className="grid gap-2">
                    <Label htmlFor="password">Password</Label>
                    <Input id="password" type="password" required value={form.data.password} onChange={(e) => form.setData('password', e.target.value)} autoComplete="new-password" />
                    <InputError message={form.errors.password} />
                </div>

                <div className="grid gap-2">
                    <Label htmlFor="password_confirmation">Confirm password</Label>
                    <Input
                        id="password_confirmation"
                        type="password"
                        required
                        value={form.data.password_confirmation}
                        onChange={(e) => form.setData('password_confirmation', e.target.value)}
                        autoComplete="new-password"
                    />
                </div>

                <Button type="submit" className="mt-2 w-full" disabled={form.processing}>
                    {form.processing && <LoaderCircle className="h-4 w-4 animate-spin" />}
                    Create workspace
                </Button>

                <p className="text-muted-foreground text-center text-sm">
                    Already have a workspace? <TextLink href={route('workspace.find')}>Log in</TextLink>
                </p>
            </form>
        </AuthLayout>
    );
}
