/* The owner's staff: add a cashier with their phone and a PIN, turn them off, reset their PIN. */
import { useForm } from '@inertiajs/react';
import { useState, type FormEvent } from 'react';
import { Plus, UserRound, Users } from 'lucide-react';
import ShopLayout from '../../layouts/ShopLayout';
import PinInput from '../../components/PinInput';
import { Avatar, Badge, Button, EmptyState, Field, Input, PageHeader, Toggle } from '../../components/ui';
import { Modal } from '../../components/overlays';
import type { Person } from '../../types';

function AddForm({ onDone }: { onDone: () => void }) {
    const form = useForm({ name: '', phone: '', pin: '' });
    const err = form.errors as Record<string, string | undefined>;
    const submit = (e: FormEvent) => { e.preventDefault(); form.post(route('team.store'), { preserveScroll: true, onSuccess: onDone }); };
    return (
        <form onSubmit={submit} className="space-y-4" noValidate>
            <Field label="Name" htmlFor="t-name" error={err.name} required><Input id="t-name" value={form.data.name} onChange={(e) => form.setData('name', e.target.value)} autoFocus /></Field>
            <Field label="Their phone number" htmlFor="t-phone" error={err.phone_e164 || err.phone} required hint="They sign in with it.">
                <Input id="t-phone" type="tel" inputMode="tel" placeholder="0991 234 567" value={form.data.phone} onChange={(e) => form.setData('phone', e.target.value)} />
            </Field>
            <Field label="Their PIN" htmlFor="t-pin" error={err.pin} required hint="At least 4 digits. Tell them; they can change it later.">
                <PinInput id="t-pin" autoComplete="new-password" value={form.data.pin} onChange={(v) => form.setData('pin', v)} allowLetters={false} />
            </Field>
            <p className="rounded-xl bg-line-2 p-3 text-xs text-ink-2">Staff can record sales and see products and their own sales. They can't see cost prices or profit, cancel sales, or change settings.</p>
            <Button type="submit" size="lg" className="w-full" disabled={form.processing}>{form.processing ? 'Adding…' : 'Add staff member'}</Button>
        </form>
    );
}

function EditForm({ person, onDone }: { person: Person; onDone: () => void }) {
    const form = useForm({ name: person.name, is_active: person.isActive, pin: '' });
    const err = form.errors as Record<string, string | undefined>;
    const submit = (e: FormEvent) => { e.preventDefault(); form.put(route('team.update', { user: person.id }), { preserveScroll: true, onSuccess: onDone }); };
    return (
        <form onSubmit={submit} className="space-y-4" noValidate>
            <Field label="Name" htmlFor="e-name" error={err.name}><Input id="e-name" value={form.data.name} onChange={(e) => form.setData('name', e.target.value)} /></Field>
            <div className="flex items-center justify-between gap-3 rounded-xl border border-line p-3">
                <div><p className="text-sm font-bold text-ink">Can sign in</p><p className="text-xs text-muted">Turn off when someone leaves. Their past sales stay.</p></div>
                <Toggle checked={form.data.is_active} onChange={(v) => form.setData('is_active', v)} label="Can sign in" />
            </div>
            <Field label={<>New PIN <span className="font-normal text-muted">(leave empty to keep)</span></>} htmlFor="e-pin" error={err.pin}>
                <PinInput id="e-pin" autoComplete="new-password" value={form.data.pin} onChange={(v) => form.setData('pin', v)} allowLetters={false} />
            </Field>
            <Button type="submit" size="lg" className="w-full" disabled={form.processing}>{form.processing ? 'Saving…' : 'Save'}</Button>
        </form>
    );
}

export default function Team({ people }: { people: Person[] }) {
    const [adding, setAdding] = useState(false);
    const [editing, setEditing] = useState<Person | null>(null);
    const staff = people.filter((p) => p.role === 'staff');

    return (
        <ShopLayout title="Staff">
            <PageHeader title="Staff" subtitle="People who sell for you, each with their own phone and PIN." actions={<Button icon={Plus} onClick={() => setAdding(true)}>Add staff</Button>} />
            <ul className="divide-y divide-line overflow-hidden rounded-card border border-line bg-white shadow-card">
                {people.map((p) => (
                    <li key={p.id}>
                        <button disabled={p.role === 'owner'} onClick={() => setEditing(p)} className="flex w-full items-center gap-3 px-4 py-3 text-left enabled:hover:bg-line-2/50">
                            <Avatar name={p.name} size="sm" />
                            <div className="min-w-0 flex-1">
                                <p className="truncate text-[15px] font-bold text-ink">{p.name}</p>
                                <p className="truncate text-xs text-muted">{p.phoneLabel}{p.lastLogin ? ` · last in ${p.lastLogin}` : ' · never signed in'}</p>
                            </div>
                            {p.role === 'owner' ? <Badge tone="brand">Owner</Badge> : p.isActive ? <Badge tone="green">Staff</Badge> : <Badge>Turned off</Badge>}
                        </button>
                    </li>
                ))}
            </ul>
            {staff.length === 0 && <EmptyState icon={Users}>No staff yet. Add someone and they can sell from their own phone.</EmptyState>}

            <Modal open={adding} onClose={() => setAdding(false)} title="Add a staff member">{adding && <AddForm onDone={() => setAdding(false)} />}</Modal>
            <Modal open={!!editing} onClose={() => setEditing(null)} title={editing?.name ?? ''} subtitle={editing?.phoneLabel}>
                {editing && <EditForm key={editing.id} person={editing} onDone={() => setEditing(null)} />}
            </Modal>
            <p className="mt-4 flex items-center gap-1.5 text-xs text-muted"><UserRound className="size-3.5" aria-hidden />Change your own PIN under More → My profile and PIN.</p>
        </ShopLayout>
    );
}
