import { Link, usePage } from "@inertiajs/react";
import { ClipboardList, Package, ShieldCheck } from "lucide-react";
import AppLogoIcon from "@/components/app-logo-icon";
import { cn } from "@/lib/utils";
import { home } from "@/routes";
import type { AuthLayoutProps, Branding } from "@/types";

/**
 * The frame every staff authentication screen sits in.
 *
 * One half is the company's own: the picture they chose in Settings -> Company
 * profile, or — when they have not chosen one — the colour they chose instead,
 * plus their name, their logo and the words they wrote for this screen. The
 * other half is the form, on plain ground in a card so the fields are the only
 * thing competing for attention.
 *
 * Every word on the panel is a setting, including the three lines it lists, so
 * a client can say what this system does in their own language rather than the
 * language it shipped with.
 */

/** The icons the panel cycles through, whatever the words beside them say. */
const featureIcons = [ClipboardList, Package, ShieldCheck];

function Backdrop({
    background,
    branding,
}: {
    background: string | null;
    branding?: Branding;
}) {
    const panel = branding?.login_panel;

    if (background) {
        return (
            <div aria-hidden className="absolute inset-0">
                <div
                    className="absolute inset-0 bg-cover bg-center"
                    style={{ backgroundImage: `url(${background})` }}
                />
                {/* The veil is built from the chosen colour server-side, so a
                    client's palette keeps the words on their photo readable. */}
                <div
                    className="absolute inset-0"
                    style={{ backgroundImage: panel?.veil }}
                />
            </div>
        );
    }

    return (
        <div aria-hidden className="absolute inset-0">
            <div
                className="absolute inset-0"
                style={{ backgroundColor: panel?.color }}
            />
            <div
                className="absolute inset-0"
                style={{ backgroundImage: panel?.glow }}
            />
            <div
                className="absolute inset-0 opacity-[0.14]"
                style={{
                    backgroundImage:
                        "repeating-linear-gradient(90deg, rgba(255,255,255,0.55) 0 1px, transparent 1px 64px), repeating-linear-gradient(0deg, rgba(255,255,255,0.55) 0 1px, transparent 1px 64px)",
                    maskImage:
                        "linear-gradient(to top, #000 0%, transparent 78%)",
                    WebkitMaskImage:
                        "linear-gradient(to top, #000 0%, transparent 78%)",
                }}
            />
        </div>
    );
}

function BrandLockup({
    branding,
    compact = false,
}: {
    branding?: Branding;
    compact?: boolean;
}) {
    return (
        <Link
            href={home()}
            className="relative z-10 flex items-center gap-3 text-white"
        >
            {branding?.logo_url ? (
                <img
                    src={branding.logo_url}
                    alt=""
                    className={cn(
                        "rounded-xl bg-white/5 object-cover ring-1 ring-white/20",
                        compact ? "size-9" : "size-11",
                    )}
                />
            ) : (
                <span
                    className={cn(
                        "flex items-center justify-center rounded-xl bg-white/10 ring-1 ring-white/20 backdrop-blur-sm",
                        compact ? "size-9" : "size-11",
                    )}
                >
                    <AppLogoIcon
                        className={cn(
                            "fill-white",
                            compact ? "size-4" : "size-5",
                        )}
                    />
                </span>
            )}
            <span className="min-w-0">
                <span
                    className={cn(
                        "block truncate font-semibold tracking-tight",
                        compact ? "text-sm" : "text-base",
                    )}
                >
                    {branding?.name ?? ""}
                </span>
                <span className="block truncate text-[10px] font-medium tracking-[0.14em] text-white/55 uppercase">
                    {branding?.login_eyebrow ?? "Staff workspace"}
                </span>
            </span>
        </Link>
    );
}

