import { Link } from '@inertiajs/react';
import { CircleUserRound, Landmark } from 'lucide-react';
import InputError from '@/components/input-error';
import { formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { edit as editPin } from '@/routes/transaction-pin';
import { RequiredMark } from '@/components/required-mark';

export type TransferLimits = {
    min: number;
    max: number;
    daily: number;
    remainingToday: number;
};

export const transferInputClasses =
    'h-11 w-full rounded-landing border border-surface-200 bg-white px-3.5 text-[15px] text-ink outline-none placeholder:text-ink-300 focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15 aria-invalid:border-red-500';

export const transferPrimaryButton =
    'inline-flex h-11 w-full items-center justify-center gap-2 rounded-full bg-brand px-5 text-[15px] font-semibold text-white transition-colors hover:bg-brand-hover focus-visible:ring-2 focus-visible:ring-highlight focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50';

/** Parses a typed naira amount ("2500" or "2500.50") into kobo, or null when invalid. */
export function toKobo(naira: string): number | null {
    if (!/^\d{1,10}(\.\d{1,2})?$/.test(naira)) {
        return null;
    }

    const [whole, fraction = ''] = naira.split('.');

    return Number(whole) * 100 + Number(fraction.padEnd(2, '0'));
}

/** Why an amount cannot be sent yet, or null when it is fine (or still empty). */
export function amountProblem(
    amount: string,
    balance: number,
    limits: TransferLimits,
): string | null {
    if (amount === '') {
        return null;
    }

    const kobo = toKobo(amount);

    if (kobo === null) {
        return 'Enter an amount in naira, e.g. 5000 or 5000.50.';
    }

    if (kobo < limits.min) {
        return `The smallest transfer is ${formatNaira(limits.min)}.`;
    }

    if (kobo > limits.max) {
        return `The largest single transfer is ${formatNaira(limits.max)}.`;
    }

    if (kobo > balance) {
        return 'This is more than your available balance.';
    }

    if (kobo > limits.remainingToday) {
        return `You can send up to ${formatNaira(limits.remainingToday)} more today.`;
    }

    return null;
}

export function TransferBalance({ balance }: { balance: number }) {
    return (
        <div className="relative overflow-hidden rounded-landing bg-linear-to-br from-brand to-brand-dark px-4 py-3.5 text-white">
            <div
                aria-hidden="true"
                className="pointer-events-none absolute -top-16 -right-10 size-40 rounded-full bg-white/6"
            />
            <p className="text-xs text-white/70">Available balance</p>
            <p className="mt-0.5 font-display text-2xl font-semibold tabular-nums">
                {formatNaira(balance)}
            </p>
            <Landmark className="absolute top-1/2 right-4 size-8 -translate-y-1/2 text-white/25" />
        </div>
    );
}

export function TransferSteps({
    steps,
    current,
}: {
    steps: readonly string[];
    current: number;
}) {
    return (
        <ol
            className="mt-5 grid gap-2"
            style={{
                gridTemplateColumns: `repeat(${steps.length}, minmax(0, 1fr))`,
            }}
        >
            {steps.map((label, index) => (
                <li key={label} className="text-center">
                    <span
                        className={cn(
                            'block h-1 rounded-full',
                            index <= current
                                ? 'bg-highlight'
                                : 'bg-surface-100',
                        )}
                    />
                    <span
                        className={cn(
                            'mt-1.5 block truncate text-xs font-semibold',
                            index === current ? 'text-ink' : 'text-ink-400',
                        )}
                        aria-current={index === current ? 'step' : undefined}
                    >
                        {label}
                    </span>
                </li>
            ))}
        </ol>
    );
}

export function RecipientCard({
    name,
    detail,
    onChange,
}: {
    name: string;
    detail: string;
    onChange: () => void;
}) {
    return (
        <div className="flex items-center gap-3 rounded-landing border border-highlight/30 bg-highlight-faint px-3.5 py-3">
            <CircleUserRound className="size-8 shrink-0 text-highlight-dark" />
            <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-semibold text-ink">
                    {name}
                </p>
                <p className="truncate text-xs tracking-wide text-ink-500">
                    {detail}
                </p>
            </div>
            <button
                type="button"
                onClick={onChange}
                className="shrink-0 text-xs font-semibold text-brand hover:text-highlight-dark"
            >
                Change
            </button>
        </div>
    );
}

/** Summary rows shown before the member confirms a transfer. */
export function TransferSummary({
    rows,
    balanceAfter,
}: {
    rows: [string, string][];
    balanceAfter: number;
}) {
    return (
        <dl className="grid gap-2.5 rounded-landing bg-surface-50 p-4 text-sm">
            {rows.map(([term, detail]) => (
                <div key={term} className="flex justify-between gap-4">
                    <dt className="shrink-0 text-ink-400">{term}</dt>
                    <dd className="text-right font-semibold break-all text-ink">
                        {detail}
                    </dd>
                </div>
            ))}
            <div className="mt-1 flex justify-between gap-4 border-t border-dashed border-surface-200 pt-2.5">
                <dt className="text-ink-500">Balance after</dt>
                <dd className="font-semibold text-ink tabular-nums">
                    {formatNaira(balanceAfter)}
                </dd>
            </div>
        </dl>
    );
}

export function PinField({
    hasPin,
    value,
    error,
    onChange,
}: {
    hasPin: boolean;
    value: string;
    error?: string;
    onChange: (pin: string) => void;
}) {
    if (!hasPin) {
        return (
            <p className="rounded-landing border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
                <Link
                    href={editPin()}
                    className="font-semibold underline-offset-4 hover:underline"
                >
                    Set your transaction PIN
                </Link>{' '}
                before sending money.
            </p>
        );
    }

    return (
        <div className="flex flex-col gap-2">
            <label htmlFor="pin" className="text-sm font-semibold text-ink-700">
                Transaction PIN
                <RequiredMark />
            </label>
            <input
                id="pin"
                type="password"
                inputMode="numeric"
                autoComplete="off"
                autoFocus
                maxLength={4}
                placeholder="••••"
                value={value}
                onChange={(event) =>
                    onChange(event.target.value.replace(/\D/g, '').slice(0, 4))
                }
                aria-invalid={error ? true : undefined}
                className={cn(
                    transferInputClasses,
                    'text-center tracking-[0.5em]',
                )}
            />
            <InputError message={error} />
        </div>
    );
}

/** Numbered "how it works" panel shown beside the transfer form on wide screens. */
export function HowItWorks({
    title,
    steps,
}: {
    title: string;
    steps: string[];
}) {
    return (
        <aside className="rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm">
            <h2 className="font-display text-base font-semibold text-ink">
                {title}
            </h2>
            <ol className="mt-4 grid gap-3">
                {steps.map((step, index) => (
                    <li
                        key={step}
                        className="flex items-start gap-3 text-sm text-ink-500"
                    >
                        <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-highlight-faint text-xs font-semibold text-highlight-dark">
                            {index + 1}
                        </span>
                        <span className="pt-0.5">{step}</span>
                    </li>
                ))}
            </ol>
        </aside>
    );
}
