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

import { EditableTimeRangeForm } from '@/components/shared/time-range';
import { useSlotCreate } from '@/hooks/api/slots';
import { useDateTimeStore } from '@/stores/datetime';
import { ScheduleStoreProvider, useScheduleStore } from '@/stores/schedule';
import { withContext } from '@/utils/context';
import { Enum_Slot_State } from '@repo/graphql/types';
import { Button } from '@repo/ui/components/ui/button';
import { formatDate, formatTime } from '@repo/utils/datetime-format';
import { PlusSquare } from 'lucide-react';
import { type FormEvent } from 'react';

export const DaySlotAddForm = withContext(ScheduleStoreProvider)(function () {
  const selectedDate = useDateTimeStore((store) => store.date);
  const endTime = useScheduleStore((state) => state.endTime);
  const resetTime = useScheduleStore((state) => state.resetTime);
  const startTime = useScheduleStore((state) => state.startTime);

  const { isPending, mutate: addSlot } = useSlotCreate();

  const handleSubmit = (event: FormEvent) => {
    event.preventDefault();
    if (startTime && endTime) {
      addSlot({
        input: {
          date: formatDate(selectedDate).db(),
          state: Enum_Slot_State.Open,
          time_end: formatTime(endTime).db(),
          time_start: formatTime(startTime).db(),
        },
      });

      resetTime();
    }
  };

  return (
    <EditableTimeRangeForm disabled={isPending} onSubmit={handleSubmit}>
      <Button className="rounded-full" disabled={isPending} type="submit">
        <PlusSquare className="mr-1 size-4" />
        Добавить
      </Button>
    </EditableTimeRangeForm>
  );
});
