import { updateEventAPI, useEvent, useNotifications } from "@/api";
import { LoadingData } from "@/components/common";
import { EventForm } from "@/components/events";
import { BasePage, Header } from "@/components/layout";
import { HandleError } from "@/pages/others";
import { CAPABILITY } from "@/utils/consts";
import { __ } from "@wordpress/i18n";
import { useParams, useSearchParams } from "react-router";

export const UpdateEvent = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const params = useParams();
  const { data, error, isLoading } = useEvent(params.id);
  const navigateTo =
    searchParams.get("from") === "detail" ? `/${params.id}` : "/";
  const {
    data: notifications,
    isLoading: isLoadingNotifications,
    notificationsError,
  } = useNotifications({});

  const getDefaultValues = (data) => {
    if (data) {
      let copied = { ...data };
      copied.notification_ids = data.notifications.map((item) => item.id);
      // 分から時に変換
      copied.min_time_to_close_booking = Math.trunc(
        copied.min_time_to_close_booking / 60,
      );
      copied.min_time_to_cancel_booking = Math.trunc(
        copied.min_time_to_cancel_booking / 60,
      );
      delete copied.notifications;
      return copied;
    } else {
      return null;
    }
  };

  if (error || notificationsError) return <HandleError error={error} />;
  if (isLoading || isLoadingNotifications) return <LoadingData />;

  return (
    <BasePage capability={CAPABILITY.WRITE}>
      <Header title={__("Edit Event", "yoyaku-manager")} />
      <EventForm
        defaultValues={getDefaultValues(data)}
        dataHandler={updateEventAPI}
        notifications={notifications}
        navigateTo={navigateTo}
      />
    </BasePage>
  );
};
