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 { IEndUser } from '../types'; import { useForm } from 'react-hook-form'; import { toast } from 'sonner'; import { Button } from '@/components/ui/button'; import { ImageIcon, Loader2, UploadIcon } from 'lucide-react'; import { Input } from '@/components/ui/input'; import { serverApiCall } from '@/lib/server-api'; import { Textarea } from '@/components/ui/textarea'; import Dropzone from 'react-dropzone'; import { LazyImage } from '@/components/ui/lazy-image'; import { Label } from '@/components/ui/label'; const validationSchema = Yup.object().shape({ name: Yup.string().required(), description: Yup.string().optional().default(''), }); type FormDataType = Yup.InferType; type Props = { data?: IEndUser onCancel?: VoidFunction onSuccess?: VoidFunction; }; const FormEndUser: FC = ({ data, onSuccess, onCancel }) => { const [currentFile, setCurrentFile] = useState(undefined); const [isLoading, setIsLoading] = useState(false); const existFile = data?.photo || null const dropzoneRef = useRef(null); const maxSizeMB = 2 const maxSizeBytes = maxSizeMB * 1024 * 1024; const openDialog = () => { // Note that the ref is set async, // so it might be null at some point if (dropzoneRef.current) { dropzoneRef.current.open(); } }; const onDrop = useCallback((acceptedFiles: any[]) => { acceptedFiles.forEach(async (file: any) => { if (file.size > maxSizeBytes) { toast.error('File size exceeds the limit', { description: `Maximum allowed file size is ${maxSizeMB}MB.`, }); return; } 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 form = useForm({ resolver: yupResolver(validationSchema), defaultValues: { "name": data?.name || '', 'description': data?.description || '', }, }); 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-end-user" }) 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."}`, id: toastId }) } } 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}`, { id: toastId }); } finally { toast.dismiss(toastId) setIsLoading(false) } 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', `/end-user/${data.id}`, newPayload) } else { res = await serverApiCall('POST', '/end-user', newPayload) } setIsLoading(false) if (res.success) { toast.success('End User saved successfully') onSuccess!() } else { toast.error(`Fail to save end user`, { description: `(${res.code || '-'}) ${res.message}` }) } }; return ( <> End User Information Enter the basic details of the End User.
( End User Name * )} /> ( Description