import { useState } from 'react';
import Link from '@/core/components/elements/Link/Link';
import Spinner from '@/core/components/elements/Spinner/Spinner';
import useAuth from '@/core/hooks/useAuth';
import { getItemAddress, updateItemAddress } from '@/core/utils/address';
import { useRouter } from 'next/router';
import useAddresses from '../hooks/useAddresses';
import MobileView from '@/core/components/views/MobileView';
import DesktopView from '@/core/components/views/DesktopView';
import Menu from '@/lib/auth/components/Menu';
import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
import { MapPinIcon } from 'lucide-react';

const Addresses = () => {
  const router = useRouter();
  const { select = null } = router.query;
  const { addresses } = useAddresses();
  const selectedAddress = getItemAddress(select || '');
  const [changeConfirmation, setChangeConfirmation] = useState(false);
  const [selectedForChange, setSelectedForChange] = useState(null); // State baru untuk simpan alamat yang akan diubah

  const changeSelectedAddress = (id) => {
    if (!select) return;
    updateItemAddress(select, id);
    router.back();
  };

  const handleConfirmSubmit = () => {
    setChangeConfirmation(false);
    if (selectedForChange) {
      router.push(`/my/address/${selectedForChange}/edit`);
    }
  };

  if (addresses.isLoading) {
    return (
      <div className='flex justify-center my-6'>
        <Spinner className='w-6 text-gray_r-12/50 fill-gray_r-12' />
      </div>
    );
  }

  return (
    <>
      <BottomPopup
        active={changeConfirmation}
        close={() => setChangeConfirmation(false)} // Menutup popup
        title='Ubah alamat Bisnis'
      >
        <div className='leading-7 text-gray_r-12/80'>
          Anda akan mengubah alamat utama bisnis?
        </div>
        <div className='flex mt-6 gap-x-4 md:justify-end'>
          <button
            className='btn-solid-red flex-1 md:flex-none'
            type='button'
            onClick={handleConfirmSubmit}
          >
            Yakin
          </button>
          <button
            className='btn-light flex-1 md:flex-none'
            type='button'
            onClick={() => setChangeConfirmation(false)}
          >
            Batal
          </button>
        </div>
      </BottomPopup>

      <MobileView>
        <div className='p-4'>
          <div className='text-right'>
            <Link href='/my/address/create'>Tambah Alamat</Link>
          </div>

          <div className='grid gap-y-4 mt-4'>
            {addresses.data?.map((address, index) => {
              const type =
                address.type.charAt(0).toUpperCase() +
                address.type.slice(1) +
                ' Address';
              return (
                <AddressCard
                  key={index}
                  address={address}
                  type={type}
                  changeSelectedAddress={changeSelectedAddress}
                  selectedAddress={selectedAddress}
                  setChangeConfirmation={setChangeConfirmation} // Memanggil popup
                  setSelectedForChange={setSelectedForChange} // Simpan id address yang akan diubah
                  select={select}
                />
              );
            })}
          </div>
        </div>
      </MobileView>

      <DesktopView>
        <div className='container mx-auto flex py-10'>
          <div className='w-3/12 pr-4'>
            <Menu />
          </div>
          <div className='w-9/12 p-4 bg-white border border-gray_r-6 rounded'>
            <div className='flex items-center mb-6'>
              <h1 className='text-title-sm font-semibold'>Daftar Alamat</h1>
              <Link
                href='/my/address/create'
                className='btn-solid-red py-2 px-3 !text-gray_r-1 h-fit ml-auto'
              >
                Tambah Alamat
              </Link>
            </div>

            <div className='grid grid-cols-2 gap-4'>
              {addresses.data?.map((address, index) => {
                const type =
                  address.type.charAt(0).toUpperCase() +
                  address.type.slice(1) +
                  ' Address';
                return (
                  <AddressCard
                    key={index}
                    address={address}
                    type={type}
                    changeSelectedAddress={changeSelectedAddress}
                    selectedAddress={selectedAddress}
                    setChangeConfirmation={setChangeConfirmation}
                    setSelectedForChange={setSelectedForChange}
                    select={select}
                  />
                );
              })}
            </div>
          </div>
        </div>
      </DesktopView>
    </>
  );
};

const AddressCard = ({
  address,
  selectedAddress,
  changeSelectedAddress,
  type,
  select,
  setChangeConfirmation,
  setSelectedForChange,
}) => {
  const auth = useAuth();
  const router = useRouter();

  return (
    <div
      className={`p-4 rounded-md border 
        ${
          (selectedAddress && selectedAddress == address.id
            ? 'border-gray_r-7 bg-gray_r-4'
            : 'border-gray_r-7') +
          ' ' +
          (select && 'cursor-pointer hover:bg-gray_r-4 transition')
        }`}
    >
      <div
        onClick={() => changeSelectedAddress(address.id)}
        className={select && 'cursor-pointer'}
      >
        <div className='flex gap-x-2'>
          <div className='badge-red'>{type}</div>
          {auth?.partnerId == address.id && (
            <div className='badge-green'>Utama</div>
          )}
        </div>
        <p className='font-medium mt-2'>{address.name}</p>
        {address.mobile && (
          <p className='mt-2 text-gray_r-11'>{address.mobile}</p>
        )}
        <p className='mt-1 leading-6 text-gray_r-11'>{address.street}</p>

        <div className='flex items-center mt-4'>
          {address.addressMap ? (
            <>
              <MapPinIcon class='h-7 w-8 text-yellow-600 mr-3 font-semibold' />
              <p className='text-yellow-600 font-semibold'>Sudah PinPoint</p>
            </>
          ) : (
            <>
              <MapPinIcon class='h-7 w-8 text-red-600 mr-3 font-semibold' />
              <p className='text-red-600 font-semibold'>Belum PinPoint</p>
            </>
          )}
        </div>
      </div>
      <button
        onClick={() => {
          if (type == 'Contact Address' && auth.parentId) {
            setSelectedForChange(address.id); // Set alamat yang dipilih
            setChangeConfirmation(true); // Tampilkan popup konfirmasi
          } else {
            router.push(`/my/address/${address.id}/edit`);
          }
        }}
        className='btn-light bg-white mt-3 w-full !text-gray_r-11'
      >
        Ubah Alamat
      </button>
    </div>
  );
};

export default Addresses;
