import { Head, Link, router } from '@inertiajs/react';
import { Bell, BellOff, CheckCheck, Megaphone, GraduationCap, CreditCard, MessageSquare, FileText } from 'lucide-react';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type Notification = {
    id: string;
    read_at: string | null;
    created_at: string;
    data: {
        type: string;
        title: string;
        body: string;
        url?: string;
    };
};

type Paginator<T> = {
    data: T[];
    current_page: number;
    last_page: number;
    total: number;
    links: { url: string | null; label: string; active: boolean }[];
};

type Props = { notifications: Paginator<Notification> };

const breadcrumbs: BreadcrumbItem[] = [{ title: 'Notifikasi', href: '/notifications' }];

const TYPE_CONFIG: Record<string, { color: string; icon: React.ElementType; label: string }> = {
    payment_approved: { color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400', icon: CreditCard,     label: 'Pembayaran' },
    payment_rejected: { color: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',                 icon: CreditCard,     label: 'Pembayaran' },
    new_payment:      { color: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',              icon: CreditCard,     label: 'Pembayaran' },
    new_order:        { color: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',              icon: CreditCard,     label: 'Pesanan' },
    assignment_graded:{ color: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400',      icon: FileText,       label: 'Nilai' },
    essay_graded:     { color: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400',      icon: FileText,       label: 'Nilai' },
    announcement:     { color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',          icon: Megaphone,      label: 'Pengumuman' },
    discussion_replied:{ color: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',     icon: MessageSquare,  label: 'Diskusi' },
    course_enrolled:  { color: 'bg-teal-100 text-teal-700 dark:bg-teal-900/30 dark:text-teal-400',              icon: GraduationCap,  label: 'Kelas' },
};

function getTypeConfig(type: string) {
    return TYPE_CONFIG[type] ?? { color: 'bg-muted text-muted-foreground', icon: Bell, label: 'Info' };
}

function timeAgo(date: string): string {
    const diff = Math.floor((Date.now() - new Date(date).getTime()) / 1000);
    if (diff < 60) return 'Baru saja';
    if (diff < 3600) return `${Math.floor(diff / 60)} menit lalu`;
    if (diff < 86400) return `${Math.floor(diff / 3600)} jam lalu`;
    return `${Math.floor(diff / 86400)} hari lalu`;
}

export default function NotificationsIndex({ notifications }: Props) {
    const unreadCount = notifications.data.filter((n) => !n.read_at).length;

    function markRead(id: string) {
        router.patch(`/notifications/${id}/read`, {}, { preserveScroll: true });
    }

    function markAllRead() {
        router.patch('/notifications/read-all');
    }

    return (
        <>
            <Head title="Notifikasi" />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                {/* Header */}
                <div className="relative overflow-hidden rounded-2xl border border-blue-100 bg-gradient-to-br from-blue-50 via-white to-indigo-50 p-5 shadow-sm dark:border-blue-800/30 dark:from-blue-950/40 dark:via-card dark:to-indigo-950/30">
                    <div className="relative z-10 flex items-center justify-between">
                        <div className="flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-blue-100 dark:bg-blue-800/60">
                                <Bell className="h-5 w-5 text-blue-600 dark:text-blue-300" />
                            </div>
                            <div>
                                <h1 className="text-xl font-bold text-blue-900 dark:text-blue-100">Notifikasi</h1>
                                <p className="text-sm text-blue-600 dark:text-blue-400">
                                    <span className="font-semibold">{notifications.total}</span> total notifikasi
                                    {unreadCount > 0 && (
                                        <span className="ml-2 inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-xs font-semibold text-blue-700 dark:bg-blue-900/40 dark:text-blue-300">
                                            {unreadCount} belum dibaca
                                        </span>
                                    )}
                                </p>
                            </div>
                        </div>
                        {unreadCount > 0 && (
                            <button
                                onClick={markAllRead}
                                className="flex items-center gap-1.5 rounded-xl border border-blue-200 bg-white/70 px-3 py-1.5 text-xs font-semibold text-blue-700 hover:bg-white transition-colors dark:border-blue-700 dark:bg-blue-900/20 dark:text-blue-300"
                            >
                                <CheckCheck className="h-3.5 w-3.5" />
                                Tandai semua dibaca
                            </button>
                        )}
                    </div>
                    <div className="absolute -right-4 -top-4 h-20 w-20 rounded-full bg-blue-100/40 dark:bg-blue-700/10" />
                    <div className="absolute right-10 -bottom-6 h-28 w-28 rounded-full bg-indigo-100/30 dark:bg-indigo-700/10" />
                </div>

                {/* Empty */}
                {notifications.data.length === 0 && (
                    <div className="flex flex-col items-center justify-center rounded-2xl border border-dashed border-blue-100 bg-white py-16 text-center shadow-sm dark:border-blue-900/20 dark:bg-card">
                        <div className="mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-blue-50 dark:bg-blue-900/20">
                            <BellOff className="h-7 w-7 text-blue-300 dark:text-blue-600" />
                        </div>
                        <p className="font-semibold text-foreground">Belum ada notifikasi</p>
                        <p className="mt-1 text-xs text-muted-foreground">Notifikasi baru akan muncul di sini.</p>
                    </div>
                )}

                {/* List */}
                {notifications.data.length > 0 && (
                    <div className="flex flex-col gap-2">
                        {notifications.data.map((n) => {
                            const cfg = getTypeConfig(n.data.type);
                            const Icon = cfg.icon;
                            return (
                                <div
                                    key={n.id}
                                    className={`flex gap-4 rounded-2xl border p-4 transition-colors ${
                                        !n.read_at
                                            ? 'border-blue-100 bg-blue-50/60 dark:border-blue-800/30 dark:bg-blue-950/20'
                                            : 'border-border bg-white dark:bg-card'
                                    }`}
                                >
                                    {/* Icon */}
                                    <div className={`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl ${cfg.color}`}>
                                        <Icon className="h-4 w-4" />
                                    </div>

                                    {/* Content */}
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-start justify-between gap-3">
                                            <p className={`text-sm font-semibold leading-snug ${!n.read_at ? 'text-foreground' : 'text-muted-foreground'}`}>
                                                {n.data.title}
                                            </p>
                                            <span className="shrink-0 text-xs text-muted-foreground">{timeAgo(n.created_at)}</span>
                                        </div>
                                        <p className="mt-0.5 text-sm text-muted-foreground leading-relaxed">{n.data.body}</p>
                                        <div className="mt-2 flex items-center gap-3">
                                            {n.data.url && (
                                                <Link
                                                    href={n.data.url}
                                                    className="text-xs font-semibold text-blue-600 hover:underline dark:text-blue-400"
                                                >
                                                    Lihat →
                                                </Link>
                                            )}
                                            {!n.read_at && (
                                                <button
                                                    onClick={() => markRead(n.id)}
                                                    className="text-xs text-muted-foreground hover:text-foreground transition-colors"
                                                >
                                                    Tandai dibaca
                                                </button>
                                            )}
                                        </div>
                                    </div>

                                    {/* Unread dot */}
                                    {!n.read_at && (
                                        <div className="mt-1.5 h-2 w-2 shrink-0 rounded-full bg-blue-500" />
                                    )}
                                </div>
                            );
                        })}
                    </div>
                )}

                {/* Pagination */}
                {notifications.last_page > 1 && (
                    <div className="flex items-center justify-center gap-1">
                        {notifications.links.map((link, i) =>
                            link.url ? (
                                <Link
                                    key={i}
                                    href={link.url}
                                    className={`rounded-lg px-3.5 py-1.5 text-xs font-medium transition-colors ${
                                        link.active
                                            ? 'bg-blue-600 text-white shadow-sm'
                                            : 'border border-zinc-200 bg-white text-zinc-600 hover:bg-blue-50 hover:text-blue-600 dark:border-zinc-700 dark:bg-card dark:text-zinc-400'
                                    }`}
                                    dangerouslySetInnerHTML={{ __html: link.label }}
                                />
                            ) : (
                                <span
                                    key={i}
                                    className="rounded-lg px-3.5 py-1.5 text-xs text-muted-foreground/40"
                                    dangerouslySetInnerHTML={{ __html: link.label }}
                                />
                            ),
                        )}
                    </div>
                )}
            </div>
        </>
    );
}

NotificationsIndex.layout = (page: React.ReactNode) => <AppLayout breadcrumbs={breadcrumbs}>{page}</AppLayout>;
