import { useRouter } from "next/navigation" import { useEffect, useState } from "react" import { Form, Input, Select } from "antd" import useAxiosAuth from "@/lib/axios/useAxiosAuth" 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 useFetch from "@/hooks/useFetch" import { type ICompany } from "../../company/component/type" import { type IDivision } from "./type" import { toast } from "sonner" type Props = { isUpdate?: boolean data?: IDivision onCancel?: () => any } export default function ComponentForm({ data, isUpdate, onCancel }: Props) { const [isLoading, setIsLoading] = useState(false) const [form] = Form.useForm(); const router = useRouter() const axios = useAxiosAuth() const { data: companyList, isLoading: loadingCompany, error } = useFetch('/company') useEffect(() => { if (data) { form.setFieldsValue(data) if (data.company) form.setFieldValue('company_id', data.company.id) } else { form.resetFields() } }, [data, form]) const handleSubmit = (value: any) => { console.log(value) !isUpdate ? handleCreate(value) : handleUpdate(value) } const handleCreate = async (payload: IDivision) => { try { setIsLoading(true) await axios.post('/division', payload) handleSuccess('Data successfully created.') } catch (error: any) { handleError(`Data failed to create, (${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`) } } const handleUpdate = async (payload: IDivision) => { try { setIsLoading(true) await axios.put('/division/' + data?.id, payload) handleSuccess('Data successfully updated.') } catch (error: any) { handleError(`Data failed to update, (${error.response.data.code || error.response.status || '-'}) ${error.response.data.message || error.response.statusText || error.message}`) } } const handleSuccess = (message: string) => { toast.success(message) setIsLoading(false) onCancel!() router.refresh() form.resetFields() } const handleError = (message: string) => { toast.error(message) setIsLoading(false) } return (
{isUpdate ? 'Update Division' : 'Create Division'} Add a new team to manage products and customers
) }