/* eslint-disable react/jsx-no-bind */
'use client';

import { type SlotComponentProps } from '../types';
import { EditableTimeRangeForm, ReadonlyTimeRange } from '@/components/shared/time-range';
import { useSlotMutation, useSlotQuery } from '@/hooks/api/slots';
import { useScheduleStore } from '@/stores/schedule';
import { Button } from '@repo/ui/components/ui/button';
import { formatTime } from '@repo/utils/datetime-format';
import { PencilLine } from 'lucide-react';
import { useEffect } from 'react';

export function SlotTime(props: Readonly<SlotComponentProps>) {
  const editMode = useScheduleStore((state) => state.editMode);

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

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

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

  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: formatTime(endTime).db(), time_start: formatTime(startTime).db() },
    });
    resetTime();
    setEditMode(false);
  }

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

function SlotTimeReadonly({ documentId }: Readonly<SlotComponentProps>) {
  const setEditMode = useScheduleStore((state) => state.setEditMode);

  const { data: { slot } = {} } = useSlotQuery({ documentId });

  if (!slot) return null;

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

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