/* Your own name and PIN. Works for owners, staff and platform admins (each in their own layout). */
import { useForm, usePage } from '@inertiajs/react';
import type { FormEvent, ReactNode } from 'react';
import { KeyRound, UserRound } from 'lucide-react';
import ShopLayout from '../layouts/ShopLayout';
import PlatformLayout from '../layouts/PlatformLayout';
import PinInput from '../components/PinInput';
import { Button, Card, CardHeader, Field, Input, PageHeader, Select } from '../components/ui';
import type { SharedProps } from '../types';

export default function Profile({ profile }: { profile: { name: string; phone: string; email: string; locale: string } }) {
    const { auth } = usePage<SharedProps>().props;
    const admin = auth?.role === 'admin';
    const prefix = admin ? 'platform.' : '';
    const details = useForm({ name: profile.name, email: profile.email, locale: profile.locale });
    const pin = useForm({ current_pin: '', pin: '', pin_confirmation: '' });
    const pinErr = pin.errors as Record<string, string | undefined>;
    const saveDetails = (e: FormEvent) => { e.preventDefault(); details.put(route(`${prefix}profile.update`), { preserveScroll: true }); };
    const savePin = (e: FormEvent) => { e.preventDefault(); pin.put(route(`${prefix}profile.pin`), { preserveScroll: true, onSuccess: () => pin.reset() }); };
    // a stable component (not one made during render), so the fields keep focus while typing
    const Layout: (p: { title: string; children: ReactNode }) => ReactNode = admin ? PlatformLayout : ShopLayout;

    return (
        <Layout title="My profile">
            <PageHeader title="My profile" subtitle={`You sign in with ${profile.phone}.`} />
            <div className="grid gap-4 lg:grid-cols-2">
                <Card>
                    <CardHeader icon={UserRound} title="Your details" />
                    <form onSubmit={saveDetails} className="mt-4 space-y-4" noValidate>
                        <Field label="Name" htmlFor="pr-name" error={details.errors.name}><Input id="pr-name" value={details.data.name} onChange={(e) => details.setData('name', e.target.value)} /></Field>
                        <Field label={<>Email <span className="font-normal text-muted">(optional)</span></>} htmlFor="pr-email" error={details.errors.email}><Input id="pr-email" type="email" value={details.data.email} onChange={(e) => details.setData('email', e.target.value)} /></Field>
                        {!admin && (
                            <Field label="Language / Chiyankhulo" htmlFor="pr-locale">
                                <Select id="pr-locale" value={details.data.locale} onChange={(e) => details.setData('locale', e.target.value)}>
                                    <option value="">Same as the business</option>
                                    <option value="en">English</option>
                                    <option value="ny">Chichewa</option>
                                </Select>
                            </Field>
                        )}
                        <Button type="submit" disabled={details.processing || !details.isDirty}>Save</Button>
                    </form>
                </Card>
                <Card>
                    <CardHeader icon={KeyRound} title="Change your PIN" />
                    <form onSubmit={savePin} className="mt-4 space-y-4" noValidate>
                        <Field label="Current PIN" htmlFor="pr-cur" error={pinErr.current_pin}><PinInput id="pr-cur" value={pin.data.current_pin} onChange={(v) => pin.setData('current_pin', v)} /></Field>
                        <Field label="New PIN" htmlFor="pr-new" error={pinErr.pin} hint="At least 4 digits."><PinInput id="pr-new" autoComplete="new-password" value={pin.data.pin} onChange={(v) => pin.setData('pin', v)} /></Field>
                        <Field label="New PIN again" htmlFor="pr-new2"><PinInput id="pr-new2" autoComplete="new-password" value={pin.data.pin_confirmation} onChange={(v) => pin.setData('pin_confirmation', v)} allowLetters={false} /></Field>
                        <Button type="submit" disabled={pin.processing}>Change PIN</Button>
                    </form>
                </Card>
            </div>
        </Layout>
    );
}
