/* eslint-disable react/jsx-no-bind */
'use client';
import { ScheduleTimeContext } from '../context';
import { type SlotComponentProps } from '../types';
import { EditableTimeRangeForm, ReadonlyTimeRange } from './time-range';
import { useSlotMutation, useSlotQuery } from '@/hooks/slots';
import { Button } from '@repo/ui/components/ui/button';
import { PencilLine } from 'lucide-react';
import { use, useEffect } from 'react';

export function SlotTime(props: Readonly<SlotComponentProps>) {
  const { editMode } = use(ScheduleTimeContext);

  return editMode ? <SlotTimeEditForm {...props} /> : <SlotTimeReadonly {...props} />;
}

function SlotTimeEditForm({ documentId }: Readonly<SlotComponentProps>) {
  const { editMode, endTime, resetTime, setEditMode, setEndTime, setStartTime, startTime } =
    use(ScheduleTimeContext);
  const { isPending: isMutationPending, mutate: updateSlot } = useSlotMutation({ documentId });

  const { data, isPending: isQueryPending } = useSlotQuery({ documentId });
  const slot = data?.data?.slot;

  const isPending = isMutationPending || isQueryPending;

  useEffect(() => {
    if (editMode) {
      if (slot?.time_start) setStartTime(slot.time_start);
      if (slot?.time_end) setEndTime(slot.time_end);
    }
  }, [editMode, setEndTime, setStartTime, slot]);

  function handleSubmit() {
    updateSlot({ data: { time_end: endTime, time_start: startTime }, documentId });
    resetTime();
    setEditMode(false);
  }

  return (
    <EditableTimeRangeForm disabled={isPending} onSubmit={handleSubmit}>
      <Button className="rounded-full text-xs" disabled={isPending} onClick={() => handleSubmit()}>
        Сохранить
      </Button>
    </EditableTimeRangeForm>
  );
}

function SlotTimeReadonly(props: Readonly<SlotComponentProps>) {
  const { setEditMode } = use(ScheduleTimeContext);

  const { data } = useSlotQuery(props);
  const slot = data?.data?.slot;

  if (!slot) return null;

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

  return (
    <div className="flex items-center gap-2">
      <ReadonlyTimeRange {...slot} className="text-3xl" />
      <Button
        className="rounded-full text-xs"
        disabled={hasOrders}
        onClick={() => setEditMode(true)}
        size="icon"
        variant="outline"
      >
        <PencilLine className="size-4" />
      </Button>
    </div>
  );
}
