import React, { useEffect, useState, useCallback } from "react"; import { useNavigate, useLocation } from "react-router-dom"; import Breadcrumb from "../common/Breadcrumb"; import { Modal } from "react-bootstrap"; import { apiTenant } from "./apiTenant"; import { useCreateTenant } from "./useTenants"; const defaultAvatar = "https://via.placeholder.com/100x100.png?text=Avatar"; const initialData = { firstName: "", lastName: "", email: "", phone: "", mobile: "", domainName: "", organizationName: "", description: "", organizationSize: "", industryId: "", reference: "", taxId: "", billingAddress: "", onBoardingDate: "", }; const CreateTenant = () => { const navigate = useNavigate(); const location = useLocation(); const formData = location.state?.formData || null; const { createTenant, updateTenant, loading, error, success } = useCreateTenant(); const [form, setForm] = useState(initialData); const [imagePreview, setImagePreview] = useState(defaultAvatar); const [imageFile, setImageFile] = useState(null); const [showImageModal, setShowImageModal] = useState(false); const [showImageSizeModal, setShowImageSizeModal] = useState(false); const [industryOptions, setIndustryOptions] = useState([]); // Load form data if it's passed via location state useEffect(() => { if (formData) { const { contactName, contactNumber, logoImage, ...rest } = formData; let firstName = ""; let lastName = ""; if (contactName) { const nameParts = contactName.trim().split(" "); firstName = nameParts.shift() || ""; lastName = nameParts.join(" ") || ""; } setForm({ ...initialData, ...rest, firstName, lastName, phone: contactNumber || "", }); if (logoImage) { setImagePreview(logoImage); } } }, [formData]); // Load industry options from the API when the component mounts useEffect(() => { const fetchIndustries = async () => { try { const res = await apiTenant.getIndustries(); if (Array.isArray(res.data)) { setIndustryOptions(res.data); if (formData?.industry) { const matchedIndustry = res.data.find( (industry) => industry.name === formData.industry.name ); if (matchedIndustry) { setForm((prev) => ({ ...prev, industryId: matchedIndustry.id })); } } } else { console.error("Unexpected response format for industries", res); } } catch (err) { console.error("Failed to load industries:", err); } }; fetchIndustries(); }, [formData]); const handleChange = (e) => { const { name, value } = e.target; setForm((prev) => ({ ...prev, [name]: value })); }; const handleImageChange = (e) => { const file = e.target.files[0]; if (file) { if (file.size <= 200 * 1024) { setImageFile(file); const reader = new FileReader(); reader.onloadend = () => { setImagePreview(reader.result); }; reader.readAsDataURL(file); } else { setShowImageSizeModal(true); } } }; const handleImageReset = () => { setImageFile(null); setImagePreview(defaultAvatar); }; const handleClearForm = () => { setForm(initialData); setImagePreview(defaultAvatar); setImageFile(null); }; const handleSubmit = useCallback( async (e) => { e.preventDefault(); // Determine the image to send to the API // If there's a new file selected (imageFile), use it. // If the image was reset (imagePreview is defaultAvatar), send null. // Otherwise, use the existing logo image (imagePreview). const finalLogoImage = imageFile ? imageFile : imagePreview === defaultAvatar ? null : imagePreview; const submissionData = { ...form, logoImage: finalLogoImage, contactNumber: form.phone, contactName: `${form.firstName} ${form.lastName}`.trim(), }; let result; if (formData?.id) { result = await updateTenant(formData.id, submissionData); if (result) { alert("Tenant updated successfully!"); navigate("/tenant/profile", { state: { newTenant: result } }); } else { alert("Failed to update tenant. Please check the form and try again."); } } else { result = await createTenant(submissionData); if (result) { alert("Tenant created successfully!"); navigate("/tenant/profile/subscription", { state: { formData: result } }); } else { alert("Failed to create tenant. Please check the form and try again."); } } }, [form, imagePreview, imageFile, formData, navigate, createTenant, updateTenant] ); const RequiredLabel = ({ label }) => ( ); return (
{formData?.id ? "Update Tenant" : "Create Tenant"}
{/* Form fields */}
Profile Preview setShowImageModal(true)} style={{ width: "100px", height: "100px", objectFit: "cover", borderRadius: "8px", border: "1px solid #ccc", cursor: "pointer", }} />
Allowed JPG, GIF or PNG. Max size of 200KB
{!formData?.id && ( )} {formData?.id && ( )}
setShowImageModal(false)} centered size="lg"> Preview setShowImageSizeModal(false)} centered> Image Size Warning The selected image file must be less than 200KB. Please choose a smaller file.
); }; export default CreateTenant;