import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { motion } from "framer-motion";
import { Bell, CheckCheck, Info, AlertTriangle, Sparkles, CheckCircle2 } from "lucide-react";
import { PageHeader, EmptyState } from "@/components/common/PageBits";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { notificationsService } from "@/services";
import { formatDistanceToNow } from "date-fns";
import { cn } from "@/lib/utils";
import { toast } from "sonner";

export const Route = createFileRoute("/_app/notifications")({
  head: () => ({ meta: [{ title: "Notifications — Study Unique" }] }),
  component: NotificationsPage,
});

const iconMap = {
  info: Info,
  warning: AlertTriangle,
  success: CheckCircle2,
  tip: Sparkles,
};

const colorMap = {
  info: "text-secondary bg-secondary/10",
  warning: "text-warning bg-warning/10",
  success: "text-success bg-success/10",
  tip: "text-primary bg-primary/10",
};

function NotificationsPage() {
  const qc = useQueryClient();
  const { data, isLoading } = useQuery({
    queryKey: ["notifications"],
    queryFn: notificationsService.list,
  });

  const markAll = useMutation({
    mutationFn: notificationsService.markAllRead,
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["notifications"] });
      toast.success("All marked as read");
    },
  });

  return (
    <div className="mx-auto w-full max-w-3xl space-y-5 p-4 md:p-6">
      <PageHeader
        title="Notifications"
        description="Stay on top of new summaries, quizzes and goals."
        actions={
          <Button variant="outline" size="sm" onClick={() => markAll.mutate()}>
            <CheckCheck className="mr-1.5 h-4 w-4" /> Mark all read
          </Button>
        }
      />

      {isLoading ? (
        <div className="space-y-2">
          {Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-20" />)}
        </div>
      ) : !data?.length ? (
        <EmptyState icon={Bell} title="You're all caught up" description="No new notifications right now." />
      ) : (
        <div className="space-y-2">
          {data.map((n, i) => {
            const Icon = iconMap[n.type];
            return (
              <motion.div
                key={n.id}
                initial={{ opacity: 0, y: 6 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: i * 0.03 }}
                className={cn(
                  "flex items-start gap-3 rounded-xl border border-border bg-card p-4",
                  !n.read && "border-primary/30",
                )}
              >
                <div className={cn("flex h-9 w-9 items-center justify-center rounded-md", colorMap[n.type])}>
                  <Icon className="h-4 w-4" />
                </div>
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <p className="text-sm font-medium">{n.title}</p>
                    {!n.read && <span className="h-1.5 w-1.5 rounded-full bg-primary" />}
                  </div>
                  <p className="mt-0.5 text-xs text-muted-foreground">{n.body}</p>
                </div>
                <span className="shrink-0 text-[11px] text-muted-foreground">
                  {formatDistanceToNow(new Date(n.createdAt), { addSuffix: true })}
                </span>
              </motion.div>
            );
          })}
        </div>
      )}
    </div>
  );
}
