/* 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';
import { isBeforeToday } from '@repo/utils/datetime-format';

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

  const isOrderStale = order?.datetime_start && isBeforeToday(order?.datetime_start);

  const canCancel = !isOrderStale && (isCreated || (isMaster && isCancelling) || isApproved);
  const canComplete = isMaster && isApproved;
  const canConfirm = !isOrderStale && isMaster && isCreated;
  const canRepeat = isCancelled || isCompleted;
  const canReturn = !isOrderStale && isMaster && isCancelled;

  return (
    <FloatingActionPanel
      isLoading={isPending}
      onCancel={canCancel ? handleCancel : undefined}
      onComplete={canComplete ? handleOnComplete : undefined}
      onConfirm={canConfirm ? handleApprove : undefined}
      onRepeat={canRepeat ? handleOnRepeat : undefined}
      onReturn={canReturn ? handleApprove : undefined}
    />
  );
}
