/* eslint-disable canonical/id-match */
'use client';

import FloatingActionPanel from '../shared/action-panel';
import { type OrderComponentProps } from './types';
import { useIsMaster } from '@/hooks/api/customers';
import { useOrderMutation, useOrderQuery } from '@/hooks/api/orders';
import { usePushWithData } from '@/hooks/url';
import { Enum_Order_State } from '@repo/graphql/types';

export function OrderButtons({ documentId }: Readonly<OrderComponentProps>) {
  const push = usePushWithData();

  const isMaster = useIsMaster();

  const { data: { order } = {} } = useOrderQuery({ documentId });

  const { isPending, mutate: updateSlot } = useOrderMutation({ documentId });

  if (!order) return null;

  const isCreated = order?.state === Enum_Order_State.Created;
  const isApproved = order?.state === Enum_Order_State.Approved;
  const isCompleted = order?.state === Enum_Order_State.Completed;
  const isCancelling = order?.state === Enum_Order_State.Cancelling;
  const isCancelled = order?.state === Enum_Order_State.Cancelled;

  function handleApprove() {
    if (isMaster) {
      updateSlot({ data: { state: Enum_Order_State.Approved } });
    }
  }

  function handleCancel() {
    if (isMaster) {
      updateSlot({ data: { state: Enum_Order_State.Cancelled } });
    } else {
      updateSlot({ data: { state: Enum_Order_State.Cancelling } });
    }
  }

  function handleOnComplete() {
    if (isMaster) {
      updateSlot({ data: { state: Enum_Order_State.Completed } });
    }
  }

  function handleOnRepeat() {
    push('/orders/add', order);
  }

  return (
    <FloatingActionPanel
      isLoading={isPending}
      onCancel={isCreated || (isMaster && isCancelling) || isApproved ? handleCancel : undefined}
      onComplete={isMaster && isApproved ? handleOnComplete : undefined}
      onConfirm={isMaster && isCreated ? handleApprove : undefined}
      onRepeat={isCancelled || isCompleted ? handleOnRepeat : undefined}
      onReturn={isMaster && isCancelled ? handleApprove : undefined}
    />
  );
}
