import { Form, Head, usePage } from '@inertiajs/react';
import { useMemo, useRef } from 'react';
import SecurityController from '@/actions/App/Http/Controllers/Settings/SecurityController';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import PasswordInput from '@/components/password-input';
import {
    SettingsSectionNav,
    ShowSectionWithError,
    useSettingsSections,
} from '@/components/settings-sections';
import type { SettingsSection } from '@/components/settings-sections';
import TwoFactorSettings from '@/components/two-factor-settings';
import { formatDateTime } from '@/lib/format';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { edit } from '@/routes/security';

// oxfmt-ignore
type Props = {
    passwordRules: string;
    canManageTwoFactor: boolean;
    twoFactorEnabled?: boolean;
    twoFactorPending?: boolean;
    twoFactorRequired?: boolean;
    recentSignIns: {
        id: number;
        event: string;
        ipAddress: string | null;
        device: string | null;
        at: string | null;
    }[];
};

type Section = 'password' | 'two-factor' | 'sign-ins';

const passwordFields = [
    'current_password',
    'password',
    'password_confirmation',
];

function fieldSection(field: string): Section | undefined {
    return passwordFields.includes(field) ? 'password' : undefined;
}

export default function Security(props: Props) {
    const { errors: pageErrors } = usePage<{
        errors: Record<string, string | undefined>;
    }>().props;

    const sectionList = useMemo(() => {
        const list: SettingsSection<Section>[] = [
            {
                id: 'password',
                label: 'Password',
                description: 'Change the password you sign in with',
            },
        ];

        if (props.canManageTwoFactor) {
            list.push({
                id: 'two-factor',
                label: 'Two-factor sign-in',
                description: 'A code from your phone as well as your password',
            });
        }

        list.push({
            id: 'sign-ins',
            label: 'Recent sign-ins',
            description: 'Where and when your account was used',
        });

        return list;
    }, [props.canManageTwoFactor]);

    const sections = useSettingsSections(sectionList);

    const passwordInput = useRef<HTMLInputElement>(null);
    const currentPasswordInput = useRef<HTMLInputElement>(null);

    return (
        <>
            <Head title="Security settings" />

            <h1 className="sr-only">Security settings</h1>

            <div className="space-y-6">
                <ShowSectionWithError
                    errors={pageErrors}
                    fieldSection={fieldSection}
                    show={sections.show}
                />

                <SettingsSectionNav
                    sections={sectionList}
                    state={sections}
                    label="Security sections"
                    hasError={(id) =>
                        Object.keys(pageErrors).some(
                            (field) => fieldSection(field) === id,
                        )
                    }
                />

                <section
                    role="tabpanel"
                    id="panel-password"
                    aria-labelledby="tab-password"
                    className={sections.panelClass('password', 'space-y-6')}
                >
                    <Heading
                        variant="small"
                        title="Update password"
                        description="Ensure your account is using a long, random password to stay secure"
                    />

                    <Form
                        {...SecurityController.update.form()}
                        options={{
                            preserveScroll: true,
                        }}
                        resetOnError={[
                            'password',
                            'password_confirmation',
                            'current_password',
                        ]}
                        resetOnSuccess
                        onError={(errors) => {
                            if (errors.password) {
                                passwordInput.current?.focus();
                            }

                            if (errors.current_password) {
                                currentPasswordInput.current?.focus();
                            }
                        }}
                        className="space-y-6"
                    >
                        {({ errors, processing }) => (
                            <>
                                <div className="grid gap-2">
                                    <Label htmlFor="current_password" required>
                                        Current password
                                    </Label>

                                    <PasswordInput
                                        id="current_password"
                                        ref={currentPasswordInput}
                                        name="current_password"
                                        className="mt-1 block w-full"
                                        autoComplete="current-password"
                                        placeholder="Current password"
                                    />

                                    <InputError
                                        message={errors.current_password}
                                    />
                                </div>

                                <div className="grid gap-2">
                                    <Label htmlFor="password" required>
                                        New password
                                    </Label>

                                    <PasswordInput
                                        id="password"
                                        ref={passwordInput}
                                        name="password"
                                        className="mt-1 block w-full"
                                        autoComplete="new-password"
                                        placeholder="New password"
                                        passwordrules={props.passwordRules}
                                    />

                                    <InputError message={errors.password} />
                                </div>

                                <div className="grid gap-2">
                                    <Label
                                        htmlFor="password_confirmation"
                                        required
                                    >
                                        Confirm password
                                    </Label>

                                    <PasswordInput
                                        id="password_confirmation"
                                        name="password_confirmation"
                                        className="mt-1 block w-full"
                                        autoComplete="new-password"
                                        placeholder="Confirm password"
                                        passwordrules={props.passwordRules}
                                    />

                                    <InputError
                                        message={errors.password_confirmation}
                                    />
                                </div>

                                <div className="flex items-center gap-4">
                                    <Button
                                        disabled={processing}
                                        data-test="update-password-button"
                                    >
                                        Save
                                    </Button>
                                </div>
                            </>
                        )}
                    </Form>
                </section>

                {props.canManageTwoFactor && (
                    <section
                        role="tabpanel"
                        id="panel-two-factor"
                        aria-labelledby="tab-two-factor"
                        className={sections.panelClass('two-factor')}
                    >
                        <TwoFactorSettings
                            enabled={props.twoFactorEnabled ?? false}
                            pending={props.twoFactorPending ?? false}
                            required={props.twoFactorRequired ?? false}
                        />
                    </section>
                )}

                <section
                    role="tabpanel"
                    id="panel-sign-ins"
                    aria-labelledby="tab-sign-ins"
                    className={sections.panelClass('sign-ins', 'space-y-3')}
                >
                    <Heading
                        variant="small"
                        title="Recent sign-ins"
                        description="If you do not recognise one, change your password straight away."
                    />
                    <ul className="divide-y rounded-md border text-sm">
                        {props.recentSignIns.length === 0 && (
                            <li className="p-3 text-muted-foreground">
                                No sign-ins recorded yet.
                            </li>
                        )}
                        {props.recentSignIns.map((signIn) => (
                            <li
                                key={signIn.id}
                                className="flex flex-wrap items-center justify-between gap-2 p-3"
                            >
                                <span>
                                    <span className="font-medium">
                                        {signIn.event === 'failed'
                                            ? 'Failed sign-in'
                                            : signIn.event === 'logout'
                                              ? 'Signed out'
                                              : 'Signed in'}
                                    </span>{' '}
                                    <span className="text-muted-foreground">
                                        · {signIn.device ?? 'Unknown device'} ·{' '}
                                        {signIn.ipAddress ?? '—'}
                                    </span>
                                </span>
                                <span className="text-xs text-muted-foreground">
                                    {formatDateTime(signIn.at)}
                                </span>
                            </li>
                        ))}
                    </ul>
                </section>
            </div>
        </>
    );
}

Security.layout = {
    breadcrumbs: [
        {
            title: 'Security settings',
            href: edit(),
        },
    ],
};
