import React, { useState, useEffect, useRef, useCallback } from "react"; import axios from "axios"; import { Box, Typography, Grid, Paper, Avatar, IconButton, Dialog, DialogContent, DialogTitle, Autocomplete, TextField, } from "@mui/material"; import { useParams, useNavigate } from "react-router-dom"; import { format } from "date-fns"; import { isAutheticated } from "../../auth"; import CancelIcon from "@mui/icons-material/Cancel"; // Add this import import { City, State } from "country-state-city"; import { Modal, Button } from "react-bootstrap"; import swal from "sweetalert"; const SingleRetailDistributor = () => { const { id } = useParams(); const [retailerDetails, setRetailerDetails] = useState(null); const [openPopup, setOpenPopup] = useState(false); const [selectedImage, setSelectedImage] = useState(""); const token = isAutheticated(); const navigate = useNavigate(); const [userAllAddress, setUserAllAddress] = useState([]); const [tradeName, setTradeName] = useState(null); const [showModal, setShowModal] = useState(false); const [isEditMode, setIsEditMode] = useState(false); const [stateOptions, setStateOptions] = useState([]); const [cityOptions, setCityOptions] = useState([]); const [selectedState, setSelectedState] = useState(null); const [selectedCity, setSelectedCity] = useState(null); const [currentAddress, setCurrentAddress] = useState({ Name: "", tradeName: "", phoneNumber: "", street: "", district: "", city: "", state: "", postalCode: "", country: "India", isDefault: false, }); // Fetch states when the component mounts useEffect(() => { const fetchStates = () => { const states = State.getStatesOfCountry("IN").map((state) => ({ label: state.name, value: state.isoCode, })); setStateOptions(states); }; fetchStates(); }, []); // Fetch cities when a state is selected useEffect(() => { const fetchCities = () => { if (selectedState) { const cities = City.getCitiesOfState("IN", selectedState.value).map( (city) => ({ label: city.name, value: city.name, }) ); setCityOptions(cities); } else { setCityOptions([]); // Clear cities if no state is selected } }; fetchCities(); }, [selectedState]); // Open modal for add or edit mode const handleOpenModal = (address = null) => { setIsEditMode(!!address); // Set edit mode if address is provided const initialAddress = address || { Name: "", tradeName: tradeName, phoneNumber: "", street: "", district: "", city: "", state: "", postalCode: "", country: "India", isDefault: false, }; setCurrentAddress(initialAddress); // Fetch city options based on the state from the backend if (address) { const state = stateOptions.find((option) => option.label === address.state) || null; // Set selected state from backend address setSelectedState(state); // Fetch cities if state is found if (state) { const cities = City.getCitiesOfState("IN", state.value).map((city) => ({ label: city.name, value: city.name, })); setCityOptions(cities); // Set selected city if it exists in the fetched city options const city = cities.find((option) => option.label === address.city) || null; setSelectedCity(city); // Set the selected city } } else { setSelectedState(null); setSelectedCity(null); setCityOptions([]); // Clear city options if no address is provided } setShowModal(true); }; // Close modal without saving changes const handleCloseModal = () => { setShowModal(false); // Reset selections to previous state when modal is closed setSelectedState(null); // Reset state selection setSelectedCity(null); // Reset city selection setCurrentAddress({ Name: "", tradeName: "", phoneNumber: "", street: "", district: "", city: "", state: "", postalCode: "", country: "India", isDefault: false, }); }; // Save address logic for adding or updating const handleSaveAddress = async () => { try { const updatedAddress = { ...currentAddress, tradeName: tradeName, }; const apiUrl = isEditMode ? `/api/rd/shipping/address/update/${currentAddress._id}` : `/api/rd/shipping/address/admin/new/${id}`; // console.log(currentAddress); const method = isEditMode ? "patch" : "post"; // Prepare the headers with the token const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }; // Make the API call with the headers await axios[method](apiUrl, updatedAddress, { headers }); swal( "Success!", `Address ${isEditMode ? "updated" : "added"} successfully!`, "success" ); handleCloseModal(); getUserAddress(); } catch (error) { console.error("Error saving address:", error); swal("Error!", "There was an error saving the address.", "error"); } }; const handleStateChange = (event, newValue) => { setSelectedState(newValue); setCurrentAddress((prev) => ({ ...prev, state: newValue ? newValue.label : "", city: "", // Clear city when state changes })); setSelectedCity(null); // Reset city selection setCityOptions([]); // Clear city options on state change }; const handleCityChange = (event, newValue) => { setSelectedCity(newValue); setCurrentAddress((prev) => ({ ...prev, city: newValue ? newValue.label : "", })); }; // Fetch Shipping address of the individual user const getUserAddress = useCallback(async () => { try { const response = await axios.get( `/api/rd/shipping/address/user/address/${id}`, { headers: { Authorization: `Bearer ${token}`, }, } ); // console.log(response.data); setUserAllAddress(response.data?.UserShippingAddress || []); } catch (error) { swal({ title: "Warning", text: error.message, icon: "error", button: "Close", dangerMode: true, }); } }, [id, token]); const handledeleteAddress = async (address_id) => { try { const response = await axios.delete( `/api/rd/shipping/address/delete/${address_id}`, // Address ID in the URL { headers: { Authorization: `Bearer ${token}`, // Authorization header }, data: { userId: id }, // User ID in the request body } ); swal({ title: "Success", text: response.data.message, icon: "success", button: "Close", }); getUserAddress(); } catch (error) { // Handle errors here, ensuring that you access the error message correctly swal({ title: "Warning", text: error.response?.data?.message || error.message, // Improved error handling icon: "error", button: "Close", dangerMode: true, }); } }; const getUserDetails = useCallback(async () => { try { // Commented out the API call and using dummy data const response = await axios.get(`/api/getRD/${id}`, { headers: { "Access-Control-Allow-Origin": "*", Authorization: `Bearer ${token}`, "Content-Type": "multipart/form-data", }, }); setRetailerDetails(response.data); // console.log('Retailer Details: ', response.data); setTradeName(response.data?.kyc?.trade_name || ""); } catch (error) { console.error("Error fetching data: ", error); } }, [id, token]); // Fetch retailer details on mount useEffect(() => { getUserDetails(); getUserAddress(); }, [id, getUserDetails, getUserAddress]); const handleOpenPopup = (imageUrl) => { setSelectedImage(imageUrl); setOpenPopup(true); }; const handleClosePopup = () => { setOpenPopup(false); setSelectedImage(""); }; const handleCancel = () => { navigate("/retail-distributor"); }; if (!retailerDetails) { return Loading...; } return ( Retailer Details Cancel Retailer Details Unique Id: {retailerDetails.uniqueId} Trade Name: {retailerDetails.kyc.trade_name} Name: {retailerDetails.name} Mobile Number: {retailerDetails.mobile_number} Email: {retailerDetails.email} Address: {retailerDetails.kyc.address} Town/City: {retailerDetails.kyc.city} District: {retailerDetails.kyc.district} State: {retailerDetails.kyc.state} Pincode: {retailerDetails.kyc.pincode} Mapped Principal Distributor:{" "} {retailerDetails?.principal_distributer?.name || "Not Mapped"} Documents PAN Number: {retailerDetails.kyc.pan_number} {retailerDetails?.kyc?.pan_img ? ( handleOpenPopup(retailerDetails?.kyc?.pan_img?.url) } /> ) : ( Img not available )} Aadhar Number:{" "} {retailerDetails.kyc.aadhar_number} {retailerDetails?.kyc?.aadhar_img ? ( handleOpenPopup(retailerDetails?.kyc?.aadhar_img?.url) } /> ) : ( Img not available )} GST Number: {retailerDetails.kyc.gst_number} {retailerDetails?.kyc?.gst_img ? ( handleOpenPopup(retailerDetails?.kyc?.gst_img?.url) } /> ) : ( Img not available )} Pesticide License: {retailerDetails?.kyc?.pesticide_license_img ? ( handleOpenPopup( retailerDetails?.kyc?.pesticide_license_img?.url ) } /> ) : ( Img not available )} Fertilizer License (optional): {retailerDetails?.kyc?.fertilizer_license_img ? ( handleOpenPopup( retailerDetails?.kyc?.fertilizer_license_img?.url ) } /> ) : ( Img not available )} Selfie of Entrance Board: {retailerDetails?.kyc?.selfie_entrance_img ? ( handleOpenPopup( retailerDetails?.kyc?.selfie_entrance_img?.url ) } /> ) : ( Img not available )} Sales Coordinators/Territory Manager Details Designation:{" "} {retailerDetails?.userType || "Not Available"} Name:{" "} {retailerDetails?.addedBy?.name || "Not Available"} ID:{" "} {retailerDetails?.addedBy?.uniqueId || "Not Available"} {/* Address of retail distributor */}
• Addresses{" "}
• Total Addresses: {userAllAddress?.length || 0}{" "}
{userAllAddress?.length > 0 && (
{userAllAddress?.map((address, i) => ( ))}
SL No. Trade Name RD Name Address Default Action
{i + 1} {address?.tradeName ? `${address.tradeName}` : "No Trade Name"} {address?.Name ? `${address.Name}` : "No RD Name"} {address?.street}, {address?.city}, {address?.district}, {address?.state},{" "} {address?.country}, {address?.postalCode} {address.isDefault ? "Yes" : "No"}
)} {/* Modal for Adding/Editing Address */} {isEditMode ? "Edit Shipping Address" : "Add Shipping Address"}
{/* Name and Trade Name */}
setCurrentAddress({ ...currentAddress, Name: e.target.value, }) } className="form-control mb-3" placeholder="Enter name" />
setCurrentAddress({ ...currentAddress, tradeName: e.target.value, }) } className="form-control mb-3" placeholder="Enter trade name" />
{/* Phone Number and Street */}
setCurrentAddress({ ...currentAddress, phoneNumber: e.target.value, }) } className="form-control mb-3" placeholder="Enter phone number" />
setCurrentAddress({ ...currentAddress, street: e.target.value, }) } className="form-control mb-3" placeholder="Enter street" />
{/* State and City */}
( )} />
option.value === value.value } renderInput={(params) => ( )} />
{/* Postal Code and Country */}
setCurrentAddress({ ...currentAddress, postalCode: e.target.value, }) } className="form-control mb-3" placeholder="Enter postal code" />
setCurrentAddress({ ...currentAddress, district: e.target.value, }) } className="form-control mb-3" placeholder="Enter District" />
Large Preview
); }; export default SingleRetailDistributor;