"use client";

import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { Icons } from "@turbostarter/ui-web/icons";
import { api } from "~/lib/api/client";
import { pathsConfig } from "~/config/paths";
import { diagramTypeConfig, timeAgo } from "../DiagramCard";

import type { DiagramResponse } from "../DiagramCard";

export function RecentList() {
  const router = useRouter();

  const { data, isLoading } = useQuery({
    queryKey: ["diagrams"],
    queryFn: async () => {
      const res = await api.diagrams.$get({ query: {} });
      return await res.json();
    },
  });

  const diagrams = (data?.data ?? []) as DiagramResponse[];

  if (isLoading) {
    return (
      <div className="flex justify-center p-4">
        <Icons.Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (diagrams.length === 0) {
    return (
      <p className="p-2 text-center text-xs text-muted-foreground">
        No diagrams yet
      </p>
    );
  }

  return (
    <div className="space-y-0.5">
      {diagrams.map((d) => {
        const config = diagramTypeConfig[d.type];
        const TypeIcon = config.icon;
        return (
          <button
            key={d.id}
            className="flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-accent/50 cursor-pointer"
            onClick={() => router.push(pathsConfig.dashboard.user.diagram(d.id))}
          >
            <TypeIcon className={`h-4 w-4 shrink-0 mt-0.5 ${config.color}`} />
            <div className="flex-1 min-w-0">
              <span className="block truncate text-left">{d.title}</span>
              {d.lastAiMessage && (
                <span className="block truncate text-xs text-muted-foreground">
                  {d.lastAiMessage.length > 60
                    ? `${d.lastAiMessage.slice(0, 60)}...`
                    : d.lastAiMessage}
                </span>
              )}
            </div>
            <span className="shrink-0 text-xs text-muted-foreground mt-0.5">
              {d.updatedAt ? timeAgo(new Date(d.updatedAt)) : "just now"}
            </span>
          </button>
        );
      })}
    </div>
  );
}
