"use client"

import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { useTranslations } from "next-intl"
import { Bell, CheckCheck, MessageSquare, Megaphone, PenTool, GraduationCap, Stethoscope } 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 { cn, formatDate } from "@/shared/lib/utils"

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

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

const TYPE_KEYS: NotificationType[] = ["message", "announcement", "homework", "grade", "diagnostic"]

const PRIORITY_COLOR: Record<NotificationPriority, string> = {
  low: "bg-muted text-muted-foreground",
  normal: "bg-blue-500/10 text-blue-700 dark:text-blue-400",
  high: "bg-orange-500/10 text-orange-700 dark:text-orange-400",
  urgent: "bg-red-500/10 text-red-700 dark:text-red-400",
}

export function NotificationList({ notifications }: { notifications: Notification[] }) {
  const t = useTranslations("notifications")
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)
  const [filterType, setFilterType] = useState<NotificationType | "all">("all")
  const hasUnread = notifications.some((n) => !n.isRead)

  const filteredNotifications = filterType === "all"
    ? notifications
    : notifications.filter((n) => n.type === filterType)

  const handleMarkAllRead = async () => {
    setIsWorking(true)
    try {
      const res = await markAllNotificationsAsReadAction()
      if (res.success) {
        toast.success(res.message)
        router.refresh()
      } else {
        toast.error(res.message || t("messages.markReadFailed"))
      }
    } catch {
      toast.error(t("messages.markReadFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  const handleMarkRead = async (id: string) => {
    try {
      const res = await markNotificationAsReadAction(id)
      if (res.success) {
        router.refresh()
      }
    } catch {
      toast.error(t("messages.markReadFailed"))
    }
  }

  const handleArchive = async (id: string) => {
    try {
      const res = await archiveNotificationAction(id)
      if (res.success) {
        router.refresh()
      }
    } catch {
      toast.error(t("messages.archiveFailed"))
    }
  }

  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">{t("title.list")}</h2>
          <p className="text-muted-foreground text-sm">{t("description.list")}</p>
        </div>
        {hasUnread ? (
          <Button onClick={handleMarkAllRead} disabled={isWorking} variant="outline">
            <CheckCheck className="mr-2 h-4 w-4" />
            {t("actions.markAllRead")}
          </Button>
        ) : null}
      </div>

      <div className="flex flex-wrap gap-2">
        <Button
          variant={filterType === "all" ? "default" : "outline"}
          size="sm"
          onClick={() => setFilterType("all")}
        >
          {t("filter.all")}
        </Button>
        {TYPE_KEYS.map((type) => (
          <Button
            key={type}
            variant={filterType === type ? "default" : "outline"}
            size="sm"
            onClick={() => setFilterType(type)}
          >
            {t(`type.${type}`)}
          </Button>
        ))}
      </div>

      {filteredNotifications.length === 0 ? (
        <EmptyState
          title={filterType === "all" ? t("empty.noNotifications") : t("empty.noFilterResults")}
          description={filterType === "all" ? t("empty.noNotificationsDesc") : t("empty.noFilterResultsDesc")}
          icon={Bell}
          className="h-auto border-none shadow-none"
        />
      ) : (
        <div className="space-y-3">
          {filteredNotifications.map((n) => {
            const Icon = TYPE_ICON[n.type] ?? Bell
            return (
              <Card
                key={n.id}
                className={cn("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" aria-hidden="true" />
                  </div>
                  <div className="min-w-0 flex-1 space-y-1">
                    <div className="flex items-center gap-2">
                      <span className={cn("text-sm", !n.isRead ? "font-semibold" : "font-medium")}>
                        {n.title}
                      </span>
                      {!n.isRead ? <Badge variant="default" className="text-xs">{t("status.new")}</Badge> : null}
                      {n.priority !== "normal" ? (
                        <Badge variant="outline" className={cn("text-xs", PRIORITY_COLOR[n.priority])}>
                          {t(`priority.${n.priority}`)}
                        </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">
                        {t(`type.${n.type}`)}
                      </Badge>
                      <span>{formatDate(n.createdAt)}</span>
                      {!n.isRead ? (
                        <button
                          type="button"
                          onClick={() => handleMarkRead(n.id)}
                          className="text-primary hover:underline"
                          aria-label={t("actions.markRead")}
                        >
                          {t("actions.markRead")}
                        </button>
                      ) : null}
                      <button
                        type="button"
                        onClick={() => handleArchive(n.id)}
                        className="text-muted-foreground hover:text-foreground hover:underline"
                        aria-label={t("actions.archive")}
                      >
                        {t("actions.archive")}
                      </button>
                      {n.link ? (
                        <Link href={n.link} className="ml-auto text-primary hover:underline">
                          {t("actions.view")}
                        </Link>
                      ) : null}
                    </div>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
      )}
    </div>
  )
}
