import { type BreadcrumbItem, type SharedData } from '@/types';
import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { FormEventHandler } from 'react';

import { ClientCustomFieldsSection, type CustomFieldDefinition } from '@/components/client-custom-fields-section';
import HeadingSmall from '@/components/heading-small';
import InputError from '@/components/input-error';
import { SaveButton } from '@/components/save-button';
import { StartPageSelect, type StartPageOption } from '@/components/start-page-select';
import { TimezonePicker, type TimezoneOption } from '@/components/timezone-picker';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useTranslation } from '@/hooks/use-translation';
import AppLayout from '@/layouts/app-layout';
import SettingsLayout from '@/layouts/settings/layout';

export default function Profile({
    mustVerifyEmail,
    status,
    custom_fields,
    custom_field_values,
    timezone,
    timezones,
    start_page,
    start_page_options,
    role_start_page,
}: {
    mustVerifyEmail: boolean;
    status?: string;
    custom_fields: CustomFieldDefinition[];
    custom_field_values: Record<string, string>;
    timezone: string;
    timezones: TimezoneOption[];
    start_page: string | null;
    start_page_options: StartPageOption[];
    /** The page this person lands on when they choose nothing, already translated. */
    role_start_page: string;
}) {
    const { t } = useTranslation();
    const { auth } = usePage<SharedData>().props;

    const breadcrumbs: BreadcrumbItem[] = [
        {
            title: t('Profile settings'),
            href: '/settings/profile',
        },
    ];

    const { data, setData, patch, errors, processing, recentlySuccessful } = useForm({
        name: auth.user.name,
        email: auth.user.email,
        custom_field_values,
        timezone,
        start_page,
        current_password: '',
    });

    // Changing this address is a credential change: it is where a password
    // reset is sent. So the field appears only when the address actually
    // differs from the stored one — the rest of the screen keeps saving
    // with nothing extra, which is what the server asks for too.
    const emailChanged = data.email.trim().toLowerCase() !== auth.user.email.trim().toLowerCase();

    const submit: FormEventHandler = (e) => {
        e.preventDefault();

        patch(route('profile.update'));
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={t('Profile settings')} />

            <SettingsLayout>
                <div className="space-y-6">
                    <HeadingSmall title={t('Profile information')} description={t('Update your name and email address')} />

                    <form onSubmit={submit} className="space-y-6">
                        <div className="grid gap-2">
                            <Label htmlFor="name">{t('Name')}</Label>

                            <Input
                                id="name"
                                className="mt-1 block w-full"
                                value={data.name}
                                onChange={(e) => setData('name', e.target.value)}
                                required
                                autoComplete="name"
                                placeholder={t('Full name')}
                            />

                            <InputError className="mt-2" message={errors.name} />
                        </div>

                        <div className="grid gap-2">
                            <Label htmlFor="email">{t('Email address')}</Label>

                            <Input
                                id="email"
                                type="email"
                                className="mt-1 block w-full"
                                value={data.email}
                                onChange={(e) => setData('email', e.target.value)}
                                required
                                autoComplete="username"
                                placeholder={t('Email address')}
                            />

                            <InputError className="mt-2" message={errors.email} />
                        </div>

                        {/* An account with no password here confirms through its
                            provider instead: saving opens that dialog. */}
                        {emailChanged && !auth.has_password && (
                            <p className="text-muted-foreground text-sm">
                                {t('A password reset goes to this address, so saving asks you to confirm it is you first.')}
                            </p>
                        )}

                        {emailChanged && auth.has_password && (
                            <div className="grid gap-2">
                                <Label htmlFor="current_password">{t('Current password')}</Label>

                                <Input
                                    id="current_password"
                                    type="password"
                                    className="mt-1 block w-full"
                                    value={data.current_password}
                                    onChange={(e) => setData('current_password', e.target.value)}
                                    required
                                    autoComplete="current-password"
                                />

                                <p className="text-muted-foreground text-sm">
                                    {t('A password reset goes to this address, so changing it needs your password.')}
                                </p>

                                <InputError className="mt-2" message={errors.current_password} />
                            </div>
                        )}

                        <div className="grid gap-2">
                            <Label htmlFor="timezone">{t('Timezone')}</Label>

                            <TimezonePicker options={timezones} value={data.timezone} onChange={(tz) => setData('timezone', tz)} />

                            <p className="text-muted-foreground text-sm">
                                {t('Dates and times across the app are shown in this zone. Detected from your browser the first time you signed in.')}
                            </p>

                            <InputError className="mt-2" message={errors.timezone} />
                        </div>

                        <StartPageSelect
                            value={data.start_page}
                            onChange={(value) => setData('start_page', value)}
                            options={start_page_options}
                            inheritLabel={t('Default (:page)', { page: role_start_page })}
                            error={errors.start_page}
                            description={t('The page you land on after signing in.')}
                        />

                        <ClientCustomFieldsSection
                            fields={custom_fields}
                            values={data.custom_field_values}
                            onChange={(fieldId, value) => setData('custom_field_values', { ...data.custom_field_values, [fieldId]: value })}
                            errors={errors}
                        />

                        {mustVerifyEmail && auth.user.email_verified_at === null && (
                            <div>
                                <p className="mt-2 text-sm text-neutral-800">
                                    {t('Your email address is unverified.')}
                                    <Link
                                        href={route('verification.send')}
                                        method="post"
                                        as="button"
                                        className="rounded-md text-sm text-neutral-600 underline hover:text-neutral-900 focus:ring-2 focus:ring-offset-2 focus:outline-hidden"
                                    >
                                        {t('Click here to re-send the verification email.')}
                                    </Link>
                                </p>

                                {status === 'verification-link-sent' && (
                                    <div className="mt-2 text-sm font-medium text-green-600">
                                        {t('A new verification link has been sent to your email address.')}
                                    </div>
                                )}
                            </div>
                        )}

                        <SaveButton processing={processing} recentlySuccessful={recentlySuccessful} />
                    </form>
                </div>
            </SettingsLayout>
        </AppLayout>
    );
}
