import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { MapPin, RefreshCw, Check } from 'lucide-react';

type Member = { id: number; name: string; email: string };
type Location = { id: number; name: string; city: string | null; state: string | null; is_active: boolean; users: Member[] };

export default function Locations() {
    const props = usePage().props as unknown as { locations: Location[]; members: Member[] };
    const { locations, members } = props;
    const [editing, setEditing] = useState<number | null>(null);
    const [selected, setSelected] = useState<number[]>([]);

    const openFor = (userId: number) => {
        setEditing(userId);
        setSelected(locations.filter((l) => l.users.some((u) => u.id === userId)).map((l) => l.id));
    };

    const save = (userId: number) =>
        router.post(`/admin/locations/assign/${userId}`, { location_ids: selected }, {
            preserveScroll: true, onSuccess: () => setEditing(null),
        });

    return (
        <>
            <Head title="Locations" />
            <div className="mx-auto w-full max-w-4xl px-6 py-8">
                <header className="mb-6 flex items-start justify-between">
                    <div>
                        <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
                            <MapPin className="size-5 text-primary" /> Locations
                        </h1>
                        <p className="mt-1 text-sm text-muted-foreground">
                            Tag people to the locations they can see. Admins and owners see everything.
                        </p>
                    </div>
                    <button onClick={() => router.post('/admin/locations/sync', {}, { preserveScroll: true })}
                        className="inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-sm font-medium hover:bg-muted">
                        <RefreshCw className="size-3.5" /> Sync from Rentec
                    </button>
                </header>

                <section className="mb-8">
                    <h2 className="mb-3 text-sm font-medium text-muted-foreground">Locations ({locations.length})</h2>
                    <div className="grid gap-2 sm:grid-cols-2">
                        {locations.map((l) => (
                            <div key={l.id} className="rounded-xl border border-border bg-card p-4">
                                <p className="font-medium text-foreground">{l.name}</p>
                                <p className="text-xs text-muted-foreground">
                                    {[l.city, l.state].filter(Boolean).join(', ') || '—'} · {l.users.length} assigned
                                </p>
                            </div>
                        ))}
                        {locations.length === 0 && (
                            <p className="col-span-2 rounded-xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
                                No locations yet. Sync from Rentec above.
                            </p>
                        )}
                    </div>
                </section>

                <section>
                    <h2 className="mb-3 text-sm font-medium text-muted-foreground">People</h2>
                    <div className="space-y-2">
                        {members.map((m) => {
                            const theirs = locations.filter((l) => l.users.some((u) => u.id === m.id));
                            const isEditing = editing === m.id;

                            return (
                                <div key={m.id} className="rounded-xl border border-border bg-card p-4">
                                    <div className="flex items-start justify-between">
                                        <div>
                                            <p className="font-medium text-foreground">{m.name}</p>
                                            <p className="text-xs text-muted-foreground">{m.email}</p>
                                            {!isEditing && (
                                                <p className="mt-1 text-xs text-muted-foreground">
                                                    {theirs.length === 0 ? 'No locations assigned' : theirs.map((l) => l.name).join(', ')}
                                                </p>
                                            )}
                                        </div>
                                        {isEditing ? (
                                            <div className="flex gap-2">
                                                <button onClick={() => setEditing(null)} className="rounded-md border border-border px-3 py-1.5 text-xs hover:bg-muted">Cancel</button>
                                                <button onClick={() => save(m.id)} className="inline-flex items-center gap-1 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:opacity-90">
                                                    <Check className="size-3.5" /> Save
                                                </button>
                                            </div>
                                        ) : (
                                            <button onClick={() => openFor(m.id)} className="rounded-md border border-border px-3 py-1.5 text-xs font-medium hover:bg-muted">
                                                Edit access
                                            </button>
                                        )}
                                    </div>

                                    {isEditing && (
                                        <div className="mt-3 flex flex-wrap gap-1.5 border-t border-border pt-3">
                                            {locations.map((l) => {
                                                const on = selected.includes(l.id);
                                                return (
                                                    <button key={l.id}
                                                        onClick={() => setSelected(on ? selected.filter((x) => x !== l.id) : [...selected, l.id])}
                                                        className={`rounded-full border px-2.5 py-1 text-xs transition ${on ? 'border-primary bg-primary text-primary-foreground' : 'border-border hover:bg-muted'}`}>
                                                        {l.name}
                                                    </button>
                                                );
                                            })}
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                </section>
            </div>
        </>
    );
}
