import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Bell, CheckCheck } from "lucide-react";
import { AppShell } from "@/components/AppShell";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/use-auth";

export const Route = createFileRoute("/_authenticated/notifications")({
  head: () => ({
    meta: [
      { title: "Notifications | Emma Mold Inspection Services" },
      { name: "description", content: "Booking updates, report availability, payment and review status alerts." },
      { property: "og:title", content: "Notifications" },
      { property: "og:description", content: "Stay up to date on your mold inspection bookings and reports." },
    ],
  }),
  component: NotificationsPage,
});

function timeAgo(iso: string) {
  const diff = Date.now() - new Date(iso).getTime();
  const mins = Math.round(diff / 60000);
  if (mins < 1) return "just now";
  if (mins < 60) return `${mins}m ago`;
  const hours = Math.round(mins / 60);
  if (hours < 24) return `${hours}h ago`;
  return `${Math.round(hours / 24)}d ago`;
}

function NotificationsPage() {
  const { user } = useAuth();
  const qc = useQueryClient();

  const { data } = useQuery({
    queryKey: ["notifications", user?.id],
    enabled: Boolean(user),
    queryFn: async () => {
      const { data, error } = await supabase
        .from("notifications")
        .select("*")
        .eq("user_id", user!.id)
        .order("created_at", { ascending: false })
        .limit(100);
      if (error) throw error;
      return data;
    },
  });

  const items = data ?? [];
  const unread = items.filter((n) => !n.read);

  async function markAll() {
    if (!user || unread.length === 0) return;
    await supabase.from("notifications").update({ read: true }).eq("user_id", user.id).eq("read", false);
    qc.invalidateQueries({ queryKey: ["notifications"] });
  }

  async function toggle(id: string, read: boolean) {
    await supabase.from("notifications").update({ read }).eq("id", id);
    qc.invalidateQueries({ queryKey: ["notifications"] });
  }

  return (
    <AppShell>
      <div className="flex items-start justify-between gap-3">
        <div>
          <h1 className="flex items-center gap-2 text-2xl font-bold">
            <Bell className="h-5 w-5 text-primary" /> Notifications
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Booking status, report availability, payments and review approvals.
          </p>
        </div>
        {unread.length ? (
          <button
            onClick={markAll}
            className="flex shrink-0 items-center gap-1.5 rounded-full border border-border px-3 py-2 text-[11px] font-semibold"
          >
            <CheckCheck className="h-3.5 w-3.5" /> Mark all read
          </button>
        ) : null}
      </div>

      <div className="mt-4 space-y-2">
        {items.map((n) => (
          <article
            key={n.id}
            className={`rounded-2xl border p-4 shadow-card ${
              n.read ? "border-border/60 bg-card" : "border-primary/40 bg-soft"
            }`}
          >
            <div className="flex items-start justify-between gap-3">
              <h2 className="text-sm font-semibold">{n.title}</h2>
              <span className="shrink-0 text-[11px] text-muted-foreground">{timeAgo(n.created_at)}</span>
            </div>
            {n.body ? <p className="mt-1 text-xs text-muted-foreground">{n.body}</p> : null}
            <button
              onClick={() => toggle(n.id, !n.read)}
              className="mt-3 text-[11px] font-semibold text-primary"
            >
              {n.read ? "Mark as unread" : "Mark as read"}
            </button>
          </article>
        ))}
        {items.length === 0 ? (
          <p className="rounded-2xl bg-muted p-4 text-sm text-muted-foreground">
            You have no notifications yet.
          </p>
        ) : null}
      </div>
    </AppShell>
  );
}