import { Form, Head, usePage } from '@inertiajs/react';
import ProfileController from '@/actions/App/Http/Controllers/Settings/ProfileController';
import DeleteUser from '@/components/delete-user';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import MemberDetailsFields from '@/components/member/member-details-fields';
import MemberImages from '@/components/member/member-images';
import {
    SettingsSectionNav,
    ShowSectionWithError,
    useSettingsSections,
} from '@/components/settings-sections';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
import { edit } from '@/routes/profile';
import { store as storeImage } from '@/routes/profile/images';
import type { Auth, SelectOption } from '@/types';

type PageProps = {
    auth: Auth;
    errors: Record<string, string | undefined>;
};

type Section = 'details' | 'more' | 'photos' | 'account';

const sectionList: { id: Section; label: string; description: string }[] = [
    {
        id: 'details',
        label: 'Personal details',
        description: 'Name, email, phone, birthday and address',
    },
    {
        id: 'more',
        label: 'About you',
        description: 'Gender, occupation, ID number and next of kin',
    },
    {
        id: 'photos',
        label: 'Photo and signature',
        description: 'Kept privately on your membership record',
    },
    {
        id: 'account',
        label: 'Delete account',
        description: 'Close your account for good',
    },
];

const formSections: Section[] = ['details', 'more'];

/** Which section holds each profile field, so a failed save opens it. */
function fieldSection(field: string): Section | undefined {
    if (
        ['name', 'email', 'phone', 'date_of_birth', 'address'].includes(field)
    ) {
        return 'details';
    }

    if (
        [
            'gender',
            'occupation',
            'id_number',
            'next_of_kin_name',
            'next_of_kin_phone',
            'next_of_kin_relationship',
        ].includes(field)
    ) {
        return 'more';
    }

    return undefined;
}

export default function Profile({ genders }: { genders: SelectOption[] }) {
    const { auth, errors: pageErrors } = usePage<PageProps>().props;
    const sections = useSettingsSections(sectionList);

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

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

            <div className="space-y-6">
                <Heading
                    variant="small"
                    title="Profile"
                    description="Update your personal details"
                />

                <p className="inline-flex items-center gap-2 rounded-landing bg-surface-50 px-3 py-2 text-sm text-ink-500">
                    Membership ID
                    <span className="font-mono font-semibold text-ink">
                        {auth.user.member_id}
                    </span>
                </p>

                <ShowSectionWithError
                    errors={pageErrors}
                    fieldSection={fieldSection}
                    show={sections.show}
                />

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

                <Form
                    {...ProfileController.update.form()}
                    options={{
                        preserveScroll: true,
                    }}
                    className="space-y-6"
                >
                    {({ processing, errors }) => (
                        <>
                            <section
                                role="tabpanel"
                                id="panel-details"
                                aria-labelledby="tab-details"
                                className={sections.panelClass(
                                    'details',
                                    'space-y-6',
                                )}
                            >
                                <div className="grid gap-2">
                                    <Label htmlFor="name" required>
                                        Name
                                    </Label>

                                    <Input
                                        id="name"
                                        className="mt-1 block w-full"
                                        defaultValue={auth.user.name}
                                        name="name"
                                        required
                                        autoComplete="name"
                                        placeholder="Full name"
                                    />

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

                                <div className="grid gap-2">
                                    <Label htmlFor="email" required>
                                        Email address
                                    </Label>

                                    <Input
                                        id="email"
                                        type="email"
                                        className="mt-1 block w-full"
                                        defaultValue={auth.user.email}
                                        name="email"
                                        required
                                        autoComplete="username"
                                        placeholder="Email address"
                                    />

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

                                <div className="grid gap-2">
                                    <Label htmlFor="phone">Phone number</Label>

                                    <Input
                                        id="phone"
                                        type="tel"
                                        className="mt-1 block w-full"
                                        defaultValue={auth.user.phone ?? ''}
                                        name="phone"
                                        autoComplete="tel"
                                        placeholder="08012345678"
                                    />

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

                                <div className="grid gap-2">
                                    <Label htmlFor="date_of_birth">
                                        Date of birth
                                    </Label>

                                    <Input
                                        id="date_of_birth"
                                        type="date"
                                        className="mt-1 block w-full"
                                        defaultValue={
                                            auth.user.date_of_birth ?? ''
                                        }
                                        name="date_of_birth"
                                        autoComplete="bday"
                                    />

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

                                <div className="grid gap-2">
                                    <Label htmlFor="address">
                                        Home address
                                    </Label>

                                    <Input
                                        id="address"
                                        className="mt-1 block w-full"
                                        defaultValue={auth.user.address ?? ''}
                                        name="address"
                                        autoComplete="street-address"
                                        placeholder="Street, town, state"
                                    />

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

                            <section
                                role="tabpanel"
                                id="panel-more"
                                aria-labelledby="tab-more"
                                className={sections.panelClass(
                                    'more',
                                    'space-y-6',
                                )}
                            >
                                <MemberDetailsFields
                                    values={{
                                        gender: auth.user.gender,
                                        occupation: auth.user.occupation,
                                        idNumber: auth.user.id_number,
                                        nextOfKinName:
                                            auth.user.next_of_kin_name,
                                        nextOfKinPhone:
                                            auth.user.next_of_kin_phone,
                                        nextOfKinRelationship:
                                            auth.user.next_of_kin_relationship,
                                    }}
                                    genders={genders}
                                    errors={errors}
                                />
                            </section>

                            <div
                                className={cn(
                                    'flex items-center gap-4',
                                    !formSections.includes(sections.current) &&
                                        'hidden',
                                    sections.hiddenOnList,
                                )}
                            >
                                <Button
                                    disabled={processing}
                                    data-test="update-profile-button"
                                >
                                    Save
                                </Button>
                            </div>
                        </>
                    )}
                </Form>

                <section
                    role="tabpanel"
                    id="panel-photos"
                    aria-labelledby="tab-photos"
                    className={sections.panelClass('photos', 'space-y-3')}
                >
                    <Heading
                        variant="small"
                        title="Photo and signature"
                        description="Kept privately on your membership record. Only you and our staff can see them."
                    />
                    <MemberImages
                        photoUrl={auth.user.avatar}
                        signatureUrl={auth.user.signature_url}
                        uploadUrl={(kind) => storeImage.url(kind)}
                    />
                </section>

                <section
                    role="tabpanel"
                    id="panel-account"
                    aria-labelledby="tab-account"
                    className={sections.panelClass('account')}
                >
                    <DeleteUser />
                </section>
            </div>
        </>
    );
}

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