import { useRouter } from "next/navigation"; import { useEffect, useState } from "react"; import { Form, Input } from "antd"; import useAxiosAuth from "@/lib/axios/useAxiosAuth"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Icons } from "@/components/Icons"; import { type IPermission } from "./type"; import { toast } from "sonner"; import RbacBadge from "@/components/ui/rbac-badge"; type Props = { isUpdate?: boolean; data?: IPermission; onCancel?: () => any; }; export default function PermissionForm({ data, isUpdate, onCancel }: Props) { const [isLoading, setIsLoading] = useState(false); const [previewName, setPreviewName] = useState(''); const [form] = Form.useForm(); const router = useRouter(); const axios = useAxiosAuth(); useEffect(() => { if (data) { form.setFieldsValue(data); setPreviewName(data.name || ''); } else { form.resetFields(); setPreviewName(''); } }, [data, form]); const handleSubmit = (value: { name: string; description?: string }) => { const payload = { name: value.name.trim().toUpperCase(), description: value.description?.trim() || '', }; !isUpdate ? handleCreate(payload) : handleUpdate(payload); }; const handleCreate = async (payload: { name: string; description?: string }) => { try { setIsLoading(true); const res = await axios.post('/permission', payload); setIsLoading(false); if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) { toast.error('Failed to create permission', { description: res.data?.message || 'Server returned an error', }); return; } toast.success('Permission successfully created.'); router.refresh(); if (onCancel) onCancel(); } catch (error: any) { setIsLoading(false); const msg = error?.response?.data?.message || error?.message || 'Failed to create permission'; toast.error('Failed to create permission', { description: msg }); } }; const handleUpdate = async (payload: { name: string; description?: string }) => { try { setIsLoading(true); const res = await axios.put(`/permission/${data?.id}`, payload); setIsLoading(false); if (res.data?.code && res.data.code !== '00' && res.data.code !== 200) { toast.error('Failed to update permission', { description: res.data?.message || 'Server returned an error', }); return; } toast.success('Permission successfully updated.'); router.refresh(); if (onCancel) onCancel(); } catch (error: any) { setIsLoading(false); const msg = error?.response?.data?.message || error?.message || 'Failed to update permission'; toast.error('Failed to update permission', { description: msg }); } }; return (
{isUpdate ? 'Edit Access Permission' : 'Create Access Permission'} Define an actionable permission identifier used by role-based access control.
setPreviewName(e.target.value.toUpperCase())} /> {previewName && (
Badge Preview:
)}
); }