import React, { useState } from "react"; import { OPACITY_ON_LOAD } from "../../Layout/animations"; import { Box, Button, HStack, Input, InputGroup, InputRightAddon, Textarea, useDisclosure, Image, Icon, VStack, Text, useToast } from "@chakra-ui/react"; import { FormControl, FormLabel, FormHelperText, } from "@chakra-ui/react"; import { DeleteIcon, Search2Icon } from "@chakra-ui/icons"; import SelectInvestorModal from "./SelectInvestorModal"; import { Controller, useForm } from "react-hook-form"; // Import useForm import { yupResolver } from "@hookform/resolvers/yup"; // Import resolver for Yup import * as Yup from "yup"; // Import Yup for validation import { motion } from 'framer-motion'; // Import Framer Motion for animations import { bytesToMB } from "../../Constants/Constants"; import { useCreateFawateerRequestMutation } from "../../Services/fawateer.maker.service"; import ToastBox from "../../Components/ToastBox"; import { useNavigate } from "react-router-dom"; import CurrencyInput from "../../Components/CurrencyInput"; // Validation schema using Yup const validationSchema = Yup.object().shape({ investorName: Yup.string().required("Investor name is required"), clientId: Yup.string().required("Client ID is required"), transaction_date: Yup.date() .required('Date is required') .transform((value, originalValue) => { return originalValue === "" ? null : value; // Convert empty strings to null }) .typeError('Please enter a valid date').max(new Date(), "Date cannot be in the future"), transaction_amount: Yup.number() .required("Transaction amount is required") .transform((value, originalValue) => originalValue === "" ? null : value) // Convert empty strings to null .typeError('Transaction amount must be a number') // Custom error message if it's not a number .positive('Transaction amount must be greater than zero'), spportFile_path: Yup.mixed().required("Support file is required"), makerComment: Yup.string(), }); const CreateRequest = () => { const toast = useToast() const navigate=useNavigate() const { isOpen, onOpen, onClose } = useDisclosure(); const [selectedInvestor, setSelectorInvestor] = useState({}); const [filePreview, setFilePreview] = useState(null); // State for previewing the file const [fileType, setFileType] = useState(null); // State to store file type for conditional rendering const[ isLoading, setIsLoading ] = useState(false) const [id, setId ] = useState(null) // Initialize useForm with the resolver for Yup validation const {control, register, handleSubmit, setValue,reset, formState: { errors } } = useForm({ resolver: yupResolver(validationSchema), }); const [ creatFawaateerRequest ] = useCreateFawateerRequestMutation() const onSubmit = async (data) => { console.log(data); setIsLoading(true) // Convert data to FormData const formData = new FormData(); // Append each field from the data object to the FormData Object.keys(data).forEach((key) => { if (key === "spportFile_path" && data[key] instanceof FileList) { // Append the first file from FileList (assuming single file input) formData.append(key, data[key][0]); // Append the file } else { formData.append(key, data[key]); // Append other fields } }); try { // Make the API call with formData const res = await creatFawaateerRequest({ data: formData, id }); if (res?.error) { toast({ render: () => ( ), }); setIsLoading(false); reset() return } else if (res?.data) { toast({ render: () => ( ), }); setIsLoading(false); navigate('/fawateer-history') return } else { toast({ render: () => ( ), }); setIsLoading(false); return } } catch (error) { console.error("Error:", error); toast({ render: () => ( ), }); setIsLoading(false); return } }; // Handle file change and preview const handleFileChange = (e) => { const file = e.target.files[0]; console.log(file); setValue("spportFile_path", file); // Set the file value in the form setFileType(file); // Set the file type if (file && file.type.startsWith("image/")) { // If the file is an image, generate a preview const reader = new FileReader(); reader.onload = () => { setFilePreview(reader.result); // Set the image preview }; reader.readAsDataURL(file); } else { setFilePreview(null); // Clear preview if the file is not an image } }; return ( {/* Investor Name Field */} Investor name Search {errors.investorName?.message} {/* Client ID Field */} Client Id {errors.clientId?.message} {/* Date Field */} Date {errors.transaction_date?.message} {/* Amount Field */} Amount (BHD) ( )} /> {errors.transaction_amount?.message} {/* Support File Field with Preview */} Support file {errors.spportFile_path?.message} {/* Animated Preview */} {filePreview && fileType?.type.startsWith("image/") && ( File preview setFilePreview(null)} className="link" rounded={'md'} color={'red.700'} cursor={'pointer'} p={1.5} position={'absolute'} top={0} right={0} as={DeleteIcon} boxSize={7} /> File Name: {fileType?.name} File Size: {bytesToMB(fileType?.size)} Mb File Type: {fileType?.type} )} {/* Description Field */} Description