import { Button } from "antd";
import axios from "axios";
import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import baseUrl from "../../../../array/base/config";
import { toast } from "react-toastify";
const addressTypeArray = ["CURRENT", "MAILING"];
/**
* EditAddressForm component for editing user address information.
*
* @param {Object} props - The component's props.
* @param {Object} props.address - The address data to edit.
* @param {function} props.setShowAddForm - Function to control the visibility of the add form.
* @param {function} props.setShowEditForm - Function to control the visibility of the edit form.
* @returns {JSX.Element} - React component for editing user address information.
*/
const EditAddressForm = ({ address, setshsetShowAddForm, setShowEditForm }) => {
const [municipality, setMunicipality] = useState([]);
const [province, setProvince] = useState([]);
const [district, setDistrict] = useState([]);
const [addressType, setAddressType] = useState(address?.address_type);
const [countryId, setCountryId] = useState(1);
const [municipalityId, setMunicipalityId] = useState(address?.municipality?.id);
const [provinceId, setProvinceId] = useState(address?.province?.id);
const [districtId, setDistrictId] = useState(address?.district?.id);
const [wardId, setWardId] = useState(address?.ward?.id);
console.log()
const [value, setValue] = useState(1);
console.log("the address to edit in editform", address);
const [wardLimit, setWardLimit] = useState(null);
const min = null;
const handleChange = (event) => {
const value = Math.max(
min,
Math.min(wardLimit, Number(event.target.value))
);
setValue(value);
setWardId(parseInt(event.target.value));
};
useEffect(() => {
municipalityApiCall();
}, [districtId]);
useEffect(() => {
DistrictApiCall();
}, [provinceId]);
useEffect(() => {
ProvinceApiCall();
}, [countryId]);
useEffect(() => {
setWardLimitFunction();
}, [municipalityId]);
const setWardLimitFunction = () => {
if (municipalityId) {
const selectedMunicipality = municipality.find(
(m) => m.id === municipalityId
);
if (selectedMunicipality) {
const wardLimit = selectedMunicipality.ward_limit;
console.log("ward limit", wardLimit);
setWardLimit(wardLimit);
}
}
};
const municipalityApiCall = async () => {
try {
const detail = localStorage.getItem("token");
const response = await axios({
method: "get",
url: `${baseUrl}/api/municipality/`,
headers: {
Authorization: `Token ${detail}`,
},
});
if (districtId) {
const filteredData = response.data.data.results.filter(
(obj) => obj.district === districtId
);
setMunicipality(filteredData);
} else {
setMunicipality(response.data.data.results);
}
} catch (err) {
console.log(err);
}
};
const ProvinceApiCall = async () => {
try {
const detail = localStorage.getItem("token");
const response = await axios({
method: "get",
url: `${baseUrl}/api/province/`,
headers: {
Authorization: `Token ${detail}`,
},
});
// console.log("Received Province list data", response.data.data.results);
const filteredData = response.data.data.results.filter(
(obj) => obj.country === 1
);
setProvince(filteredData);
} catch (err) {
console.log(err);
}
};
const DistrictApiCall = async () => {
try {
const detail = localStorage.getItem("token");
const response = await axios({
method: "get",
url: `${baseUrl}/api/district/`,
headers: {
Authorization: `Token ${detail}`,
},
});
// console.log("Received district list data", response.data.data.results);
// Update state variable
if (provinceId) {
// console.log("province id in district api call", provinceId);
const filteredData = response.data.data.results.filter(
(obj) => obj.province === provinceId
);
setDistrict(filteredData);
} else {
setDistrict(response.data.data.results);
}
} catch (err) {
console.log(err);
}
};
const addAddressCall = () => {
event.preventDefault();
if (!provinceId) {
toast.error("Province field is required!", {
position: "top-right",
autoClose: 5001,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
return;
}
// console.log(address_type, country, )
const formData = new FormData();
addressType && formData.append("address_type", addressType);
countryId && formData.append("country", parseInt(countryId));
provinceId && formData.append("province", parseInt(provinceId));
districtId && formData.append("district", parseInt(districtId));
municipalityId && formData.append("municipality", parseInt(municipalityId));
wardId && formData.append("ward", parseInt(wardId));
const detail = localStorage.getItem("token");
axios
.put(`${baseUrl}/api/shareholderaddress/${address?.id}/`, formData, {
headers: {
Authorization: `Token ${detail}`,
"Content-Type": "multipart/form-data",
},
})
.then((response) => {
toast.success("Address updated successfully!", {
position: "top-right",
autoClose: 5001,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
})
.catch((error) => {
console.error(error);
toast.error("Address could not be updated. Please try again.", {
position: "top-right",
autoClose: 5001,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
});
};
const handleSubmit = () => {
addAddressCall();
};
return (
<div>
<form onSubmit={handleSubmit}>
<div>
<div className="row">
<div className="col-lg-3">
<div className="sharetransfer_form_group">
<select
defaultValue={address?.address_type}
id="addressType"
onChange={(e) => setAddressType(e.target.value)}
>
<option value="">Choose address type</option>
{addressTypeArray.map((dat, i) => {
return (
<option key={i} value={dat}>
{dat}
</option>
);
})}
</select>
</div>
</div>
<div className="col-lg-3">
<div>
{
<div className="sharetransfer_form_group">
<select
id="countryDropdown"
onChange={(e) => setCountryId(parseInt(e.target.value))}
>
<option key={1} value={1}>
Nepal
</option>
</select>
</div>
}
</div>
</div>
<div className="col-lg-3">
<div>
{province && (
<div className="sharetransfer_form_group">
<select
defaultValue={address?.province?.name}
id="provinceDropdown"
onChange={(e) => setProvinceId(parseInt(e.target.value))}
>
<option value="">Choose a province</option>
{province.map((dat) => {
return (
<option key={dat.id} value={dat.id}>
{dat.name}
</option>
);
})}
</select>
</div>
)}
</div>
</div>
<div className="col-lg-3">
<div>
{district && (
<div className="sharetransfer_form_group">
<select defaultValue={address?.district?.name}
id="districtDropdown"
onChange={(e) => setDistrictId(parseInt(e.target.value))}
>
<option value="">Choose a district</option>
{district.map((dat) => {
return (
<option key={dat.id} value={dat.id}>
{dat.name}
</option>
);
})}
</select>
</div>
)}
</div>
</div>
<div className="col-lg-3">
<div>
{municipality && (
<div className="sharetransfer_form_group">
<select defaultValue={address?.municipality?.name}
id="municipalityDropdown"
onChange={(e) => setMunicipalityId(parseInt(e.target.value))}
>
<option value="">Choose a municipality</option>
{municipality.map((dat) => {
return (
<option key={dat.id} value={dat.id}>
{dat.name}
</option>
);
})}
</select>
</div>
)}
</div>
</div>
<div className="col-lg-3">
<div className="sharetransfer_form_group">
{/* <label>Enter ward number</label> */}
<input
type="number"
id="ward"
placeholder="Enter ward number"
max={wardLimit || undefined}
onChange={(e) => setWardId(parseInt(e.target.value))}
/>
</div>
</div>
</div>
<div className="row d-flex justify-end">
<div className="col-lg-3">
<div className="d-flex align-items-center justify-between">
<Button onClick={()=>{setShowEditForm((prev)=>!prev)}} className="cancel-btn">Cancel</Button>
<button className="sharetransfer_button" type="submit">
Add Address
</button>
</div>
</div>
</div>
</div>
</form>
</div>
);
};
export default EditAddressForm;
Source