160 lines
4.1 KiB
TypeScript

import React from 'react'
import { useForm, Controller } from 'react-hook-form'
import {
Box,
Card,
CardBody,
CardHeader,
Heading,
Button,
CloseButton,
VStack,
FormControl,
FormLabel,
FormHelperText,
FormErrorMessage,
Input,
} from '@chakra-ui/react'
import { AddIcon } from '@chakra-ui/icons'
import { useTranslation } from 'react-i18next'
import { dateToCalendarFormat } from '../../../utils/time'
import { Lesson } from '../../../__data__/model'
import { ErrorSpan } from '../style'
interface NewLessonForm {
name: string
date: string
}
interface LessonFormProps {
lesson?: Partial<Lesson>
isLoading: boolean
onCancel: () => void
onSubmit: (lesson: Lesson) => void
error?: string
title: string
nameButton: string
}
export const LessonForm = ({
lesson,
isLoading,
onCancel,
onSubmit,
error,
title,
nameButton,
}: LessonFormProps) => {
const { t } = useTranslation()
const getNearestTimeSlot = () => {
const now = new Date();
const minutes = now.getMinutes();
if (minutes < 30) {
// Округляем до начала текущего часа
now.setMinutes(0, 0, 0);
} else {
// Округляем до начала следующего часа
now.setHours(now.getHours() + 1);
now.setMinutes(0, 0, 0);
}
return dateToCalendarFormat(now.toISOString());
};
const {
control,
handleSubmit,
reset,
formState: { errors },
} = useForm<NewLessonForm>({
defaultValues: (lesson && {
...lesson,
date: dateToCalendarFormat(lesson.date),
}) || {
name: '',
date: getNearestTimeSlot(),
},
})
return (
<Card align="left">
<CardHeader display="flex">
<Heading as="h2" mt="0">
{title}
</Heading>
<CloseButton
ml="auto"
onClick={() => {
reset()
onCancel()
}}
/>
</CardHeader>
<CardBody>
<form onSubmit={handleSubmit(onSubmit)}>
<VStack spacing="10" align="left">
<Controller
control={control}
name="date"
rules={{ required: t('journal.pl.common.required') }}
render={({ field }) => (
<FormControl>
<FormLabel>{t('journal.pl.lesson.form.date')}</FormLabel>
<Input
{...field}
required={false}
placeholder={t('journal.pl.lesson.form.datePlaceholder')}
size="md"
type="datetime-local"
/>
{errors.date ? (
<FormErrorMessage>{errors.date?.message}</FormErrorMessage>
) : (
<FormHelperText>{t('journal.pl.lesson.form.dateTime')}</FormHelperText>
)}
</FormControl>
)}
/>
<Controller
control={control}
name="name"
rules={{ required: t('journal.pl.common.required') }}
render={({ field }) => (
<FormControl isRequired isInvalid={Boolean(errors.name)}>
<FormLabel>{t('journal.pl.lesson.form.title')}</FormLabel>
<Input
{...field}
required={false}
placeholder={t('journal.pl.lesson.form.namePlaceholder')}
size="md"
/>
{errors.name && (
<FormErrorMessage>{errors.name.message}</FormErrorMessage>
)}
</FormControl>
)}
/>
<Box mt="10">
<Button
size="lg"
type="submit"
leftIcon={<AddIcon />}
colorScheme="blue"
isLoading={isLoading}
>
{nameButton}
</Button>
</Box>
</VStack>
{error && <ErrorSpan>{error}</ErrorSpan>}
</form>
</CardBody>
</Card>
)
}