import { Head, Link, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { Building2, Plus, Users } from 'lucide-react';

type Org = { id: number; name: string; slug: string; users: number; pending: number };

export default function OrganizationsIndex() {
    const { organizations } = usePage().props as unknown as { organizations: Org[] };
    const [name, setName] = useState('');

    return (
        <>
            <Head title="Organizations" />
            <div className="mx-auto w-full max-w-5xl px-6 py-8">
                <header className="mb-6">
                    <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
                        <Building2 className="size-5 text-primary" /> Organizations
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">Create organizations and invite people into them.</p>
                </header>

                <div className="mb-6 flex gap-2">
                    <input value={name} onChange={(e) => setName(e.target.value)} placeholder="New organization name"
                        className="flex-1 rounded-md border border-border bg-background px-3 py-2 text-sm" />
                    <button disabled={!name.trim()}
                        onClick={() => router.post('/admin/organizations', { name }, { onSuccess: () => setName('') })}
                        className="inline-flex items-center gap-1.5 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50">
                        <Plus className="size-4" /> Create
                    </button>
                </div>

                <div className="grid gap-3 sm:grid-cols-2">
                    {organizations.map((o) => (
                        <Link key={o.id} href={`/admin/organizations/${o.id}`}
                            className="rounded-xl border border-border bg-card p-5 shadow-sm transition hover:shadow-md">
                            <p className="font-medium text-foreground">{o.name}</p>
                            <div className="mt-2 flex items-center gap-4 text-xs text-muted-foreground">
                                <span className="flex items-center gap-1"><Users className="size-3.5" /> {o.users} members</span>
                                {o.pending > 0 && <span className="text-amber-600">{o.pending} pending</span>}
                            </div>
                        </Link>
                    ))}
                    {organizations.length === 0 && (
                        <p className="col-span-2 rounded-xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
                            No organizations yet. Create your first above.
                        </p>
                    )}
                </div>
            </div>
        </>
    );
}
