"use client";

import { useParams } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { Icons } from "@turbostarter/ui-web/icons";

import { api } from "~/lib/api/client";
import { DiagramEditor } from "~/modules/diagram/components/editor/DiagramEditor";

class DiagramError extends Error {
  constructor(
    public readonly type: "forbidden" | "not-found",
    message: string,
  ) {
    super(message);
    this.name = "DiagramError";
  }
}

export default function DiagramEditorPage() {
  const params = useParams<{ id: string }>();

  const { data, isLoading, error } = useQuery({
    queryKey: ["diagram", params.id],
    queryFn: async () => {
      const res = await api.diagrams[":id"].$get({
        param: { id: params.id },
      });
      if (res.status === 403) {
        throw new DiagramError(
          "forbidden",
          "You don't have access to this diagram",
        );
      }
      if (!res.ok) {
        throw new DiagramError("not-found", "Diagram not found");
      }
      return await res.json();
    },
    retry: (failureCount, err) => {
      if (err instanceof DiagramError) return false;
      return failureCount < 3;
    },
  });

  const errorType =
    error instanceof DiagramError ? error.type : error ? "not-found" : null;

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

  if (errorType === "forbidden") {
    return (
      <div className="flex h-full flex-col items-center justify-center gap-2 p-6">
        <Icons.Lock className="h-8 w-8 text-destructive" />
        <p className="text-sm text-muted-foreground">
          You don&apos;t have access to this diagram.
        </p>
      </div>
    );
  }

  if (errorType === "not-found" || !data) {
    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 diagram. It may have been deleted or does not exist.
        </p>
      </div>
    );
  }

  return <DiagramEditor diagram={data.data} />;
}
