import { Form, Head, Link, router, usePage } from '@inertiajs/react';
import {
    ArrowRight,
    BadgeCheck,
    Check,
    Fingerprint,
    KeyRound,
    Mail,
    Upload,
} from 'lucide-react';
import type { ComponentType, ReactNode } from 'react';
import { useEffect, useState } from 'react';
import OnboardingController from '@/actions/App/Http/Controllers/OnboardingController';
import AuthField, {
    AuthSubmitButton,
    authInputClasses,
    authLinkClasses,
    errorAttributes,
} from '@/components/auth/auth-field';
import { cn } from '@/lib/utils';
import { dashboard, logout } from '@/routes';
import type { SelectOption } from '@/types';

type Step = { key: string; label: string; done: boolean };

type Props = {
    steps: Step[];
    current: string;
    firstName: string;
    email: string;
    emailCodeSent: boolean;
    emailResendAt: number | null;
    phone: string | null;
    identityDocumentTypes: SelectOption[];
    identityRejected: boolean;
    accountNumber: string | null;
    kycStatus: string;
    kycStatusLabel: string;
};

const codeClasses = cn(
    authInputClasses,
    'text-center font-mono text-xl tracking-[0.4em] md:text-xl',
);

export default function Onboarding(props: Props) {
    const { steps, current } = props;

    return (
        <>
            <Head title="Verify your account" />

            <ol
                className="mb-5 grid gap-1.5"
                style={{
                    gridTemplateColumns: `repeat(${steps.length}, minmax(0, 1fr))`,
                }}
            >
                {steps.map((step) => {
                    const isCurrent = step.key === current;

                    return (
                        <li key={step.key} className="grid gap-1">
                            <span
                                className={cn(
                                    'h-1 rounded-full',
                                    step.done
                                        ? 'bg-highlight'
                                        : isCurrent
                                          ? 'bg-brand'
                                          : 'bg-surface-200',
                                )}
                            />
                            <span
                                className={cn(
                                    'text-center text-[11px] font-semibold',
                                    step.done
                                        ? 'text-highlight-dark'
                                        : isCurrent
                                          ? 'text-brand'
                                          : 'text-ink-300',
                                )}
                            >
                                {step.label}
                            </span>
                        </li>
                    );
                })}
            </ol>

            {current === 'email' && <EmailStep {...props} />}
            {current === 'identity' && <IdentityStep {...props} />}
            {current === 'pin' && <PinStep />}
            {current === 'done' && <DoneStep {...props} />}

            {current !== 'done' && (
                <p className="mt-4 text-center text-xs text-ink-500">
                    Not you?{' '}
                    <Link
                        href={logout()}
                        as="button"
                        className={authLinkClasses}
                    >
                        Sign out
                    </Link>
                </p>
            )}
        </>
    );
}

function StepIntro({
    icon: Icon,
    title,
    children,
}: {
    icon: ComponentType<{ className?: string }>;
    title: string;
    children: ReactNode;
}) {
    return (
        <div className="mb-4 flex items-center gap-3">
            <span className="flex size-9 shrink-0 items-center justify-center rounded-landing bg-brand-faint text-brand">
                <Icon className="size-4.5" />
            </span>
            <div className="min-w-0">
                <h2 className="text-base font-semibold text-ink">{title}</h2>
                <p className="truncate text-[13px] text-ink-500">{children}</p>
            </div>
        </div>
    );
}

function digitsOnly(value: string, length: number): string {
    return value.replace(/\D/g, '').slice(0, length);
}

/**
 * Seconds left until the server allows another code (from a Unix time).
 */
