import { useEffect } from 'react' import { Modal, Stack, TextInput, Textarea, Switch, Group, Button, Text, Loader, Center, Badge, Paper, } from '@mantine/core' import { useForm } from '@mantine/form' import { useRole, useCreateRole, useUpdateRole } from '@/features/roles/hooks/useRoles' interface RoleEditModalProps { roleId: number | null opened: boolean onClose: () => void } export default function RoleEditModal({ roleId, opened, onClose }: RoleEditModalProps) { const { data: role, isLoading: roleLoading } = useRole(roleId) const createRole = useCreateRole() const updateRole = useUpdateRole() const isEditMode = roleId !== null const form = useForm({ initialValues: { name: '', code: '', description: '', is_default: false, is_director: false, is_approver: false, is_observer: false, is_executor: false, }, validate: { name: (value: string | any[]) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null), code: (value: string | any[]) => { if (value.length < 2) return 'Код должен содержать минимум 2 символа' if (!/^[a-z0-9_]+$/.test(value as string)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания' return null }, }, }) // Заполняем форму данными роли useEffect(() => { if (role) { form.setValues({ name: role.name || '', code: role.code || '', description: role.description || '', is_default: role.is_default ?? false, is_director: role.is_director ?? false, is_approver: role.is_approver ?? false, is_observer: role.is_observer ?? false, is_executor: role.is_executor ?? false, }) } else if (!isEditMode) { form.reset() } }, [role, isEditMode]) const handleSubmit = async (values: typeof form.values) => { if (isEditMode && roleId) { // Режим редактирования await updateRole.mutateAsync({ id: roleId, ...values, }) } else { // Режим создания await createRole.mutateAsync(values) } onClose() } const isLoading = roleLoading const isSubmitting = createRole.isPending || updateRole.isPending return ( {isEditMode ? 'Редактирование роли' : 'Создание роли'} {role && ID: {role.id}} } size="lg" > {isLoading ? (
) : (