"use client"
import Link from "next/link"
import { ChevronLeft, Bell, Gift, Music, CheckCheck, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { BottomNav } from "@/components/bottom-nav"
import { useAuth } from "@/components/auth-provider"
import useSWR from "swr"
import { formatDistanceToNow } from "date-fns"
import { fr } from "date-fns/locale"

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

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

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

  const getNotificationIcon = (type: string) => {
    switch (type) {
      case "promo":
        return <Gift className="w-5 h-5" />
      case "music":
        return <Music className="w-5 h-5" />
      default:
        return <Bell className="w-5 h-5" />
    }
  }

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

  const markAllAsRead = async () => {
    await Promise.all(notifications.filter((n: any) => !n.is_read).map((n: any) => markAsRead(n.id)))
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      <div className="mx-auto max-w-2xl px-4 py-6">
        {/* Header */}
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link href="/settings" className="text-foreground hover:text-primary">
              <ChevronLeft className="h-6 w-6" />
            </Link>
            <div>
              <h1 className="text-xl font-bold text-foreground">Notifications</h1>
              {unreadCount > 0 && <p className="text-sm text-muted-foreground">{unreadCount} non lues</p>}
            </div>
          </div>
          {unreadCount > 0 && (
            <Button onClick={markAllAsRead} variant="ghost" size="sm" className="text-primary">
              <CheckCheck className="w-4 h-4 mr-2" />
              Tout marquer comme lu
            </Button>
          )}
        </div>

        {/* Notifications List */}
        <div className="space-y-2">
          {notifications.length > 0 ? (
            notifications.map((notification: any) => (
              <div
                key={notification.id}
                className={`p-4 rounded-xl border transition-colors ${
                  notification.is_read ? "bg-secondary/30 border-secondary/50" : "bg-purple-500/10 border-purple-500/30"
                }`}
              >
                <div className="flex items-start gap-4">
                  <div className={`p-2 rounded-full ${notification.is_read ? "bg-secondary" : "bg-purple-500/20"}`}>
                    {getNotificationIcon(notification.type)}
                  </div>
                  <div className="flex-1">
                    <div className="flex items-start justify-between mb-1">
                      <h3 className="font-semibold text-foreground">{notification.title}</h3>
                      {!notification.is_read && <Badge className="bg-purple-500 text-white border-0">Nouveau</Badge>}
                    </div>
                    <p className="text-sm text-muted-foreground mb-2">{notification.message}</p>
                    <div className="flex items-center justify-between">
                      <p className="text-xs text-muted-foreground">
                        {formatDistanceToNow(new Date(notification.created_at), {
                          addSuffix: true,
                          locale: fr,
                        })}
                      </p>
                      {notification.action_url && (
                        <Link href={notification.action_url}>
                          <Button size="sm" variant="ghost" className="text-primary">
                            Voir
                          </Button>
                        </Link>
                      )}
                    </div>
                  </div>
                  <Button
                    onClick={() => markAsRead(notification.id)}
                    variant="ghost"
                    size="icon"
                    className="text-muted-foreground"
                  >
                    {notification.is_read ? <Trash2 className="w-4 h-4" /> : <CheckCheck className="w-4 h-4" />}
                  </Button>
                </div>
              </div>
            ))
          ) : (
            <div className="text-center py-12">
              <Bell className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
              <h3 className="text-lg font-semibold text-foreground mb-2">Aucune notification</h3>
              <p className="text-sm text-muted-foreground">
                Vous recevrez ici les nouvelles sorties, promotions et actualités
              </p>
            </div>
          )}
        </div>
      </div>

      <BottomNav />
    </div>
  )
}
