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 } from "../api/queries";

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

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

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

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