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

import FloatingActionPanel from '../shared/action-panel';
import { type OrderComponentProps } from './types';
import { useCustomerQuery } 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 { isBeforeNow } from '@repo/utils/datetime-format';

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

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

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

  if (!order || !customer) return null;

  // Проверяем роль относительно конкретного заказа
  const isOrderMaster = order.slot?.master?.documentId === customer.documentId;
  const isOrderClient = order.client?.documentId === customer.documentId;

  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 (isOrderMaster) {
      updateOrder({ data: { state: Enum_Order_State.Approved } });
    }
  }

  function handleCancel() {
    if (isOrderMaster) {
      updateOrder({ data: { state: Enum_Order_State.Cancelled } });
    } else if (isOrderClient) {
      updateOrder({ data: { state: Enum_Order_State.Cancelling } });
    }
  }

  function handleOnComplete() {
    if (isOrderMaster) {
      updateOrder({ data: { state: Enum_Order_State.Completed } });
    }
  }

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

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

  const canCancel = !isOrderStale && (isCreated || (isOrderMaster && isCancelling) || isApproved);
  const canComplete = isOrderMaster && isApproved;
  const canConfirm = !isOrderStale && isOrderMaster && isCreated;
  const canRepeat = isCancelled || isCompleted;
  const canReturn = !isOrderStale && isOrderMaster && 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}
    />
  );
}