function useSecondsUntil(at: number | null): number {
    const remaining = () =>
        at === null ? 0 : Math.max(0, Math.ceil(at - Date.now() / 1000));
    const [seconds, setSeconds] = useState(remaining);

    useEffect(() => {
        setSeconds(remaining());

        if (at === null) {
            return;
        }

        const timer = window.setInterval(() => {
            const left = remaining();
            setSeconds(left);

            if (left === 0) {
                window.clearInterval(timer);
            }
        }, 1000);

        return () => window.clearInterval(timer);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [at]);

    return seconds;
}

function CodeForm({
    action,
    resend,
    resendAt,
    extra,
}: {
    action: ReturnType<typeof OnboardingController.verifyEmail.form>;
    resend: () => void;
    resendAt: number | null;
    extra?: ReactNode;
}) {
    const wait = useSecondsUntil(resendAt);
    const pageErrors = usePage().props.errors as Record<
        string,
        string | undefined
    >;
    const [code, setCode] = useState('');

    return (
        <Form
            {...action}
            className="flex flex-col gap-3"
            onError={() => setCode('')}
        >
            {({ processing, errors }) => {
                const error = errors.code ?? pageErrors.code;

                return (
                    <>
                        <input
                            id="code"
                            name="code"
                            aria-label="6-digit code"
                            inputMode="numeric"
                            autoComplete="one-time-code"
                            maxLength={6}
                            autoFocus
                            placeholder="••••••"
                            className={codeClasses}
                            value={code}
                            onChange={(event) =>
                                setCode(digitsOnly(event.target.value, 6))
                            }
                            {...errorAttributes('code', error)}
                        />
                        {error && (
                            <p
                                id="code-error"
                                className="-mt-1 text-sm text-red-600"
                            >
                                {error}
                            </p>
                        )}
                        <AuthSubmitButton
                            processing={processing}
                            disabled={code.length !== 6}
                        >
                            Confirm
                        </AuthSubmitButton>
                        <p className="text-center text-xs text-ink-500">
                            Didn't get it?{' '}
                            {wait > 0 ? (
                                <span className="font-semibold text-ink-400 tabular-nums">
                                    Resend in {Math.floor(wait / 60)}:
                                    {String(wait % 60).padStart(2, '0')}
                                </span>
                            ) : (
                                <button
                                    type="button"
                                    onClick={resend}
                                    className={authLinkClasses}
                                >
                                    Resend
                                </button>
                            )}
                            {extra}
                        </p>
                    </>
                );
            }}
        </Form>
    );
}

function EmailStep({ firstName, email, emailResendAt }: Props) {
    const send = () =>
        router.post(
            OnboardingController.sendEmailCode.url(),
            {},
            { preserveScroll: true },
        );

    return (
        <>
            <StepIntro icon={Mail} title={`Hi ${firstName}, check your email`}>
                Code sent to{' '}
                <span className="font-semibold text-ink-700">{email}</span>
            </StepIntro>
            <CodeForm
                action={OnboardingController.verifyEmail.form()}
                resend={send}
                resendAt={emailResendAt}
            />
        </>
    );
}

const MAX_UPLOAD_BYTES = 5 * 1024 * 1024;

function FileTile({
    name,
    title,
    hint,
    accept,
    error,
    optional = false,
}: {
    name: string;
    title: string;
    hint: string;
    accept: string;
    error?: string;
    optional?: boolean;
}) {
    const [fileName, setFileName] = useState<string | null>(null);
    const [localError, setLocalError] = useState<string | null>(null);
    const shownError = localError ?? error;
    const allowed = accept.split(',').map((type) => type.trim().slice(1));

    const pick = (input: HTMLInputElement) => {
        const file = input.files?.[0];
        const extension = file?.name.split('.').pop()?.toLowerCase() ?? '';
        const problem = !file
            ? null
            : !allowed.includes(extension) || file.name.split('.').length > 2
              ? `Upload ${hint.replaceAll(',', ' or')} only`
              : file.size > MAX_UPLOAD_BYTES
                ? 'Must be 5 MB or smaller'
                : null;

        if (problem) {
            input.value = '';
        }

        setLocalError(problem);
        setFileName(problem ? null : (file?.name ?? null));
    };

    return (
        <label
            className={cn(
                'flex cursor-pointer flex-col items-center gap-1 rounded-landing border border-dashed px-2 py-3 text-center transition-colors focus-within:ring-3 focus-within:ring-brand/15',
                fileName
                    ? 'border-highlight/50 bg-highlight-faint'
                    : 'border-surface-200 bg-surface-50 hover:border-brand/40',
                shownError && 'border-red-300 bg-red-50',
            )}
        >
            <input
                id={name}
                name={name}
                type="file"
                accept={accept}
                className="sr-only"
                aria-invalid={shownError ? true : undefined}
                onChange={(event) => pick(event.currentTarget)}
            />
            {fileName ? (
                <Check className="size-5 text-highlight-dark" />
            ) : (
                <Upload className="size-5 text-ink-400" />
            )}
            <span className="text-xs font-semibold text-ink">
                {title}
                {!optional && <span className="text-red-600"> *</span>}
            </span>
            <span
                className={cn(
                    'w-full truncate text-[11px]',
                    localError ? 'text-red-600' : 'text-ink-400',
                )}
            >
                {localError ??
                    fileName ??
                    (optional ? `${hint} · optional` : hint)}
            </span>
        </label>
    );
}

function IdentityStep({
    identityDocumentTypes,
    identityRejected,
    phone,
}: Props) {
    const [idType, setIdType] = useState<'nin' | 'bvn'>('nin');

    return (
        <>
            <StepIntro icon={Fingerprint} title="Verify your identity">
                Checked by our team within a working day
            </StepIntro>
            {identityRejected && (
                <p className="mb-3 rounded-landing border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700">
                    Earlier documents were not accepted. Please upload clear
                    copies.
                </p>
            )}
            <Form
                {...OnboardingController.storeIdentity.form()}
                className="flex flex-col gap-3"
            >
                {({ processing, errors }) => {
                    const fileError =
                        errors.document_type ??
                        errors.document ??
                        errors.photo ??
                        errors.address_proof;

                    return (
                        <>
                            <div
                                role="radiogroup"
                                aria-label="ID number type"
                                className="grid grid-cols-2 rounded-full bg-surface-100 p-1 text-sm font-semibold"
                            >
                                {(['nin', 'bvn'] as const).map((type) => (
                                    <label
                                        key={type}
                                        className={cn(
                                            'cursor-pointer rounded-full py-1.5 text-center transition-colors',
                                            idType === type
                                                ? 'bg-white text-ink shadow-landing-sm'
                                                : 'text-ink-500 hover:text-ink',
                                        )}
                                    >
                                        <input
                                            type="radio"
                                            name="id_number_type"
                                            value={type}
                                            checked={idType === type}
                                            onChange={() => setIdType(type)}
                                            className="sr-only"
                                        />
                                        {type.toUpperCase()}
                                    </label>
                                ))}
                            </div>
                            <div className="grid grid-cols-2 gap-2">
                                <AuthField
                                    id="id_number"
                                    label={idType.toUpperCase()}
                                    error={
                                        errors.id_number ??
                                        errors.id_number_type
                                    }
                                    required
                                >
                                    <input
                                        id="id_number"
                                        name="id_number"
                                        inputMode="numeric"
                                        maxLength={11}
                                        placeholder="11 digits"
                                        className={authInputClasses}
                                        onInput={(event) => {
                                            event.currentTarget.value =
                                                digitsOnly(
                                                    event.currentTarget.value,
                                                    11,
                                                );
                                        }}
                                        {...errorAttributes(
                                            'id_number',
                                            errors.id_number,
                                        )}
                                    />
                                </AuthField>
                                <AuthField
                                    id="date_of_birth"
                                    label="Date of birth"
                                    error={errors.date_of_birth}
                                    required
                                >
                                    <input
                                        id="date_of_birth"
                                        name="date_of_birth"
                                        type="date"
                                        className={authInputClasses}
                                        {...errorAttributes(
                                            'date_of_birth',
                                            errors.date_of_birth,
                                        )}
                                    />
                                </AuthField>
                            </div>
                            <AuthField
                                id="phone"
                                label="Phone number"
                                error={errors.phone}
                                required
                            >
                                <input
                                    id="phone"
                                    name="phone"
                                    type="tel"
                                    inputMode="numeric"
                                    autoComplete="tel"
                                    maxLength={11}
                                    required
                                    placeholder="08012345678"
                                    defaultValue={digitsOnly(
                                        (phone ?? '').replace(/^\+234/, '0'),
                                        11,
                                    )}
                                    className={authInputClasses}
                                    onInput={(event) => {
                                        const raw =
                                            event.currentTarget.value.replace(
                                                /[\s-]/g,
                                                '',
                                            );
                                        event.currentTarget.value = digitsOnly(
                                            raw.startsWith('+234')
                                                ? `0${raw.slice(4)}`
                                                : raw,
                                            11,
                                        );
                                    }}
                                    {...errorAttributes('phone', errors.phone)}
                                />
                            </AuthField>
                            <div className="flex items-center justify-between gap-2">
                                <span className="text-sm font-semibold text-ink">
                                    Documents
                                </span>
                                <select
                                    name="document_type"
                                    aria-label="ID document type"
                                    defaultValue={
                                        identityDocumentTypes[0]?.value
                                    }
                                    className="max-w-[60%] truncate rounded-full border border-surface-200 bg-white px-3 py-1 text-xs font-semibold text-ink-700 outline-none focus-visible:border-brand"
                                >
                                    {identityDocumentTypes.map((type) => (
                                        <option
                                            key={type.value}
                                            value={type.value}
                                        >
                                            {type.label}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className="grid grid-cols-3 gap-2">
                                <FileTile
                                    name="document"
                                    title="ID"
                                    hint="JPG, PNG, PDF"
                                    accept=".jpg,.jpeg,.png,.pdf"
                                    error={errors.document}
                                />
                                <FileTile
                                    name="photo"
                                    title="Photo"
                                    hint="JPG, PNG"
                                    accept=".jpg,.jpeg,.png"
                                    error={errors.photo}
                                />
                                <FileTile
                                    name="address_proof"
                                    title="Address"
                                    hint="JPG, PNG, PDF"
                                    accept=".jpg,.jpeg,.png,.pdf"
                                    error={errors.address_proof}
                                    optional
                                />
                            </div>
                            {fileError && (
                                <p className="-mt-1 text-sm text-red-600">
                                    {fileError}
                                </p>
                            )}
                            <AuthSubmitButton processing={processing}>
                                Submit for review
                            </AuthSubmitButton>
                            <p className="text-center text-[11px] text-ink-400">
                                Stored privately · only verification officers
                                can view
                            </p>
                        </>
                    );
                }}
            </Form>
        </>
    );
}

function PinStep() {
    const [pin, setPin] = useState('');
    const [repeat, setRepeat] = useState('');

    return (
        <>
            <StepIntro icon={KeyRound} title="Set your transaction PIN">
                Used to approve payments · keep it secret
            </StepIntro>
            <Form
                {...OnboardingController.storePin.form()}
                className="flex flex-col gap-3"
                onError={() => {
                    setPin('');
                    setRepeat('');
                }}
            >
                {({ processing, errors }) => (
                    <>
                        <div className="grid grid-cols-2 gap-2">
                            <input
                                id="pin"
                                name="pin"
                                type="password"
                                inputMode="numeric"
                                maxLength={4}
                                autoComplete="new-password"
                                aria-label="New PIN"
                                placeholder="PIN"
                                autoFocus
                                className={codeClasses}
                                value={pin}
                                onChange={(event) =>
                                    setPin(digitsOnly(event.target.value, 4))
                                }
                                {...errorAttributes('pin', errors.pin)}
                            />
                            <input
                                id="pin_confirmation"
                                name="pin_confirmation"
                                type="password"
                                inputMode="numeric"
                                maxLength={4}
                                autoComplete="new-password"
                                aria-label="Repeat PIN"
                                placeholder="Repeat"
                                className={codeClasses}
                                value={repeat}
                                onChange={(event) =>
                                    setRepeat(digitsOnly(event.target.value, 4))
                                }
                            />
                        </div>
                        {errors.pin && (
                            <p
                                id="pin-error"
                                className="-mt-1 text-sm text-red-600"
                            >
                                {errors.pin}
                            </p>
                        )}
                        <AuthSubmitButton
                            processing={processing}
                            disabled={pin.length !== 4 || repeat !== pin}
                        >
                            Save PIN
                        </AuthSubmitButton>
                    </>
                )}
            </Form>
        </>
    );
}

function DoneStep({
    firstName,
    accountNumber,
    kycStatus,
    kycStatusLabel,
}: Props) {
    return (
        <div className="flex flex-col items-center text-center">
            <span className="flex size-12 items-center justify-center rounded-full bg-highlight-faint text-highlight-dark">
                <BadgeCheck className="size-6" />
            </span>
            <h2 className="mt-3 text-lg font-semibold text-ink">
                You're in, {firstName}
            </h2>

            {accountNumber && (
                <div className="mt-4 w-full rounded-landing bg-brand-dark px-4 py-3 text-left text-white">
                    <p className="text-[11px] font-semibold tracking-widest text-white/60 uppercase">
                        Wallet account number
                    </p>
                    <p className="font-mono text-xl font-semibold tracking-wider">
                        {accountNumber}
                    </p>
                </div>
            )}

            <p
                className={cn(
                    'mt-2 w-full rounded-landing px-3 py-2 text-left text-xs',
                    kycStatus === 'verified'
                        ? 'bg-highlight-faint text-ink-700'
                        : 'bg-amber-50 text-amber-900',
                )}
            >
                <span className="font-semibold">
                    Identity: {kycStatusLabel}.
                </span>{' '}
                {kycStatus === 'verified'
                    ? 'Everything is open to you.'
                    : 'Payments and loans unlock once approved.'}
            </p>

            <Link
                href={dashboard()}
                className="mt-4 inline-flex h-11 w-full items-center justify-center gap-2 rounded-full bg-brand px-5 text-[15px] font-semibold text-white shadow-landing-sm transition-colors hover:bg-brand-hover"
            >
                Go to dashboard
                <ArrowRight className="size-4" />
            </Link>
        </div>
    );
}

Onboarding.layout = {
    title: 'Verify your account',
};
