"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useTranslations } from "next-intl";
import { Bell } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { EmptyState } from "@/components/shared/empty-state";
import { cn } from "@/lib/utils";
import { notificationHref, type NotificationType } from "@/lib/notification-links";

const PAGE_SIZE = 20;

type Notification = {
  id: string;
  type: NotificationType;
  recipeId: string | null;
  commentId: string | null;
  read: boolean;
  createdAt: string;
  actorId: string;
  actorName: string;
  actorUsername: string | null;
  actorAvatarUrl: string | null;
};

type NotificationsResponse = {
  notifications: Notification[];
  unreadCount: number;
  total: number;
  limit: number;
  offset: number;
};

function timeAgo(dateStr: string, t: ReturnType<typeof useTranslations>) {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return t("justNow");
  if (mins < 60) return t("minutesAgo", { mins });
  const hours = Math.floor(mins / 60);
  if (hours < 24) return t("hoursAgo", { hours });
  return t("daysAgo", { days: Math.floor(hours / 24) });
}

export function NotificationsPageContent() {
  const t = useTranslations("notifications");
  const tSocial = useTranslations("social");
  const [items, setItems] = useState<Notification[]>([]);
  const [total, setTotal] = useState(0);
  const [unreadCount, setUnreadCount] = useState(0);
  const [offset, setOffset] = useState(0);
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState(false);

  const fetchPage = useCallback(async (off: number, append: boolean) => {
    if (append) setLoadingMore(true);
    else setLoading(true);
    setError(false);
    try {
      const res = await fetch(`/api/v1/notifications?limit=${PAGE_SIZE}&offset=${off}`);
      if (!res.ok) throw new Error("Request failed");
      const json = (await res.json()) as NotificationsResponse;
      setItems((prev) => (append ? [...prev, ...json.notifications] : json.notifications));
      setTotal(json.total);
      setUnreadCount(json.unreadCount);
      setOffset(off + json.notifications.length);
    } catch {
      setError(true);
    } finally {
      setLoading(false);
      setLoadingMore(false);
    }
  }, []);

  useEffect(() => {
    void fetchPage(0, false);
  }, [fetchPage]);

  async function markRead(id: string) {
    setItems((prev) => prev.map((n) => (n.id === id ? { ...n, read: true } : n)));
    setUnreadCount((prev) => {
      const n = items.find((x) => x.id === id);
      return n && !n.read ? Math.max(0, prev - 1) : prev;
    });
    await fetch(`/api/v1/notifications/${id}/read`, { method: "POST" });
  }

  async function markAllRead() {
    setUnreadCount(0);
    setItems((prev) => prev.map((n) => ({ ...n, read: true })));
    await fetch("/api/v1/notifications/read", { method: "POST" });
  }

  const hasMore = items.length < total;

  return (
    <div className="space-y-6 max-w-2xl">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold tracking-tight">{t("title")}</h1>
        {unreadCount > 0 && (
          <Button variant="outline" size="sm" onClick={() => void markAllRead()}>
            {t("markAllRead")}
          </Button>
        )}
      </div>

      {loading ? (
        <p className="text-sm text-muted-foreground">{t("loading")}</p>
      ) : error && items.length === 0 ? (
        <div className="flex flex-col items-start gap-2">
          <p className="text-sm text-destructive">{t("loadFailed")}</p>
          <Button variant="outline" size="sm" onClick={() => void fetchPage(0, false)}>
            {t("retry")}
          </Button>
        </div>
      ) : items.length === 0 ? (
        <EmptyState icon={Bell} title={t("empty")} compact />
      ) : (
        <div className="divide-y rounded-xl border">
          {items.map((n) => (
            <Link
              key={n.id}
              href={notificationHref(n)}
              onClick={() => { if (!n.read) void markRead(n.id); }}
              className={cn(
                "flex items-start gap-3 p-4 hover:bg-accent transition-colors",
                !n.read && "bg-accent/40"
              )}
            >
              <Avatar className="h-9 w-9 shrink-0">
                <AvatarImage src={n.actorAvatarUrl ?? ""} alt={n.actorName} />
                <AvatarFallback className="text-xs">{n.actorName.slice(0, 2).toUpperCase()}</AvatarFallback>
              </Avatar>
              <div className="flex-1 min-w-0 space-y-1">
                <p className={cn("text-sm", !n.read && "font-medium")}>
                  {t(n.type, { name: n.actorName })}
                </p>
                <p className="text-xs text-muted-foreground">{timeAgo(n.createdAt, tSocial)}</p>
              </div>
              {!n.read && <span className="mt-1.5 h-2 w-2 rounded-full bg-primary shrink-0" aria-label={t("unread")} />}
            </Link>
          ))}
        </div>
      )}

      {error && items.length > 0 && (
        <p className="text-sm text-destructive">{t("loadFailed")}</p>
      )}

      {(hasMore || (error && items.length > 0)) && (
        <div className="flex justify-center pt-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => void fetchPage(offset, true)}
            disabled={loadingMore}
          >
            {loadingMore ? t("loading") : error ? t("retry") : t("loadMore")}
          </Button>
        </div>
      )}
    </div>
  );
}
