"use client";

import {
  Bell,
  CalendarDays,
  CheckCheck,
  GitPullRequestArrow,
  MessageSquare,
  Users2,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { Avatar } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { useNotifications } from "@/hooks/use-notifications";
import { formatDate, formatRelativeDate } from "@/lib/utils";
import type { Notification } from "@/types";

function getNotificationIcon(notification: Notification) {
  if (notification.kind === "mention") {
    return <MessageSquare className="h-4 w-4 text-primary" />;
  }

  if (notification.kind === "event_invite") {
    return <CalendarDays className="h-4 w-4 text-primary" />;
  }

  if (notification.kind === "task_review") {
    return <GitPullRequestArrow className="h-4 w-4 text-primary" />;
  }

  if (notification.kind === "project_approval") {
    return <GitPullRequestArrow className="h-4 w-4 text-primary" />;
  }

  if (
    notification.kind === "direct_message" ||
    notification.kind === "direct_task_request" ||
    notification.kind === "team_message" ||
    notification.kind === "team_task_request"
  ) {
    return <MessageSquare className="h-4 w-4 text-primary" />;
  }

  return <Users2 className="h-4 w-4 text-primary" />;
}

export default function NotificationsPage() {
  const router = useRouter();
  const { notifications, unreadCount, loading, markAsRead, markAllAsRead } =
    useNotifications();

  async function handleOpen(notification: Notification) {
    if (!notification.is_read) {
      await markAsRead(notification.id);
    }

    router.push(notification.link || "/");
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div className="space-y-1">
          <div className="flex items-center gap-3">
            <Bell className="h-5 w-5 text-muted-foreground" />
            <h1 className="text-2xl font-bold tracking-tight">Notifications</h1>
            <Badge variant="secondary">{unreadCount} unread</Badge>
          </div>
          <p className="text-sm text-muted-foreground">
            Mentions, messages, task reviews, project approvals, event invites, and workspace updates land here.
          </p>
        </div>

        <Button
          variant="outline"
          onClick={() => void markAllAsRead()}
          disabled={unreadCount === 0}
        >
          <CheckCheck className="h-4 w-4" />
          Mark all read
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Inbox</CardTitle>
          <CardDescription>
            Stay on top of collaboration without losing the context behind each update.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <p className="text-sm text-muted-foreground">Loading notifications...</p>
          ) : notifications.length === 0 ? (
            <EmptyState
              icon={<Bell className="h-10 w-10" />}
              title="No notifications yet"
              description="Once people message you, mention you, or add you to events, updates will appear here."
              className="py-8"
            />
          ) : (
            <div className="space-y-3">
              {notifications.map((notification) => (
                <button
                  key={notification.id}
                  type="button"
                  onClick={() => void handleOpen(notification)}
                  className={`flex w-full items-start gap-4 rounded-2xl border border-border/60 p-4 text-left transition-colors hover:bg-accent/40 ${
                    !notification.is_read ? "bg-primary/5" : "bg-background/60"
                  }`}
                >
                  <div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted">
                    {notification.actor ? (
                      <Avatar
                        src={notification.actor.avatar_url}
                        name={notification.actor.full_name || notification.actor.email}
                        size="sm"
                      />
                    ) : (
                      getNotificationIcon(notification)
                    )}
                  </div>

                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <p className="font-medium">{notification.title}</p>
                      {!notification.is_read && <Badge>New</Badge>}
                    </div>
                    {notification.body && (
                      <p className="mt-1 text-sm text-muted-foreground">
                        {notification.body}
                      </p>
                    )}
                    <div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
                      <span>{formatRelativeDate(notification.created_at)}</span>
                      <span title={formatDate(notification.created_at)}>
                        {formatDate(notification.created_at)}
                      </span>
                      <span className="inline-flex items-center gap-1">
                        {getNotificationIcon(notification)}
                        {notification.kind.replaceAll("_", " ")}
                      </span>
                    </div>
                  </div>
                </button>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
