import ClientLayout from '@/Layouts/ClientLayout';
import { PageProps } from '@/types';
import { Head, useForm } from '@inertiajs/react';
import { Globe } from 'lucide-react';
import { useState } from 'react';
import SetupStepper from './components/SetupStepper';

type Props = PageProps<{
    tenant: { id: string; name: string; subdomain: string | null };
    domainSuffix: string;
}>;

function toSubdomainSlug(value: string): string {
    return value
        .toLowerCase()
        .replace(/[^a-z0-9-]/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '');
}

export default function Subdomain({ tenant, domainSuffix }: Props) {
    const { data, setData, post, processing, errors } = useForm({
        subdomain: tenant.subdomain ?? toSubdomainSlug(tenant.name),
    });

    const [touched, setTouched] = useState(false);

    function handleChange(value: string) {
        setTouched(true);
        setData('subdomain', toSubdomainSlug(value));
    }

    function submit(e: React.FormEvent) {
        e.preventDefault();
        post(route('setup.subdomain.store', { tenant: tenant.id }));
    }

    const preview = data.subdomain
        ? `${data.subdomain}${domainSuffix}`
        : `yourorg${domainSuffix}`;

    const isValid =
        data.subdomain.length >= 3 &&
        /^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(data.subdomain);

    return (
        <ClientLayout title="Setup — Subdomain">
            <Head title="Setup: Subdomain" />

            <div className="mx-auto max-w-2xl space-y-6 p-6 lg:p-8">
                <SetupStepper current={2} />

                <div className="pf-glass p-6 sm:p-8">
                    <div className="mb-6 flex items-center gap-3">
                        <span className="bg-primary/10 flex h-10 w-10 items-center justify-center rounded-xl">
                            <Globe className="text-primary h-5 w-5" />
                        </span>
                        <div>
                            <h1 className="text-foreground text-lg font-semibold">
                                Choose your subdomain
                            </h1>
                            <p className="text-muted-foreground text-sm">
                                This is the URL your clients will use to log in.
                            </p>
                        </div>
                    </div>

                    <form onSubmit={submit} className="space-y-5">
                        <div className="space-y-2">
                            <label className="text-foreground text-sm font-medium">
                                Subdomain
                                <span className="text-destructive ml-0.5">
                                    *
                                </span>
                            </label>

                            <div className="border-border focus-within:ring-primary/30 flex overflow-hidden rounded-xl border focus-within:ring-2">
                                <input
                                    type="text"
                                    value={data.subdomain}
                                    onChange={(e) =>
                                        handleChange(e.target.value)
                                    }
                                    placeholder="yourorg"
                                    className="bg-background text-foreground placeholder:text-muted-foreground dark:placeholder:text-muted-foreground/50 min-w-0 flex-1 px-4 py-2.5 text-sm outline-none"
                                />
                                <span className="bg-muted/40 text-muted-foreground flex items-center border-l px-3 text-sm select-none">
                                    {domainSuffix}
                                </span>
                            </div>

                            {errors.subdomain && (
                                <p className="text-destructive text-xs">
                                    {errors.subdomain}
                                </p>
                            )}

                            {touched && data.subdomain && !isValid && (
                                <p className="text-xs text-amber-600 dark:text-amber-400">
                                    Must be 3+ characters, lowercase letters,
                                    numbers and hyphens only — cannot start or
                                    end with a hyphen.
                                </p>
                            )}
                        </div>

                        <div className="bg-muted/30 border-border rounded-xl border p-4">
                            <p className="text-muted-foreground mb-1 text-xs font-medium tracking-wider uppercase">
                                Your portal URL
                            </p>
                            <p
                                className={`font-mono text-sm font-semibold break-all ${isValid || !data.subdomain ? 'text-foreground' : 'text-muted-foreground'}`}
                            >
                                https://{preview}
                            </p>
                        </div>

                        <div className="flex items-center justify-between pt-2">
                            <a
                                href={route('setup.edit', {
                                    tenant: tenant.id,
                                })}
                                className="text-muted-foreground hover:text-foreground text-sm transition-colors"
                            >
                                ← Back
                            </a>
                            <button
                                type="submit"
                                disabled={processing || !isValid}
                                className="pf-btn px-6 py-2.5 text-sm disabled:cursor-not-allowed disabled:opacity-50"
                            >
                                {processing ? 'Saving…' : 'Continue →'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </ClientLayout>
    );
}
