From cf76c139519b8fda880969e151928c203538fd69 Mon Sep 17 00:00:00 2001
From: Miqdad <ahmadmiqdad27@gmail.com>
Date: Sat, 16 Aug 2025 14:31:09 +0700
Subject: <Miqdad> Fix Map

---
 src/lib/address/components/EditAddress.jsx | 222 +++++++++++++++++------------
 1 file changed, 129 insertions(+), 93 deletions(-)

(limited to 'src/lib/address/components/EditAddress.jsx')

diff --git a/src/lib/address/components/EditAddress.jsx b/src/lib/address/components/EditAddress.jsx
index deaa8a3e..6599a764 100644
--- a/src/lib/address/components/EditAddress.jsx
+++ b/src/lib/address/components/EditAddress.jsx
@@ -1,6 +1,6 @@
 import { yupResolver } from '@hookform/resolvers/yup';
 import { useRouter } from 'next/router';
-import { useEffect, useState } from 'react';
+import { useEffect, useState, useMemo } from 'react';
 import * as Yup from 'yup';
 import cityApi from '../api/cityApi';
 import { Controller, useForm } from 'react-hook-form';
@@ -44,35 +44,61 @@ const EditAddress = ({ id, defaultValues }) => {
   const [districts, setDistricts] = useState([]);
   const [subDistricts, setSubDistricts] = useState([]);
   const [tempAddress, setTempAddress] = useState(getValues('addressMap'));
-  const { addressMaps,
+
+  const {
+    addressMaps,
     selectedPosition,
     detailAddress,
     pinedMaps,
-    setPinedMaps } = useMaps();
-
-  
+    setPinedMaps,
+    getDefaultCenter, // penting untuk deteksi default center
+  } = useMaps();
+
+  // Helper: cek apakah benar2 sudah PIN (bukan default center & ada addressMaps)
+  const isPinned = useMemo(() => {
+    if (
+      !selectedPosition ||
+      typeof selectedPosition.lat !== 'number' ||
+      typeof selectedPosition.lng !== 'number'
+    )
+      return false;
+    const dc =
+      typeof getDefaultCenter === 'function'
+        ? getDefaultCenter()
+        : { lat: -6.2, lng: 106.816666 };
+    const nearDefault =
+      Math.abs(selectedPosition.lat - dc.lat) < 1e-4 &&
+      Math.abs(selectedPosition.lng - dc.lng) < 1e-4;
+    return Boolean(addressMaps) && !nearDefault;
+  }, [selectedPosition, addressMaps, getDefaultCenter]);
+
+  // Hanya isi addressMap & lat/lng di form kalau SUDAH PIN
   useEffect(() => {
-    if (addressMaps) {
+    if (addressMaps && isPinned) {
       setTempAddress(addressMaps);
       setValue('addressMap', addressMaps);
+    }
+    if (isPinned && selectedPosition) {
       setValue('longtitude', selectedPosition.lng);
       setValue('latitude', selectedPosition.lat);
     }
-  }, [addressMaps, selectedPosition, setValue]);
-  
+  }, [addressMaps, selectedPosition, isPinned, setValue]);
+
+  // Isi ZIP/Prov dari detailAddress (JANGAN isi street)
   useEffect(() => {
-    if (Object.keys(detailAddress).length > 0) {
+    if (Object.keys(detailAddress || {}).length > 0 && isPinned) {
       setValue('zip', detailAddress.postalCode);
       const selectedState = states.find(
         (state) =>
-          detailAddress?.province.includes(state.label) ||
-        state.label.includes(detailAddress?.province)
+          detailAddress?.province?.includes(state.label) ||
+          state.label?.includes(detailAddress?.province)
       );
-      setValue('state', selectedState?.value);  
-      setValue('street', detailAddress?.street);      
+      setValue('state', selectedState?.value);
+      // jangan override street:
+      // setValue('street', detailAddress?.street);
     }
-  }, [detailAddress, setValue]);
-  
+  }, [detailAddress, states, isPinned, setValue]);
+
   useEffect(() => {
     const loadProfile = async () => {
       const dataProfile = await addressApi({ id: auth.partnerId });
@@ -88,8 +114,8 @@ const EditAddress = ({ id, defaultValues }) => {
       setValue('subDistrict', dataProfile.subDistrict?.id);
     };
     if (auth) loadProfile();
-  }, [auth?.parentId]);
-  
+  }, [auth?.parentId, setValue]);
+
   useEffect(() => {
     const loadStates = async () => {
       let dataStates = await stateApi({ tempo: false });
@@ -101,7 +127,7 @@ const EditAddress = ({ id, defaultValues }) => {
     };
     loadStates();
   }, []);
-  
+
   const watchState = watch('state');
   useEffect(() => {
     setValue('city', '');
@@ -122,63 +148,64 @@ const EditAddress = ({ id, defaultValues }) => {
       loadCities();
     }
   }, [watchState, setValue, getValues]);
-  
+
   useEffect(() => {
-    if (Object.keys(detailAddress).length > 0) {
-      const selectedCities = cities.find(
-          (city) => 
-            city.label.toLowerCase() === detailAddress?.district.toLowerCase()
-        ) || cities.find(
+    if (Object.keys(detailAddress || {}).length > 0 && isPinned) {
+      const selectedCities =
+        cities.find(
           (city) =>
-            detailAddress?.district.toLowerCase().includes(city.label.toLowerCase()) ||
-            city.label.toLowerCase().includes(detailAddress?.district.toLowerCase())
+            city.label.toLowerCase() === detailAddress?.district?.toLowerCase()
+        ) ||
+        cities.find(
+          (city) =>
+            detailAddress?.district
+              ?.toLowerCase()
+              .includes(city.label.toLowerCase()) ||
+            city.label
+              .toLowerCase()
+              .includes(detailAddress?.district?.toLowerCase())
         );
-          setValue('city', selectedCities?.value);
-        }
-      }, [cities, detailAddress, setValue]);
-      
-      const watchCity = watch('city');
-      useEffect(() => {
-        if (watchCity) {
-          // setValue('district', '');
-          const loadDistricts = async () => {
-            let dataDistricts = await districtApi({ cityId: watchCity });
-            dataDistricts = dataDistricts.map((district) => ({
-              value: district.id,
-              label: district.name,
+      setValue('city', selectedCities?.value);
+    }
+  }, [cities, detailAddress, isPinned, setValue]);
+
+  const watchCity = watch('city');
+  useEffect(() => {
+    if (watchCity) {
+      const loadDistricts = async () => {
+        let dataDistricts = await districtApi({ cityId: watchCity });
+        dataDistricts = dataDistricts.map((district) => ({
+          value: district.id,
+          label: district.name,
         }));
         setDistricts(dataDistricts);
         let oldDistrict = getValues('oldDistrict');
         if (oldDistrict) {
-          // setValue('district', oldDistrict);
           setValue('oldDistrict', '');
         }
       };
       loadDistricts();
     }
   }, [watchCity, setValue, getValues]);
-  
+
   useEffect(() => {
-    if (Object.keys(detailAddress).length > 0) {
+    if (Object.keys(detailAddress || {}).length > 0 && isPinned) {
       const selectedDistrict = districts.find(
         (district) =>
-          detailAddress.subDistrict
-            .toLowerCase()
+          detailAddress?.subDistrict
+            ?.toLowerCase()
             .includes(district.label.toLowerCase()) ||
           district.label
             .toLowerCase()
-            .includes(detailAddress.subDistrict.toLowerCase())
+            .includes(detailAddress?.subDistrict?.toLowerCase())
       );
       setValue('district', selectedDistrict?.value);
     }
-  }, [districts, detailAddress, setValue]);
-  
-  
-  
+  }, [districts, detailAddress, isPinned, setValue]);
+
   const watchDistrict = watch('district');
   useEffect(() => {
     if (watchDistrict) {
-      // setValue('subDistrict', '');
       const loadSubDistricts = async () => {
         let dataSubDistricts = await subDistrictApi({
           districtId: watchDistrict,
@@ -199,29 +226,27 @@ const EditAddress = ({ id, defaultValues }) => {
     }
   }, [watchDistrict, setValue, getValues]);
 
-  
   useEffect(() => {
-    if (Object.keys(detailAddress).length > 0) {
+    if (Object.keys(detailAddress || {}).length > 0 && isPinned) {
       const selectedSubDistrict = subDistricts.find(
         (district) =>
-          detailAddress.village
-            .toLowerCase()
+          detailAddress?.village
+            ?.toLowerCase()
             .includes(district.label.toLowerCase()) ||
-            district.label
+          district.label
             .toLowerCase()
-            .includes(detailAddress.village.toLowerCase())
-          );
-
-          setValue('subDistrict', selectedSubDistrict?.value);
+            .includes(detailAddress?.village?.toLowerCase())
+      );
+      setValue('subDistrict', selectedSubDistrict?.value);
     }
-  }, [subDistricts, detailAddress, setValue]);
+  }, [subDistricts, detailAddress, isPinned, setValue]);
 
   useEffect(() => {
     if (id) {
       setValue('id', id);
     }
   }, [id, setValue]);
-  
+
   const onSubmitHandler = async (values) => {
     const data = {
       ...values,
@@ -230,20 +255,32 @@ const EditAddress = ({ id, defaultValues }) => {
       city_id: parseInt(values.city, 10),
       district_id: parseInt(values.district, 10),
       sub_district_id: parseInt(values.subDistrict, 10),
-      longtitude: selectedPosition?.lng,
-      latitude: selectedPosition?.lat,
-      address_map: addressMaps,
     };
+
+    // kirim koordinat + address_map + use_pin HANYA jika sudah PIN
+    if (isPinned) {
+      data.longtitude = selectedPosition?.lng;
+      data.latitude = selectedPosition?.lat;
+      data.address_map = addressMaps || values.addressMap;
+      data.use_pin = true;
+    } else {
+      data.use_pin = false;
+      // pastikan tidak ada nilai default center yang ikut terkirim
+      delete data.longtitude;
+      delete data.latitude;
+      delete data.address_map;
+    }
+
     if (!auth.company) {
       data.alamat_lengkap_text = values.street;
     }
+
     try {
       const address = await editAddressApi({ id, data });
       console.log('Response address:', address);
 
       let isUpdated = null;
 
-      // Jika company dan partnerId sama dengan id, maka update data alamat wajib pajak
       const isCompanyEditingSelf = auth.company && auth.partnerId == id;
 
       if (isCompanyEditingSelf) {
@@ -260,15 +297,13 @@ const EditAddress = ({ id, defaultValues }) => {
           mobile: values.mobile,
         };
 
-        const isUpdated = await editPartnerApi({
+        const isUpdatedRes = await editPartnerApi({
           id: auth.partnerId,
           data: dataAlamat,
         });
-
-        console.log('Response isUpdated:', isUpdated);
+        console.log('Response isUpdated:', isUpdatedRes);
       }
 
-      // Validasi kondisi sukses
       const isSuccess = !!address?.id;
 
       if (isSuccess) {
@@ -286,19 +321,8 @@ const EditAddress = ({ id, defaultValues }) => {
       toast.error(error?.message || 'Terjadi kesalahan tidak terduga.');
     }
 
-    
     const dataProfile = await addressApi({ id: auth.partnerId });
     console.log('ini adalah', dataProfile);
-
-
-    // if (isUpdated?.id) {
-    // if (address?.id && auth.company ? isUpdated?.id : true) {
-    //   toast.success('Berhasil mengubah alamat');
-    //   router.back();
-    // } else {
-    //   toast.error('Terjadi kesalahan internal');
-    //   router.back();
-    // }
   };
 
   return (
@@ -310,12 +334,11 @@ const EditAddress = ({ id, defaultValues }) => {
         close={() => setPinedMaps(false)}
       >
         <div className='flex mt-4'>
-          <PinPointMap 
-              initialLatitude={selectedPosition?.lat} 
-              initialLongitude={selectedPosition?.lng} 
-              initialAddress={tempAddress} 
-            />
-
+          <PinPointMap
+            initialLatitude={selectedPosition?.lat}
+            initialLongitude={selectedPosition?.lng}
+            initialAddress={tempAddress}
+          />
         </div>
       </BottomPopup>
       <div className='max-w-none md:container mx-auto flex p-0 md:py-10'>
@@ -334,15 +357,28 @@ const EditAddress = ({ id, defaultValues }) => {
               <label className='form-label mb-2'>Koordinat Alamat</label>
               {tempAddress ? (
                 <div className='flex gap-x-2 items-center'>
-                  <button type='button' className="flex items-center justify-center me-3 p-2 badge-solid-red text-white rounded-full hover:bg-red-500 transition">
-                  <MapPinIcon class='h-6 w-6' onClick={() => setPinedMaps(true)} />{' '}
-                    </button>
+                  <button
+                    type='button'
+                    className='flex items-center justify-center me-3 p-2 badge-solid-red text-white rounded-full hover:bg-red-500 transition'
+                  >
+                    <MapPinIcon
+                      className='h-6 w-6'
+                      onClick={() => setPinedMaps(true)}
+                    />
+                  </button>
                   <span> {tempAddress} </span>
                 </div>
               ) : (
-                <Button variant='plain' style={{ padding: 0 }} onClick={() => setPinedMaps(true)}>
-                  <button type='button' className="flex items-center justify-center me-3 p-2 badge-solid-red text-white rounded-full hover:bg-red-500 transition">
-                    <MapPinIcon className="h-6 w-6" />
+                <Button
+                  variant='plain'
+                  style={{ padding: 0 }}
+                  onClick={() => setPinedMaps(true)}
+                >
+                  <button
+                    type='button'
+                    className='flex items-center justify-center me-3 p-2 badge-solid-red text-white rounded-full hover:bg-red-500 transition'
+                  >
+                    <MapPinIcon className='h-6 w-6' />
                   </button>
                   Pin Koordinat Alamat
                 </Button>
@@ -530,4 +566,4 @@ const types = [
   { value: 'other', label: 'Other Address' },
 ];
 
-export default EditAddress;
+export default EditAddress;
\ No newline at end of file
-- 
cgit v1.2.3

