/* eslint-disable react/jsx-no-bind */
/* eslint-disable canonical/id-match */
'use client';
import { type SlotComponentProps } from './types';
import { useSlotDelete, useSlotMutation, useSlotQuery } from '@/hooks/slots';
import { Enum_Slot_State } from '@repo/graphql/types';
import { Button } from '@repo/ui/components/ui/button';
import { useRouter } from 'next/navigation';

export function SlotButtons({ documentId }: Readonly<SlotComponentProps>) {
  const { data } = useSlotQuery({ documentId });
  const { mutate: updateSlot } = useSlotMutation({ documentId });
  const { mutate: deleteSlot } = useSlotDelete({ documentId });

  const router = useRouter();

  const slot = data?.data?.slot;

  if (!slot) return null;

  const isOpened = slot?.state === Enum_Slot_State.Open;
  const isClosed = slot?.state === Enum_Slot_State.Closed;

  function handleOpenSlot() {
    return updateSlot({ data: { state: Enum_Slot_State.Open }, documentId });
  }

  function handleCloseSlot() {
    return updateSlot({ data: { state: Enum_Slot_State.Closed }, documentId });
  }

  function handleDeleteSlot() {
    router.back();
    return deleteSlot();
  }

  const hasOrders = Boolean(slot?.orders.length);

  return (
    <div className="grid grid-cols-[2fr_1fr]">
      {isOpened && (
        <Button
          className="rounded-l-2xl rounded-r-none bg-orange-100 p-6 text-orange-500 dark:bg-yellow-700 dark:text-orange-100"
          onClick={handleCloseSlot}
          variant="ghost"
        >
          Закрыть
        </Button>
      )}
      {isClosed && (
        <Button
          className="rounded-l-2xl rounded-r-none bg-green-100 p-6 text-green-500 dark:bg-green-700 dark:text-green-100"
          onClick={handleOpenSlot}
          variant="ghost"
        >
          Открыть
        </Button>
      )}
      <Button
        className="rounded-l-none rounded-r-2xl bg-red-100 p-6 text-red-500 dark:bg-red-700 dark:text-red-100"
        disabled={hasOrders}
        onClick={handleDeleteSlot}
        variant="ghost"
      >
        Удалить
      </Button>
    </div>
  );
}
