import { useCallback, useEffect, useRef, useState, type FC } from 'react'; import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import * as Yup from 'yup' import { yupResolver } from '@hookform/resolvers/yup'; import { IClient } from '../types'; import { useForm } from 'react-hook-form'; import { toast } from 'sonner'; import { Button } from '@/components/ui/button'; import { ImageIcon, Loader2, Plus, Upload, UploadIcon } from 'lucide-react'; import { Input } from '@/components/ui/input'; import { useRouter } from 'next/navigation'; import { useFetchWithAxios } from '@/lib/axios/useFetch'; import { Combobox } from '@/components/ui/combobox'; import Dropzone from 'react-dropzone'; import { LazyImage } from '@/components/ui/lazy-image'; import { Label } from '@/components/ui/label'; import { serverApiCall } from '@/lib/server-api'; import FormEndUser from './FormEndUser'; const validationSchema = Yup.object().shape({ name: Yup.string().required(), end_user_id: Yup.number().required(), imageUrl: Yup.string().optional().default('') }); type FormDataType = Yup.InferType; type Props = { data?: IClient onCancel?: VoidFunction onSuccess?: VoidFunction; }; const FormClient: FC = ({ data, onSuccess, onCancel }) => { const [showEnduserForm, setShowEndUserForm] = useState(false) const [isLoading, setIsLoading] = useState(false) const [currentFile, setCurrentFile] = useState(undefined); const { data: endUserList, mutate } = useFetchWithAxios('/end-user') const existFile = data?.photo || null const dropzoneRef = useRef(null); const maxSizeMB = 5 const openDialog = () => { if (dropzoneRef.current) { dropzoneRef.current.open(); } }; const onDrop = useCallback((acceptedFiles: any[]) => { acceptedFiles.forEach(async (file: any) => { const reader = new FileReader(); reader.onabort = () => console.log('file reading was aborted'); reader.onerror = () => console.log('file reading has failed'); reader.onload = async () => { // Do whatever you want with the file contents const binaryStr = reader.result; console.log(file) setCurrentFile({ file: file, base64: binaryStr?.toString() }); }; reader.readAsDataURL(file); }); }, []); const router = useRouter() const form = useForm({ resolver: yupResolver(validationSchema), defaultValues: { "name": data?.name || '', "end_user_id": data?.end_user_id || undefined, 'imageUrl': data?.imageUrl || '' }, }); const handleUploadFile = async () => { setIsLoading(true) const toastId = toast.loading('Uploading image...'); let fullPathImage = '' try { const resPresignUrl: any = await serverApiCall('POST', '/s3', { "filename": currentFile?.file?.name, "type": currentFile?.file?.type, "bucket": "hats-client" }) console.log({ resPresignUrl }) if (resPresignUrl.success) { fullPathImage = `${process.env.NEXT_PUBLIC_S3_IMAGE_URL}/${resPresignUrl?.data?.data?.path_url}` const presignedUrl = resPresignUrl?.data?.data?.upload_url const uploadResponse = await fetch(presignedUrl, { method: 'PUT', body: currentFile?.file, // Send the raw file directly headers: { 'Content-Type': currentFile?.file?.type, }, }); if (!uploadResponse.ok) { throw new Error("Failed to upload image to storage 😢"); } } else { toast.error("Oops sorry, error has occurred 😢", { description: `(${resPresignUrl.code}) ${resPresignUrl.message || "An unexpected error occurred while Getting Presigned URL. Please try again later."}`, }) } } catch (error: any) { toast.error(`Failed uploading image.\n(${error?.response?.data?.code || error?.response?.status || '-'}) ${error?.response?.data?.message || error?.response?.statusText || error?.message}`); } finally { setIsLoading(false) toast.dismiss(toastId) } return fullPathImage } const onSubmit = async (payload: FormDataType) => { setIsLoading(true); let newPayload: any = { ...payload } if (currentFile?.file) { const photoPath = await handleUploadFile() newPayload['photo'] = photoPath } else { newPayload['photo'] = data?.photo } let res: any if (data) { res = await serverApiCall('PUT', `/client/${data.id}`, newPayload) } else { res = await serverApiCall('POST', '/client', newPayload) } setIsLoading(false) if (res.success) { toast.success('Client saved successfully') if (data) { onSuccess!() } else { router.push(`/task/client-detail/${res.data?.data?.id}`) } } else { toast.error(`Fail to save client`, { description: `(${res.code || '-'}) ${res.message}` }) } }; return ( <> Client Information Enter the basic details of the client and their end user.
( Client Name * )} /> ( End User *
0 ? endUserList.map((item: any) => ({ label: item.name, value: item.id })) : []} value={field.value} setValue={field.onChange} className='flex-1' />
)} />
{/* Drop area */} {/* @ts-ignore */} {({ getRootProps, getInputProps, acceptedFiles }) => { return (
{currentFile?.base64 || existFile ? (

Current Image

) : (

Drop your files here

SVG, PNG, JPG or GIF (max. {maxSizeMB}MB)

)}
); }}
Cancel
{showEnduserForm ? setShowEndUserForm(false)} onSuccess={() => { mutate(); setShowEndUserForm(false); }} /> : null } ); } export default FormClient;