73 lines
2.4 KiB
TypeScript
73 lines
2.4 KiB
TypeScript
/* 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 { useZustandStore } from '@/stores/schedule';
|
||
import { Button } from '@repo/ui/components/ui/button';
|
||
import { PencilLine } from 'lucide-react';
|
||
import { useEffect } from 'react';
|
||
|
||
export function SlotTime(props: Readonly<SlotComponentProps>) {
|
||
const editMode = useZustandStore((state) => state.editMode);
|
||
|
||
return editMode ? <SlotTimeEditForm {...props} /> : <SlotTimeReadonly {...props} />;
|
||
}
|
||
|
||
function SlotTimeEditForm({ documentId }: Readonly<SlotComponentProps>) {
|
||
const { editMode, endTime, resetTime, setEditMode, setEndTime, setStartTime, startTime } =
|
||
useZustandStore((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: endTime, time_start: startTime } });
|
||
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 = useZustandStore((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>
|
||
);
|
||
}
|