import { Form, Head } from '@inertiajs/react';
import { Check, ShieldCheck } from 'lucide-react';
import { useState } from 'react';
import TransactionPinController from '@/actions/App/Http/Controllers/Settings/TransactionPinController';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import PasswordInput from '@/components/password-input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { edit } from '@/routes/transaction-pin';

/** Mirrors TransactionPinUpdateRequest::WEAK_PINS. */
const WEAK_PINS = ['1234', '4321', '0123', '9876', '1212', '1122', '2580'];

const PIN_LENGTH = 4;

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

function isWeak(pin: string): boolean {
    return WEAK_PINS.includes(pin) || new Set(pin).size === 1;
}

function PinField({
    id,
    label,
    value,
    onChange,
    error,
    autoFocus = false,
}: {
    id: string;
    label: string;
    value: string;
    onChange: (value: string) => void;
    error?: string;
    autoFocus?: boolean;
}) {
    return (
        <div className="grid content-start gap-2">
            <Label htmlFor={id} required>
                {label}
            </Label>
            <PasswordInput
                id={id}
                name={id}
                inputMode="numeric"
                pattern="[0-9]{4}"
                maxLength={PIN_LENGTH}
                autoComplete="off"
                required
                autoFocus={autoFocus}
                value={value}
                onChange={(event) => onChange(digitsOnly(event.target.value))}
                aria-invalid={error ? true : undefined}
                className="mt-1 block w-full text-center font-mono text-lg tracking-[0.5em]"
                placeholder="••••"
            />
            <InputError message={error} />
        </div>
    );
}

export default function TransactionPin({ hasPin }: { hasPin: boolean }) {
    const [current, setCurrent] = useState('');
    const [pin, setPin] = useState('');
    const [confirmation, setConfirmation] = useState('');
    const [saved, setSaved] = useState(false);

    const reset = () => {
        setCurrent('');
        setPin('');
        setConfirmation('');
    };

    const pinComplete = pin.length === PIN_LENGTH;
    const weak = pinComplete && isWeak(pin);
    const mismatch = confirmation.length === PIN_LENGTH && confirmation !== pin;
    const sameAsCurrent = hasPin && pinComplete && pin === current;
    const ready =
        (hasPin ? current.length === PIN_LENGTH : current.length > 0) &&
        pinComplete &&
        confirmation === pin &&
        !weak &&
        !sameAsCurrent;

    return (
        <>
            <Head title="Transaction PIN" />

            <h1 className="sr-only">Transaction PIN</h1>

            <div className="space-y-6">
                <Heading
                    variant="small"
                    title="Transaction PIN"
                    description={
                        hasPin
                            ? 'Change the 4-digit PIN you use to approve transfers and payments'
                            : 'Set a 4-digit PIN to approve transfers and payments'
                    }
                />

                <div className="flex items-start gap-3 rounded-lg border border-highlight/30 bg-highlight-faint px-4 py-3 text-sm text-ink-700">
                    <ShieldCheck className="mt-0.5 size-4 shrink-0 text-highlight" />
                    <p>
                        Never share your PIN. Our staff will never ask for it.
                        After 5 wrong attempts, PIN use is paused for 15
                        minutes.
                    </p>
                </div>

                <Form
                    {...TransactionPinController.update.form()}
                    options={{ preserveScroll: true }}
                    onStart={() => setSaved(false)}
                    onSuccess={() => {
                        reset();
                        setSaved(true);
                    }}
                    onError={reset}
                    className="space-y-6"
                >
                    {({ processing, errors }) => (
                        <>
                            {hasPin ? (
                                <div className="sm:max-w-[calc(50%-0.5rem)]">
                                    <PinField
                                        id="current_pin"
                                        label="Current PIN"
                                        value={current}
                                        onChange={setCurrent}
                                        error={errors.current_pin}
                                        autoFocus
                                    />
                                </div>
                            ) : (
                                <div className="grid gap-2">
                                    <Label htmlFor="current_password" required>
                                        Account password
                                    </Label>
                                    <PasswordInput
                                        id="current_password"
                                        name="current_password"
                                        autoComplete="current-password"
                                        required
                                        autoFocus
                                        value={current}
                                        onChange={(event) =>
                                            setCurrent(event.target.value)
                                        }
                                        className="mt-1 block w-full"
                                        placeholder="Confirm it's you"
                                    />
                                    <InputError
                                        message={errors.current_password}
                                    />
                                </div>
                            )}

                            <div className="grid gap-4 sm:grid-cols-2">
                                <PinField
                                    id="pin"
                                    label={hasPin ? 'New PIN' : 'PIN'}
                                    value={pin}
                                    onChange={setPin}
                                    error={
                                        errors.pin ??
                                        (weak
                                            ? 'Too easy to guess — avoid sequences and repeated digits.'
                                            : sameAsCurrent
                                              ? 'Choose a PIN different from your current one.'
                                              : undefined)
                                    }
                                />
                                <PinField
                                    id="pin_confirmation"
                                    label={
                                        hasPin
                                            ? 'Confirm new PIN'
                                            : 'Confirm PIN'
                                    }
                                    value={confirmation}
                                    onChange={setConfirmation}
                                    error={
                                        mismatch
                                            ? "PINs don't match."
                                            : undefined
                                    }
                                />
                            </div>

                            <div className="flex items-center gap-4">
                                <Button
                                    disabled={processing || !ready}
                                    data-test="update-pin-button"
                                >
                                    {hasPin ? 'Change PIN' : 'Set PIN'}
                                </Button>
                                {saved && (
                                    <p className="flex items-center gap-1.5 text-sm text-highlight-dark">
                                        <Check className="size-4" />
                                        {hasPin ? 'PIN updated' : 'PIN set'}
                                    </p>
                                )}
                            </div>
                        </>
                    )}
                </Form>
            </div>
        </>
    );
}

TransactionPin.layout = {
    breadcrumbs: [{ title: 'Transaction PIN', href: edit() }],
};
