"use client"

import { useCallback, useEffect, useState } from "react"
import { Bell, BellOff, Brush, CheckCheck, Flame, Heart, Images, LucideProps, Megaphone, MessageCircle, Trophy } from "lucide-react"

import Loading from "@/components/common/loading.component"
import ErrorBox from "@/components/common/error-box.component"
import EmptyState from "@/components/common/empty-state.component"
import { Button } from "@/components/ui/button"

import { useVersionedRouter } from "@/hooks/use-versioned-router"
import { NOTIFICATIONS_CHANGED_EVENT } from "@/hooks/use-unread-notifications"
import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"
import { AppNotificationDto } from "@/lib/dto/notification.dto"
import { PaginationMetaDto } from "@/lib/dto/pagination-meta.dto"
import { cn } from "@/lib/utils"

const ICONS: Record<string, React.ComponentType<LucideProps>> = {
  bell: Bell,
  brush: Brush,
  megaphone: Megaphone,
  flame: Flame,
  trophy: Trophy,
  message: MessageCircle,
  heart: Heart,
  image: Images,
}

const TONES: Record<string, string> = {
  critique_ready: "bg-sienna-soft text-sienna-dark",
  chat_message: "bg-ultra-soft text-ultra",
  gallery_like: "bg-rose-soft text-rose",
  gallery_approved: "bg-sage-soft text-sage-ink",
  gallery_rejected: "bg-paper-2 text-ink",
  announcement: "bg-ochre-soft text-ochre-ink",
}

function ago(iso: string): string {
  const seconds = Math.round((new Date(iso).getTime() - Date.now()) / 1000)
  const steps: [Intl.RelativeTimeFormatUnit, number][] = [["day", 86400], ["hour", 3600], ["minute", 60]]
  try {
    const format = new Intl.RelativeTimeFormat("fa", { numeric: "auto" })
    for (const [unit, size] of steps) {
      if (Math.abs(seconds) >= size) return format.format(Math.round(seconds / size), unit)
    }
    return format.format(0, "minute")
  } catch {
    return ""
  }
}

/** The learner's notifications: newest first, unread marked; tapping one reads it and opens its page. */
export default function NotificationsView() {
  const router = useVersionedRouter()
  const [items, setItems] = useState<AppNotificationDto[]>([])
  const [meta, setMeta] = useState<PaginationMetaDto | null>(null)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [loaded, setLoaded] = useState(false)

  const [{ loading }, fetchList] = useApi<AppNotificationDto[]>({ url: ApiEndpoint("notification", "list"), method: "GET" })
  const [, postReadAll] = useApi({ url: ApiEndpoint("notification", "readAll"), method: "POST" })
  const [, postRead] = useApi({ method: "POST" })

  const load = useCallback((page: number) => {
    return fetchList({ params: { page } }).then(
      (response) => {
        const data = response?.body?.data ?? []
        setItems((previous) => (page === 1 ? data : [...previous, ...data]))
        setMeta(response?.body?.meta ?? null)
        setLoadError(null)
        setLoaded(true)
      },
      (err: unknown) => {
        setLoadError(getApiErrorMessage(err))
        setLoaded(true)
      },
    )
  }, [fetchList])

  useEffect(() => {
    load(1)
  }, [load])

  function changed() {
    window.dispatchEvent(new CustomEvent(NOTIFICATIONS_CHANGED_EVENT))
  }

  function open(item: AppNotificationDto) {
    if (!item.read) {
      setItems((list) => list.map((n) => (n.id === item.id ? { ...n, read: true } : n)))
      postRead({ url: ApiEndpoint("notification", "read", { id: item.id }) }).then(changed, () => { /* stays unread on the server */ })
    }
    if (item.route) router.push(item.route)
  }

  function readAll() {
    setItems((list) => list.map((n) => ({ ...n, read: true })))
    postReadAll().then(changed, () => load(1))
  }

  const hasUnread = items.some((n) => !n.read)

  return (
    <div className="flex flex-col flex-1 bg-background text-right min-h-0">
      <div className="flex-1 overflow-y-auto min-h-0 px-4 py-4">
        {hasUnread && (
          <div className="flex justify-end mb-3">
            <button type="button" onClick={readAll} className="flex items-center gap-1 text-caption font-bold text-sienna">
              <CheckCheck className="w-4 h-4" aria-hidden="true" />
              خواندن همه
            </button>
          </div>
        )}

        <Loading loading={!loaded}>
          <ErrorBox active={!!loadError} title="خطا در بارگذاری" description={loadError} showRetry onRetry={() => load(1)}>
            {items.length === 0 ? (
              <EmptyState icon={<BellOff className="w-8 h-8" />} title="اعلانی نداری" description="وقتی مربی کارت را نقد کند یا خبری باشد، اینجا می‌بینی." />
            ) : (
              <ul className="flex flex-col [&>*:not(:last-child)]:mb-2">
                {items.map((item) => {
                  const Icon = ICONS[item.icon] ?? Bell
                  return (
                    <li key={item.id}>
                      <button
                        type="button"
                        onClick={() => open(item)}
                        className={cn(
                          "w-full flex items-start text-right rounded-card border p-3.5 transition",
                          item.read ? "bg-canvas border-line" : "bg-sienna-soft/40 border-sienna/30"
                        )}
                      >
                        <span className={cn("w-10 h-10 rounded-xl grid place-items-center shrink-0", TONES[item.kind] ?? "bg-paper-2 text-ink")}>
                          <Icon className="w-5 h-5" aria-hidden="true" />
                        </span>
                        <span className="flex-1 min-w-0 mr-3">
                          <span className="flex items-center justify-between">
                            <span className={cn("text-body truncate", item.read ? "font-bold" : "font-extrabold")}>{item.title}</span>
                            {!item.read && <span className="w-2 h-2 rounded-full bg-sienna shrink-0 mr-2" aria-label="خوانده‌نشده" />}
                          </span>
                          <span className="block text-body-sm text-ink-soft leading-6 mt-0.5">{item.body}</span>
                          <span className="block text-micro text-ink-soft mt-1">{ago(item.created_at)}</span>
                        </span>
                      </button>
                    </li>
                  )
                })}
              </ul>
            )}

            {meta && meta.current_page < meta.last_page && (
              <Button variant="outline" className="w-full h-11 rounded-2xl mt-3" disabled={loading} onClick={() => load(meta.current_page + 1)}>
                اعلان‌های قبلی
              </Button>
            )}
          </ErrorBox>
        </Loading>
      </div>
    </div>
  )
}