export default function AuthSplitLayout({
    children,
    title,
    description,
}: AuthLayoutProps) {
    const { branding } = usePage().props as unknown as { branding?: Branding };

    const background = branding?.login_background_url ?? null;
    const support = branding?.support_email ?? null;
    const year = new Date().getFullYear();
    const contact = [
        branding?.support_phone,
        branding?.support_email,
        branding?.website?.replace(/^https?:\/\//, ""),
    ].filter((item): item is string => Boolean(item));

    // The words on the card come from the page that is being shown — "Create an
    // account", "Reset your password" — and fall back to the sign-in screen's
    // own words only when the page supplies none, which is the sign-in page.
    const cardTitle =
        title?.trim() || branding?.login_card_title || "Log in to your account";
    const cardDescription =
        description?.trim() || branding?.login_card_description || "";

    const features = branding?.login_features?.length
        ? branding.login_features
        : [];

    return (
        <div className="grid min-h-svh lg:grid-cols-[1.08fr_1fr]">
            <aside className="relative hidden flex-col justify-between overflow-hidden p-10 text-white lg:flex xl:p-14">
                <Backdrop background={background} branding={branding} />

                <BrandLockup branding={branding} />

                <div className="relative z-10 my-10 max-w-lg space-y-7">
                    <div className="space-y-3">
                        <h2 className="text-3xl font-semibold tracking-tight text-balance xl:text-4xl">
                            {branding?.login_headline}
                        </h2>
                        <p className="max-w-md text-sm leading-relaxed text-white/65">
                            {branding?.login_tagline}
                        </p>
                    </div>

                    {features.length > 0 ? (
                        <ul className="grid gap-3 rounded-2xl border border-white/10 bg-white/[0.05] p-4 backdrop-blur-sm">
                            {features.map((item, index) => {
                                const Icon =
                                    featureIcons[index % featureIcons.length] ??
                                    ShieldCheck;

                                return (
                                    <li
                                        key={`${index}-${item.title}`}
                                        className="flex items-start gap-3"
                                    >
                                        <span className="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-lg bg-white/10 ring-1 ring-white/15">
                                            <Icon className="size-4 text-white/80" />
                                        </span>
                                        <span className="min-w-0">
                                            <span className="block text-sm font-medium">
                                                {item.title}
                                            </span>
                                            <span className="mt-0.5 block text-xs leading-relaxed text-white/55">
                                                {item.body}
                                            </span>
                                        </span>
                                    </li>
                                );
                            })}
                        </ul>
                    ) : null}
                </div>

                <div className="relative z-10 space-y-1 text-xs text-white/50">
                    {contact.length > 0 ? (
                        <p className="text-white/65">{contact.join(" · ")}</p>
                    ) : null}
                    {branding?.address_lines?.length ? (
                        <p>{branding.address_lines.join(", ")}</p>
                    ) : null}
                    {branding?.abn_label ? <p>{branding.abn_label}</p> : null}
                </div>
            </aside>

            <div className="flex min-h-svh flex-col bg-background">
                <div className="relative overflow-hidden px-6 pt-6 pb-8 text-white lg:hidden">
                    <Backdrop background={background} branding={branding} />
                    <BrandLockup branding={branding} compact />
                    {branding?.login_headline ? (
                        <p className="relative z-10 mt-5 max-w-sm text-sm leading-relaxed text-white/70">
                            {branding.login_headline}
                        </p>
                    ) : null}
                </div>

                <main className="flex flex-1 items-center justify-center px-6 py-8 lg:px-10">
                    <div className="w-full max-w-md">
                        <div className="rounded-2xl bg-card p-6 shadow-raised ring-1 ring-hairline sm:p-8">
                            <div className="space-y-1.5">
                                <h1 className="text-xl font-semibold tracking-tight">
                                    {cardTitle}
                                </h1>
                                {cardDescription ? (
                                    <p className="text-sm leading-relaxed text-muted-foreground">
                                        {cardDescription}
                                    </p>
                                ) : null}
                            </div>

                            <div className="mt-6">{children}</div>
                        </div>

                        {branding?.login_footer_note || support ? (
                            <p className="mt-4 text-center text-xs leading-relaxed text-muted-foreground">
                                {branding?.login_footer_note}
                                {support ? (
                                    <>
                                        {" "}
                                        Trouble signing in?{" "}
                                        <a
                                            href={`mailto:${support}`}
                                            className="font-medium text-foreground underline-offset-4 hover:underline"
                                        >
                                            {support}
                                        </a>
                                    </>
                                ) : null}
                            </p>
                        ) : null}
                    </div>
                </main>

                <footer className="px-6 pb-6 text-center text-[11px] text-muted-foreground lg:px-10">
                    © {year} {branding?.name ?? ""}
                </footer>
            </div>
        </div>
    );
}
