"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";

import { NoPermissionState } from "@/components/auth/no-permission-state";
import { useSuperAdminSession } from "@/components/auth/session-context";
import { PageHeader } from "@/components/dashboard/page-header";
import { PaginationControls } from "@/components/dashboard/pagination-controls";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/components/ui/toast";
import { getItems, getPagination } from "@/lib/api/core";
import { listPlatformNotifications } from "@/lib/api/notifications";
import { formatDateTime } from "@/lib/format";
import { SUPERADMIN_PERMISSIONS, hasPermission } from "@/lib/permissions";
import type { NotificationItem, NotificationsResponse } from "@/types/api";

export default function NotificationsPage() {
  const { permissions } = useSuperAdminSession();
  const [readFilter, setReadFilter] = useState("all");
  const [typeFilter, setTypeFilter] = useState("all");
  const [resourceTypeFilter, setResourceTypeFilter] = useState("all");
  const [page, setPage] = useState(1);
  const [response, setResponse] = useState<NotificationsResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();
  const filtersRef = useRef({ readFilter, typeFilter, resourceTypeFilter });

  const canReadNotifications = hasPermission(
    permissions,
    SUPERADMIN_PERMISSIONS.NOTIFICATIONS_READ,
  );

  filtersRef.current = { readFilter, typeFilter, resourceTypeFilter };

  const loadNotifications = useCallback(async () => {
    if (!canReadNotifications) {
      setLoading(false);
      return;
    }

    const {
      readFilter: currentReadFilter,
      typeFilter: currentTypeFilter,
      resourceTypeFilter: currentResourceTypeFilter,
    } = filtersRef.current;
    const read =
      currentReadFilter === "all" ? undefined : currentReadFilter === "read" ? true : false;

    setLoading(true);
    try {
      const result = await listPlatformNotifications({
        page,
        limit: 15,
        read,
        type: currentTypeFilter === "all" ? undefined : currentTypeFilter,
        resourceType:
          currentResourceTypeFilter === "all" ? undefined : currentResourceTypeFilter,
        sortOrder: "desc",
      });
      setResponse(result);
    } catch (error) {
      toast({ title: "Failed to load notifications", description: String(error), variant: "danger" });
    } finally {
      setLoading(false);
    }
  }, [canReadNotifications, page, toast]);

  useEffect(() => {
    void loadNotifications();
  }, [loadNotifications]);

  const applyFilters = () => {
    if (page === 1) {
      void loadNotifications();
      return;
    }
    setPage(1);
  };

  const items = getItems(response) as NotificationItem[];
  const health = useMemo(() => {
    const missingDeepLink = items.filter((item) => item.resourceType !== "system" && !item.deepLink).length;
    const messageLinks = items.filter(
      (item) => item.type === "message" && item.deepLink?.startsWith("/chat/conversations/"),
    ).length;
    const postLinks = items.filter(
      (item) => ["like", "comment", "reply", "mention"].includes(item.type) && item.deepLink?.startsWith("/posts/"),
    ).length;
    return { missingDeepLink, messageLinks, postLinks };
  }, [items]);

  if (!canReadNotifications) {
    return (
      <div className="space-y-5 pb-8">
        <PageHeader
          title="Notifications center"
          subtitle="Platform notifications with filters for type, read state, and target resource."
        />
        <NoPermissionState description="This page needs the notifications.read permission." />
      </div>
    );
  }

  return (
    <div className="space-y-5 pb-8">
      <PageHeader
        title="Notifications center"
        subtitle="Platform notifications with filters for type, read state, and target resource."
      />

      <Card>
        <CardHeader>
          <CardTitle>Filters</CardTitle>
        </CardHeader>
        <CardContent className="grid gap-3 md:grid-cols-4">
          <Select value={readFilter} onValueChange={setReadFilter}>
            <SelectTrigger>
              <SelectValue placeholder="Read state" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All</SelectItem>
              <SelectItem value="unread">Unread</SelectItem>
              <SelectItem value="read">Read</SelectItem>
            </SelectContent>
          </Select>
          <Select value={typeFilter} onValueChange={setTypeFilter}>
            <SelectTrigger>
              <SelectValue placeholder="Type" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All types</SelectItem>
              <SelectItem value="like">like</SelectItem>
              <SelectItem value="comment">comment</SelectItem>
              <SelectItem value="follow">follow</SelectItem>
              <SelectItem value="message">message</SelectItem>
              <SelectItem value="save">save</SelectItem>
              <SelectItem value="share">share</SelectItem>
              <SelectItem value="mention">mention</SelectItem>
              <SelectItem value="reply">reply</SelectItem>
              <SelectItem value="system">system</SelectItem>
              <SelectItem value="collaboration_request">collaboration_request</SelectItem>
            </SelectContent>
          </Select>
          <Select value={resourceTypeFilter} onValueChange={setResourceTypeFilter}>
            <SelectTrigger>
              <SelectValue placeholder="Target" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All targets</SelectItem>
              <SelectItem value="post">post</SelectItem>
              <SelectItem value="comment">comment</SelectItem>
              <SelectItem value="conversation">conversation</SelectItem>
              <SelectItem value="user">user</SelectItem>
              <SelectItem value="system">system</SelectItem>
            </SelectContent>
          </Select>
          <Button variant="outline" onClick={applyFilters}>
            Apply
          </Button>
        </CardContent>
      </Card>

      <section className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader>
            <CardTitle>Missing deep links</CardTitle>
          </CardHeader>
          <CardContent className="text-3xl font-bold text-foreground">{health.missingDeepLink}</CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle>Chat links</CardTitle>
          </CardHeader>
          <CardContent className="text-3xl font-bold text-foreground">{health.messageLinks}</CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle>Post links</CardTitle>
          </CardHeader>
          <CardContent className="text-3xl font-bold text-foreground">{health.postLinks}</CardContent>
        </Card>
      </section>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>Notifications</CardTitle>
          <Badge variant={response?.unreadCount ? "warning" : "muted"}>
            Unread: {response?.unreadCount ?? 0}
          </Badge>
        </CardHeader>
        <CardContent className="space-y-4">
          {!items.length && !loading ? (
            <EmptyState title="No notifications" description="No results matched the selected filters." />
          ) : (
            <div className="space-y-3">
              {items.map((item) => (
                <div key={item._id} className="rounded-xl border border-border/70 bg-secondary/20 p-4">
                  <div className="flex flex-wrap items-center justify-between gap-3">
                    <div>
                      <p className="text-sm font-semibold text-foreground">{item.title ?? item.type}</p>
                      <p className="mt-1 text-xs text-muted-foreground">{formatDateTime(item.createdAt)}</p>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      <Badge variant={item.read ? "muted" : "warning"}>
                        {item.read ? "Read" : "New"}
                      </Badge>
                      <Badge>{item.type}</Badge>
                      <Badge variant="muted">{item.resourceType ?? "-"}</Badge>
                    </div>
                  </div>
                  <p className="mt-3 text-sm text-foreground">{item.previewText ?? item.body ?? "-"}</p>
                  {item.deepLink ? (
                    <p className="mt-2 text-xs text-muted-foreground">Deep link: {item.deepLink}</p>
                  ) : null}
                </div>
              ))}
            </div>
          )}
          <PaginationControls pagination={getPagination(response)} loading={loading} onPageChange={setPage} />
        </CardContent>
      </Card>
    </div>
  );
}
