"use client"

import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Bell, CheckCheck, MessageSquare, Megaphone, PenTool, GraduationCap } from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent } from "@/shared/components/ui/card"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { formatDate } from "@/shared/lib/utils"

import { markAllNotificationsAsReadAction, markNotificationAsReadAction } from "../actions"
import type { Notification, NotificationType } from "../types"

const TYPE_ICON: Record<NotificationType, typeof Bell> = {
  message: MessageSquare,
  announcement: Megaphone,
  homework: PenTool,
  grade: GraduationCap,
}

const TYPE_LABEL: Record<NotificationType, string> = {
  message: "Message",
  announcement: "Announcement",
  homework: "Homework",
  grade: "Grade",
}

export function NotificationList({ notifications }: { notifications: Notification[] }) {
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)
  const hasUnread = notifications.some((n) => !n.isRead)

  const handleMarkAllRead = async () => {
    setIsWorking(true)
    try {
      const res = await markAllNotificationsAsReadAction()
      if (res.success) {
        toast.success(res.message)
        router.refresh()
      } else {
        toast.error(res.message || "Failed to mark all as read")
      }
    } catch {
      toast.error("Failed to mark all as read")
    } finally {
      setIsWorking(false)
    }
  }

  const handleMarkRead = async (id: string) => {
    try {
      const res = await markNotificationAsReadAction(id)
      if (res.success) {
        router.refresh()
      }
    } catch {
      toast.error("Failed to mark as read")
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">Notifications</h2>
          <p className="text-muted-foreground text-sm">Stay updated on your latest activities.</p>
        </div>
        {hasUnread ? (
          <Button onClick={handleMarkAllRead} disabled={isWorking} variant="outline">
            <CheckCheck className="mr-2 h-4 w-4" />
            Mark all as read
          </Button>
        ) : null}
      </div>

      {notifications.length === 0 ? (
        <EmptyState
          title="No notifications"
          description="You have no notifications yet."
          icon={Bell}
          className="h-auto border-none shadow-none"
        />
      ) : (
        <div className="space-y-3">
          {notifications.map((n) => {
            const Icon = TYPE_ICON[n.type] ?? Bell
            return (
              <Card
                key={n.id}
                className={`transition-colors ${!n.isRead ? "border-primary/40 bg-primary/5" : ""}`}
              >
                <CardContent className="flex items-start gap-3 py-4">
                  <div className="bg-muted flex size-9 shrink-0 items-center justify-center rounded-full">
                    <Icon className="h-4 w-4" />
                  </div>
                  <div className="min-w-0 flex-1 space-y-1">
                    <div className="flex items-center gap-2">
                      <span className={`text-sm ${!n.isRead ? "font-semibold" : "font-medium"}`}>
                        {n.title}
                      </span>
                      {!n.isRead ? <Badge variant="default" className="text-xs">New</Badge> : null}
                    </div>
                    {n.content ? (
                      <p className="text-muted-foreground line-clamp-2 text-sm whitespace-pre-wrap">
                        {n.content}
                      </p>
                    ) : null}
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <Badge variant="outline" className="text-xs">
                        {TYPE_LABEL[n.type]}
                      </Badge>
                      <span>{formatDate(n.createdAt)}</span>
                      {!n.isRead ? (
                        <button
                          type="button"
                          onClick={() => handleMarkRead(n.id)}
                          className="text-primary hover:underline"
                        >
                          Mark as read
                        </button>
                      ) : null}
                      {n.link ? (
                        <Link href={n.link} className="ml-auto text-primary hover:underline">
                          View
                        </Link>
                      ) : null}
                    </div>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
      )}
    </div>
  )
}
