import { Head, router, usePage } from '@inertiajs/react';
import { Bell, Check, CheckCheck } from 'lucide-react';

type Notif = { id: number; type: string; title: string; body: string; read: boolean; created_at: string };

export default function Notifications() {
    const { notifications } = usePage().props as unknown as { notifications: Notif[] };
    const unread = notifications.filter((n) => !n.read).length;

    return (
        <>
            <Head title="Notifications" />
            <div className="mx-auto w-full max-w-2xl px-6 py-8">
                <header className="mb-6 flex items-center justify-between">
                    <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
                        <Bell className="size-5 text-primary" /> Notifications
                        {unread > 0 && <span className="rounded-full bg-destructive px-2 py-0.5 text-xs font-semibold text-destructive-foreground">{unread}</span>}
                    </h1>
                    {unread > 0 && (
                        <button onClick={() => router.post('/notifications/read-all', {}, { 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">
                            <CheckCheck className="size-3.5" /> Mark all read
                        </button>
                    )}
                </header>

                <div className="space-y-2">
                    {notifications.map((n) => (
                        <div key={n.id} className={`flex items-start justify-between gap-3 rounded-lg border p-4 ${n.read ? 'border-border bg-card' : 'border-primary/30 bg-accent/40'}`}>
                            <div>
                                <p className="font-medium text-foreground">{n.title}</p>
                                {n.body && <p className="mt-0.5 text-sm text-muted-foreground">{n.body}</p>}
                                <p className="mt-1 text-xs text-muted-foreground">{n.created_at}</p>
                            </div>
                            {!n.read && (
                                <button title="Mark read" onClick={() => router.post(`/notifications/${n.id}/read`, {}, { preserveScroll: true })}
                                    className="rounded p-1.5 text-muted-foreground hover:bg-muted"><Check className="size-4" /></button>
                            )}
                        </div>
                    ))}
                    {notifications.length === 0 && (
                        <p className="rounded-xl border border-dashed border-border p-12 text-center text-sm text-muted-foreground">
                            No notifications yet.
                        </p>
                    )}
                </div>
            </div>
        </>
    );
}
