"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Icons } from "@turbostarter/ui-web/icons";
import { api } from "~/lib/api/client";
import { DiagramGrid } from "~/modules/diagram/components/DiagramGrid";
import { DiagramSidebar } from "~/modules/diagram/components/sidebar/DiagramSidebar";

export default function DiagramsPage() {
  const [selectedProjectId, setSelectedProjectId] = useState<string | null>(null);

  const { data, isLoading, isError } = useQuery({
    queryKey: ["diagrams", selectedProjectId],
    queryFn: async () => {
      const query: { projectId?: string; unorganized?: "true" } = {};
      if (selectedProjectId === "unorganized") {
        query.unorganized = "true";
      } else if (selectedProjectId) {
        query.projectId = selectedProjectId;
      }
      const res = await api.diagrams.$get({ query });
      return await res.json();
    },
  });

  if (isError) {
    return (
      <div className="flex h-full flex-col items-center justify-center gap-2 p-6">
        <Icons.AlertTriangle className="h-8 w-8 text-destructive" />
        <p className="text-sm text-muted-foreground">
          Failed to load diagrams. Please try again later.
        </p>
      </div>
    );
  }

  return (
    <div className="flex h-full">
      <DiagramSidebar
        selectedProjectId={selectedProjectId}
        onSelectProject={setSelectedProjectId}
      />
      <div className="@container flex-1 overflow-y-auto p-6">
        <DiagramGrid diagrams={data?.data ?? []} isLoading={isLoading} />
      </div>
    </div>
  );
}
