"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { ArrowLeft, Bell, CheckCircle, AlertCircle, Info, Gift } from "lucide-react"
import { useAuth } from "@/components/auth-provider"
import useSWR from "swr"

const fetcher = (url: string) => fetch(url).then((res) => res.json())

export default function ArtistNotificationsPage() {
  const router = useRouter()
  const { user, isAuthenticated, isLoading } = useAuth()
  const [selectedType, setSelectedType] = useState<string>("all")

  const { data: notifications, mutate } = useSWR(user?.id ? `/api/notifications?userId=${user.id}` : null, fetcher)

  useEffect(() => {
    if (!isLoading && (!isAuthenticated || user?.role !== "artist")) {
      router.push("/")
    }
  }, [isAuthenticated, isLoading, user, router])

  if (isLoading) {
    return (
      <div className="min-h-screen bg-zinc-950 flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-purple-500"></div>
      </div>
    )
  }

  if (!isAuthenticated || user?.role !== "artist") {
    return null
  }

  const markAsRead = async (notificationId: string) => {
    await fetch(`/api/notifications`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id: notificationId, is_read: true }),
    })
    mutate()
  }

  const markAllAsRead = async () => {
    if (!notifications?.notifications) return
    await Promise.all(
      notifications.notifications
        .filter((n: any) => !n.is_read)
        .map((n: any) =>
          fetch(`/api/notifications`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ id: n.id, is_read: true }),
          }),
        ),
    )
    mutate()
  }

  const filteredNotifications =
    notifications?.notifications?.filter((n: any) => {
      if (selectedType === "all") return true
      return n.type === selectedType
    }) || []

  const unreadCount = notifications?.notifications?.filter((n: any) => !n.is_read).length || 0

  const getIcon = (type: string) => {
    switch (type) {
      case "success":
        return <CheckCircle className="w-5 h-5 text-green-400" />
      case "error":
        return <AlertCircle className="w-5 h-5 text-red-400" />
      case "warning":
        return <AlertCircle className="w-5 h-5 text-yellow-400" />
      case "promo":
        return <Gift className="w-5 h-5 text-purple-400" />
      default:
        return <Info className="w-5 h-5 text-blue-400" />
    }
  }

  return (
    <div className="min-h-screen bg-zinc-950">
      <div className="max-w-4xl mx-auto p-4">
        {/* Header */}
        <div className="flex items-center gap-4 mb-6">
          <Link href="/artist" className="text-zinc-400 hover:text-white">
            <ArrowLeft className="w-6 h-6" />
          </Link>
          <div>
            <h1 className="text-2xl font-bold text-white">Notifications</h1>
            {unreadCount > 0 && <p className="text-zinc-400 text-sm">{unreadCount} non lues</p>}
          </div>
          {unreadCount > 0 && (
            <button onClick={markAllAsRead} className="ml-auto text-purple-400 hover:text-purple-300 text-sm">
              Tout marquer comme lu
            </button>
          )}
        </div>

        {/* Filters */}
        <div className="flex gap-2 mb-6 overflow-x-auto pb-2">
          {["all", "info", "success", "promo", "warning", "error"].map((type) => (
            <button
              key={type}
              onClick={() => setSelectedType(type)}
              className={`px-4 py-2 rounded-full text-sm whitespace-nowrap ${
                selectedType === type ? "bg-purple-500 text-white" : "bg-zinc-800 text-zinc-400 hover:text-white"
              }`}
            >
              {type === "all" ? "Tout" : type}
            </button>
          ))}
        </div>

        {/* Notifications List */}
        <div className="space-y-2">
          {filteredNotifications.length === 0 ? (
            <div className="text-center py-12">
              <Bell className="w-12 h-12 text-zinc-600 mx-auto mb-4" />
              <p className="text-zinc-400">Aucune notification</p>
            </div>
          ) : (
            filteredNotifications.map((notification: any) => (
              <div
                key={notification.id}
                className={`p-4 rounded-lg border ${
                  notification.is_read ? "bg-zinc-900/50 border-zinc-800" : "bg-zinc-900 border-purple-500/30"
                }`}
              >
                <div className="flex gap-4">
                  <div className="flex-shrink-0">{getIcon(notification.type)}</div>
                  <div className="flex-1 min-w-0">
                    <h3 className="text-white font-medium mb-1">{notification.title}</h3>
                    <p className="text-zinc-400 text-sm mb-2">{notification.message}</p>
                    <p className="text-zinc-500 text-xs">
                      {new Date(notification.created_at).toLocaleDateString("fr-FR", {
                        day: "numeric",
                        month: "short",
                        hour: "2-digit",
                        minute: "2-digit",
                      })}
                    </p>
                  </div>
                  {!notification.is_read && (
                    <button
                      onClick={() => markAsRead(notification.id)}
                      className="text-purple-400 hover:text-purple-300 text-sm flex-shrink-0"
                    >
                      Marquer comme lu
                    </button>
                  )}
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  )
}
