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 { 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) => {
    setError(null);

    let id: string;

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

      id = created.id;
    } catch {
      setError(t("form.rejected"));
      return;
    }

    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;
        navigate(`/objects/${id}/edit`, { state: { fieldsError: true, fieldErrorKey } });
        return;
      }
    }

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

  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>
  );
}
