import { createFileRoute } from "@tanstack/react-router";
import { useEffect } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ActionScreen } from "@/components/bkash/ActionScreen";
import { supabase } from "@/integrations/supabase/client";
import { useUnreadNotifications } from "@/hooks/useUnreadNotifications";
import { Bell, Megaphone } from "lucide-react";

export const Route = createFileRoute("/_authenticated/notifications")({
  component: NotificationsPage,
});

type N = {
  id: string;
  title: string;
  body: string;
  is_broadcast: boolean;
  target_user_id: string | null;
  created_at: string;
};

function NotificationsPage() {
  const qc = useQueryClient();
  const { markAllRead } = useUnreadNotifications();
  const q = useQuery({
    queryKey: ["notifications"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("notifications")
        .select("id, title, body, is_broadcast, target_user_id, created_at")
        .order("created_at", { ascending: false })
        .limit(100);
      if (error) throw new Error(error.message);
      return (data ?? []) as N[];
    },
  });

  useEffect(() => {
    const channel = supabase
      .channel("notifications-feed")
      .on(
        "postgres_changes",
        { event: "INSERT", schema: "public", table: "notifications" },
        () => {
          qc.invalidateQueries({ queryKey: ["notifications"] });
        },
      )
      .subscribe();
    return () => {
      supabase.removeChannel(channel);
    };
  }, [qc]);

  useEffect(() => {
    if ((q.data?.length ?? 0) > 0) markAllRead();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [q.data?.length]);

  const items = q.data ?? [];

  return (
    <ActionScreen title="নোটিফিকেশন" subtitle="অ্যাডমিন বার্তা ও আপডেট">
      {items.length === 0 && (
        <div className="bg-card rounded-2xl p-10 text-center shadow-[var(--shadow-card)]">
          <Bell className="h-10 w-10 mx-auto text-muted-foreground/50" />
          <p className="mt-3 text-sm text-muted-foreground">কোনো নোটিফিকেশন নেই</p>
        </div>
      )}
      <div className="space-y-2">
        {items.map((n) => (
          <div key={n.id} className="bg-card rounded-2xl p-4 shadow-[var(--shadow-card)] flex gap-3">
            <div
              className={`h-10 w-10 rounded-full flex items-center justify-center shrink-0 ${
                n.is_broadcast ? "bg-primary/10" : "bg-success/10"
              }`}
            >
              {n.is_broadcast ? (
                <Megaphone className="h-4 w-4 text-primary" />
              ) : (
                <Bell className="h-4 w-4 text-success" />
              )}
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-start justify-between gap-2">
                <p className="text-sm font-bold leading-tight">{n.title}</p>
                <span className="text-[10px] text-muted-foreground shrink-0">
                  {new Date(n.created_at).toLocaleString("en-GB", {
                    day: "2-digit",
                    month: "short",
                    hour: "2-digit",
                    minute: "2-digit",
                  })}
                </span>
              </div>
              <p className="text-sm text-muted-foreground mt-1 whitespace-pre-wrap">{n.body}</p>
              {n.is_broadcast && (
                <span className="inline-block mt-2 px-2 py-0.5 rounded-full text-[10px] font-bold bg-primary/10 text-primary">
                  সবাইকে
                </span>
              )}
            </div>
          </div>
        ))}
      </div>
    </ActionScreen>
  );
}
