import { useRouter } from "next/navigation" import { useEffect, useState } from "react" import { useSession } from "next-auth/react" import { Form, Input } from "antd" import { Button } from "@/components/ui/button" import { DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { Label } from "@/components/ui/label" import { Icons } from "@/components/Icons" import { type ICompany } from "./type" import { toast } from "sonner" type Props = { isUpdate?: boolean data?: ICompany onCancel?: () => any } export default function CompanyForm({ data, isUpdate, onCancel }: Props) { const [isLoading, setIsLoading] = useState(false) const BASE_URL = process.env.BASE_URL_API const [form] = Form.useForm(); const { data: session } = useSession() const router = useRouter() useEffect(() => { if (data) { form.setFieldsValue(data) } else { form.resetFields() } }, [data, form]) const handleSubmit = (value: any) => { console.log(value) !isUpdate ? handleCreate(value) : handleUpdate(value) } const handleCreate = async (payload: ICompany) => { try { setIsLoading(true) const res = await fetch(BASE_URL + '/company', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${session?.user.access_token}`, }, body: JSON.stringify(payload) }) const data = await res.json() setIsLoading(false) if (!res.ok) { toast.error(`Data failed to create`, { description: `(${data.code || res.status}) ${data.message || res.statusText}` }) return } toast.success('Data successfully created.') router.refresh() onCancel!() } catch (error: any) { toast.error(`Data failed to create, ${error.message}`) setIsLoading(false) } } const handleUpdate = async (payload: ICompany) => { try { setIsLoading(true) const res = await fetch(BASE_URL + '/company/' + data?.id, { method: 'PUT', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${session?.user.access_token}`, }, body: JSON.stringify(payload) }) const resData = await res.json() setIsLoading(false) if (!res.ok) { toast.error(`Data failed to update`, { description: `(${resData.code || res.status}) ${resData.message || res.statusText}` }) return } toast.success('Data successfully updated.') router.refresh() onCancel!() } catch (error: any) { toast.error(`Data failed to update`, { description: `${error.message}` }) setIsLoading(false) } } return (
{isUpdate ? 'Update company' : 'Create company'} Add a new team to manage products and customers
{/*
*/}
) }