"use client";
// src/app/notifications/page.tsx
import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { AppShell } from "@/components/layout/AppShell";
import { Button, PageHeader, Card, CardContent } from "@/components/ui/index";
import { useLanguage } from "@/i18n/LanguageContext";
import { formatRelativeTime, cn } from "@/lib/utils";
import { Bell, Loader2, ExternalLink } from "lucide-react";

interface NotificationRow {
  id: string;
  title: string;
  body: string;
  type: string;
  isRead: boolean;
  link: string | null;
  createdAt: string;
}

export default function NotificationsPage() {
  const { t, language } = useLanguage();
  const [items, setItems] = useState<NotificationRow[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [unreadOnly, setUnreadOnly] = useState(false);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({ take: "100" });
      if (unreadOnly) params.set("unreadOnly", "true");
      const res = await fetch(`/api/notifications?${params}`);
      if (!res.ok) throw new Error("Failed");
      const d = await res.json();
      setItems(d.data?.notifications ?? []);
      setUnreadCount(d.data?.unreadCount ?? 0);
    } catch {
      setItems([]);
    } finally {
      setLoading(false);
    }
  }, [unreadOnly]);

  useEffect(() => {
    load();
  }, [load]);

  const markRead = async (id: string) => {
    try {
      await fetch("/api/notifications", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "mark_read", id }),
      });
      await load();
    } catch {
      /* ignore */
    }
  };

  const markAllRead = async () => {
    try {
      await fetch("/api/notifications/read-all", { method: "POST" });
      await load();
    } catch {
      /* ignore */
    }
  };

  return (
    <AppShell breadcrumbs={[{ label: t("nav.notifications") }]}>
      <PageHeader title={t("nav.notifications")} description={t("notifications.pageHint")}>
        {unreadCount > 0 && (
          <Button variant="outline" size="sm" onClick={markAllRead}>
            {t("topbar.markAllRead")}
          </Button>
        )}
      </PageHeader>

      <div className="flex items-center gap-3 mb-4">
        <label className="flex items-center gap-2 text-sm text-muted-foreground cursor-pointer select-none">
          <input
            type="checkbox"
            checked={unreadOnly}
            onChange={(e) => setUnreadOnly(e.target.checked)}
            className="rounded border-input"
          />
          {t("notifications.unreadOnly")}
        </label>
        {unreadCount > 0 && (
          <span className="text-xs font-medium text-primary tabular-nums">{unreadCount}</span>
        )}
      </div>

      {loading ? (
        <div className="flex justify-center py-16">
          <Loader2 className="w-8 h-8 animate-spin text-primary" />
        </div>
      ) : items.length === 0 ? (
        <Card>
          <CardContent className="py-16 text-center text-muted-foreground">
            <Bell className="w-10 h-10 mx-auto mb-3 opacity-40" />
            <p>{t("topbar.noNotifications")}</p>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-2">
          {items.map((n) => (
            <Card
              key={n.id}
              className={cn(
                "transition-colors",
                !n.isRead && "border-primary/30 bg-primary/[0.03]"
              )}
            >
              <CardContent className="p-4 sm:p-5">
                <div className="flex flex-col sm:flex-row sm:items-start gap-3 justify-between">
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      {!n.isRead && (
                        <span className="w-2 h-2 rounded-full bg-primary flex-shrink-0" aria-hidden />
                      )}
                      <h2 className="text-sm font-semibold text-foreground">{n.title}</h2>
                    </div>
                    <p className="text-sm text-muted-foreground whitespace-pre-wrap">{n.body}</p>
                    <p className="text-xs text-muted-foreground mt-2">
                      {formatRelativeTime(n.createdAt, language)}
                      {n.type && (
                        <span className="ms-2 opacity-70">· {n.type}</span>
                      )}
                    </p>
                  </div>
                  <div className="flex items-center gap-2 flex-shrink-0">
                    {n.link && (
                      <Link
                        href={n.link}
                        onClick={() => {
                          if (!n.isRead) void markRead(n.id);
                        }}
                        className="inline-flex items-center gap-1 rounded-lg border border-border bg-background px-3 py-1.5 text-sm font-medium hover:bg-accent transition-colors"
                      >
                        {t("notifications.open")}
                        <ExternalLink className="w-3.5 h-3.5" />
                      </Link>
                    )}
                    {!n.isRead && (
                      <Button variant="ghost" size="sm" onClick={() => markRead(n.id)}>
                        {t("notifications.markRead")}
                      </Button>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </AppShell>
  );
}
