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

import { useObject, useUpdateObject, useSetFields } from "../api/queries";
import { ObjectForm, type ObjectCore, type ObjectFormValues } from "./object-form";

export function ObjectEditForm() {
  const { t } = useTranslation();
  const { id } = useParams();
  const navigate = useNavigate();
  const location = useLocation();

  const { data: object, isLoading } = useObject(id!);
  const update = useUpdateObject();
  const setFields = useSetFields();

  const [error, setError] = useState<string | null>(
    (location.state as { fieldsError?: boolean } | null)?.fieldsError ? t("form.rejected") : null,
  );

  if (isLoading) return <div className="p-4" role="status" aria-label="loading" />;

  if (!object) return <p className="p-4 text-sm text-neutral-500">{t("objects.notFound")}</p>;

  const core: ObjectCore = {
    object_number: object.object_number,
    object_name: object.object_name,
    number_of_objects: object.number_of_objects,
    brief_description: object.brief_description ?? null,
    current_location: object.current_location ?? null,
    current_owner: object.current_owner ?? null,
    recorder: object.recorder ?? null,
    recording_date: object.recording_date ?? null,
  };

  const defaults = { core, fields: object.fields };

  const onSubmit = async (values: ObjectFormValues) => {
    setError(null);

    try {
      await update.mutateAsync({ id: id!, body: values.core });
      await setFields.mutateAsync({ id: id!, fields: values.fields });
    } catch {
      setError(t("form.rejected"));
      return;
    }

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

  return (
    <ObjectForm
      mode="edit"
      defaults={defaults}
      formError={error}
      onSubmit={onSubmit}
      onCancel={() => navigate(`/objects/${id}`)}
    />
  );
}
