"use client";

import { useState } from "react";
import {
  useNotifications,
  useMarkAllNotificationsRead,
} from "@/lib/queries/use-notifications";
import { NotificationRow } from "@/components/notifications/notification-row";

export function NotificationsClient() {
  const [filter, setFilter] = useState<"all" | "unread">("all");
  const { data, fetchNextPage, hasNextPage, isLoading, isFetchingNextPage } =
    useNotifications(filter);
  const markAll = useMarkAllNotificationsRead();

  const items = data?.pages.flatMap((p) => p.data) ?? [];

  return (
    <div className="rounded-md border border-forest/20 bg-bone">
      <div className="flex items-center justify-between px-4 py-3 border-b border-forest/10">
        <div className="flex gap-2">
          <button
            type="button"
            onClick={() => setFilter("all")}
            className={`text-xs px-3 py-1 rounded-full ${
              filter === "all"
                ? "bg-forest text-bone"
                : "bg-bone text-forest border border-forest/20"
            }`}
          >
            All
          </button>
          <button
            type="button"
            onClick={() => setFilter("unread")}
            className={`text-xs px-3 py-1 rounded-full ${
              filter === "unread"
                ? "bg-forest text-bone"
                : "bg-bone text-forest border border-forest/20"
            }`}
          >
            Unread
          </button>
        </div>
        <button
          type="button"
          onClick={() => markAll.mutate()}
          className="text-xs text-terracotta hover:underline"
        >
          Mark all read
        </button>
      </div>

      <div>
        {isLoading ? (
          <div className="p-6 text-sm text-forest/60 text-center">Loading…</div>
        ) : items.length === 0 ? (
          <div className="p-10 text-sm text-forest/60 text-center">
            No notifications yet.
          </div>
        ) : (
          items.map((item) => <NotificationRow key={item.id} item={item} />)
        )}
      </div>

      {hasNextPage ? (
        <div className="p-4 text-center border-t border-forest/10">
          <button
            type="button"
            onClick={() => fetchNextPage()}
            disabled={isFetchingNextPage}
            className="text-sm text-forest hover:text-terracotta disabled:opacity-50"
          >
            {isFetchingNextPage ? "Loading…" : "Load more"}
          </button>
        </div>
      ) : null}
    </div>
  );
}
