import { createFileRoute } from "@tanstack/react-router";
import { useCallback, useEffect, useState } from "react";
import { Bell, CheckCheck } from "lucide-react";

import { supabase } from "@/integrations/supabase/client";
import { PortalShell } from "@/components/portal/PortalShell";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";

export const Route = createFileRoute("/_authenticated/notifications")({
  head: () => ({
    meta: [
      { title: "Notifications — Flexflares Cyber Services" },
      { name: "description", content: "Order updates, payment confirmations and announcements from Flexflares." },
      { property: "og:title", content: "Notifications — Flexflares Cyber Services" },
      { property: "og:description", content: "Stay updated on your service orders." },
    ],
  }),
  component: NotificationsPage,
});

type Note = { id: string; title: string; body: string; is_read: boolean; created_at: string };

function NotificationsPage() {
  const [rows, setRows] = useState<Note[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    const { data } = await supabase
      .from("notifications")
      .select("id, title, body, is_read, created_at")
      .order("created_at", { ascending: false })
      .limit(100);
    setRows((data ?? []) as Note[]);
    setLoading(false);
  }, []);

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

  const markAll = async () => {
    const { data: u } = await supabase.auth.getUser();
    if (!u.user) return;
    await supabase.from("notifications").update({ is_read: true }).eq("user_id", u.user.id).eq("is_read", false);
    load();
  };

  const unread = rows.filter((r) => !r.is_read).length;

  return (
    <PortalShell
      title="Notifications"
      description={unread > 0 ? `${unread} unread update${unread === 1 ? "" : "s"}` : "You are all caught up."}
      actions={
        unread > 0 ? (
          <Button variant="outline" size="sm" onClick={markAll}>
            <CheckCheck className="mr-1 h-4 w-4" /> Mark all read
          </Button>
        ) : null
      }
    >
      {loading ? (
        <div className="grid gap-2">
          {[0, 1, 2].map((i) => (
            <Skeleton key={i} className="h-16 w-full rounded-xl" />
          ))}
        </div>
      ) : rows.length === 0 ? (
        <p className="text-sm text-muted-foreground">No notifications yet.</p>
      ) : (
        <div className="grid gap-2">
          {rows.map((n) => (
            <Card key={n.id} className={`glass ${n.is_read ? "" : "border-primary/40"}`}>
              <CardContent className="flex items-start gap-3 p-4">
                <span className="grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-primary/10 text-primary">
                  <Bell className="h-4 w-4" />
                </span>
                <div className="min-w-0">
                  <div className="text-sm font-medium">{n.title}</div>
                  {n.body && <p className="text-sm text-muted-foreground">{n.body}</p>}
                  <div className="mt-1 text-xs text-muted-foreground">{new Date(n.created_at).toLocaleString()}</div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </PortalShell>
  );
}