import { DeleteUser } from '@admin/components/settings/delete-user';
import { SettingsLayout } from '@admin/components/settings/settings-layout';
import { FileUploadInput } from '@admin/components/ui/forms/file-upload-input';
import { FormGroup } from '@admin/components/ui/forms/form-group';
import { formClassName } from '@admin/components/ui/field-styles';
import { UserAvatar } from '@admin/components/ui/user-avatar';
import { useFormResponse } from '@admin/hooks/use-form-response';
import { dashboardPersistentLayout } from '@admin/layouts/dashboard-page-layout';
import { userPhotoUrl } from '@admin/lib/user-avatar-url';
import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { FormEventHandler } from 'react';

type ProfilePageProps = {
    mustVerifyEmail: boolean;
    status?: string;
    profile: {
        name: string;
        email: string;
        photo: string | null;
    };
};

function Profile({ mustVerifyEmail, status, profile }: ProfilePageProps) {
    const { auth } = usePage().props as { auth: { user: { email_verified_at: string | null } } };

    const { data, setData, patch, errors, processing } = useForm({
        name: profile.name,
        email: profile.email,
        photo: profile.photo ?? '',
    });

    const action = useFormResponse({ loadingMessage: 'Saving profile...' });

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

        patch(route('profile.update'), {
            onStart: action.onStart,
            onSuccess: action.onSuccess,
            onError: action.onError,
            preserveScroll: true,
        });
    };

    const previewUrl = userPhotoUrl({ name: data.name, photo: data.photo }) ?? '';

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

            <SettingsLayout>
                <div className="space-y-6">
                    <div>
                        <h4 className="text-lg font-semibold text-gray-800 dark:text-white">Profile</h4>
                        <p className="text-sm text-gray-500 dark:text-white/70">
                            Update your photo, name, and email. Change your password from the Password tab.
                        </p>
                    </div>

                    <div className="flex items-center gap-4">
                        <UserAvatar user={{ name: data.name, photo: data.photo }} size="lg" />
                        <div className="text-sm text-gray-500 dark:text-white/70">
                            Your photo appears in the top bar when set; otherwise your initials are shown.
                        </div>
                    </div>

                    <form onSubmit={submit} className={formClassName}>
                        <FileUploadInput
                            label="Profile photo"
                            inputId="profile-photo"
                            buttonText="Choose photo"
                            uploadUrl={route('profile.upload-photo')}
                            accept="image/jpeg,image/png,image/jpg,image/gif,image/webp"
                            previewUrl={previewUrl}
                            error={errors.photo}
                            onSuccess={(filename) => setData('photo', filename)}
                        />

                        <FormGroup
                            label="Name"
                            error={errors.name}
                            inputProps={{
                                value: data.name,
                                onChange: (event) => setData('name', event.target.value),
                                required: true,
                                autoComplete: 'name',
                            }}
                        />

                        <FormGroup
                            label="Email address"
                            error={errors.email}
                            inputProps={{
                                type: 'email',
                                value: data.email,
                                onChange: (event) => setData('email', event.target.value),
                                required: true,
                                autoComplete: 'username',
                            }}
                        />

                        {mustVerifyEmail && auth.user.email_verified_at === null && (
                            <p className="text-sm text-gray-600 dark:text-white/70">
                                Your email address is unverified.{' '}
                                <Link
                                    href={route('verification.send')}
                                    method="post"
                                    as="button"
                                    className="text-primary underline"
                                >
                                    Click here to re-send the verification email.
                                </Link>
                                {status === 'verification-link-sent' && (
                                    <span className="mt-2 block text-success">
                                        A new verification link has been sent to your email address.
                                    </span>
                                )}
                            </p>
                        )}

                        <button type="submit" className="ti-btn ti-btn-primary" disabled={processing}>
                            Save changes
                        </button>
                    </form>

                    <DeleteUser />
                </div>
            </SettingsLayout>
        </>
    );
}

export default Object.assign(Profile, {
    layout: dashboardPersistentLayout('Profile', 'Your account'),
});
