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"

const Addresses = () => {
  const router = useRouter()
  const {
    select = null
  } = router.query
  const auth = useAuth()
  const { addresses } = useAddresses()
  const selectedAdress = getItemAddress(select || '')
  const changeSelectedAddress = (id) => {
    if (!select) return
    updateItemAddress(select, id)
    router.back()
  }

  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 (
    <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) => {
          let type = address.type.charAt(0).toUpperCase() + address.type.slice(1) + ' Address';
          return (
            <div 
              key={index} 
              className={"p-4 rounded-md border " + (selectedAdress && selectedAdress == address.id ? "border-gray_r-7 bg-gray_r-2" : "border-gray_r-7") } 
            >
              <div onClick={() => changeSelectedAddress(address.id)}>
                <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 ${selectedAdress && selectedAdress == address.id ? "text-gray_r-12" : "text-gray_r-11"}`}>
                  { address.street }
                </p>
              </div>
              <Link href={`/my/address/${address.id}/edit`} className="btn-light bg-white mt-3 w-full !text-gray_r-11">Ubah Alamat</Link>
            </div>
          );
        }) }
      </div>
    </div>
  )
}

export default Addresses