import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";

import { ObjectForm, type ObjectFormValues } from "./object-form";
import { useCreateObject, useSetFields, FieldRejection } from "../api/queries";
import { errorMessageKey } from "../api/error-message";
import { useDocumentTitle } from "../lib/use-document-title";
import { useBreadcrumb } from "../shell/use-breadcrumb";
import { PageTitle } from "@/components/ui/page-title";

export function ObjectNewPage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const create = useCreateObject();
  const setFields = useSetFields();
  const [error, setError] = useState<string | null>(null);

  useDocumentTitle(t("objects.new"));
  useBreadcrumb([{ label: t("nav.objects"), to: "/objects" }, { label: t("objects.new") }]);

  const onSubmit = async (
    values: ObjectFormValues,
    opts?: { createAnother?: boolean },
  ): Promise<boolean> => {
    setError(null);

    let id: string;

    try {
      const created = await create.mutateAsync({
        ...values.core,
        visibility: values.visibility ?? "draft",
      });

      id = created.id;
    } catch (e) {
      const { key, opts } = errorMessageKey(e);
      setError(t(key, opts));
      return false;
    }

    if (Object.keys(values.fields).length > 0) {
      try {
        await setFields.mutateAsync({ id, fields: values.fields });
      } catch (e) {
        const fieldErrorKey = e instanceof FieldRejection ? e.field : undefined;
        const fieldErrorCode = e instanceof FieldRejection ? e.code : undefined;
        navigate(`/objects/${id}/edit`, { state: { created: true, fieldErrorKey, fieldErrorCode } });
        return true;
      }
    }

    if (opts?.createAnother) return true;

    navigate(`/objects/${id}`);
    return true;
  };

  return (
    <div className="mx-auto max-w-2xl">
      <PageTitle className="mb-4">{t("objects.new")}</PageTitle>
      <ObjectForm
        mode="create"
        formError={error}
        onSubmit={onSubmit}
        onCancel={() => navigate("/objects")}
      />
    </div>
  );
}
