import odooApi from '@/core/api/odooApi'
import BottomPopup from '@/core/components/elements/Popup/BottomPopup'
import LogoSpinner from '@/core/components/elements/Spinner/LogoSpinner'
import { getAuth } from '@/core/utils/auth'
import { useEffect, useState } from 'react'
import { toast } from 'react-hot-toast'
import ImageNext from 'next/image'

const Manifest = ({ idAWB, closePopup }) => {
  const [manifests, setManifests] = useState(null)
  const [isLoading, setIsLoading] = useState(false)

  const formatCustomDate = (date) => {
    const months = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec'
    ]

    const parts = date.split(' ') // Pisahkan tanggal dan waktu
    const [datePart, timePart] = parts
    const [yyyy, mm, dd] = datePart.split('-')
    const [hh, min] = timePart.split(':')

    const monthAbbreviation = months[parseInt(mm, 10) - 1]

    return `${dd} ${monthAbbreviation} ${hh}:${min}`
  }

  const getManifest = async () => {
    setIsLoading(true)
    const auth = getAuth()
    const list = await odooApi(
      'GET',
      `/api/v1/partner/${auth.partnerId}/stock-picking/${idAWB}/tracking`
    )
    setManifests(list)
    setIsLoading(false)
  }

  useEffect(() => {
    if (idAWB) {
      getManifest()
    } else {
      setManifests(null)
    }
  }, [idAWB])

  const [copied, setCopied] = useState(false)

  const handleCopyClick = () => {
    const textToCopy = manifests?.waybillNumber
    navigator.clipboard.writeText(textToCopy)
    setCopied(true)
    toast.success('No Resi Berhasil di Copy')
    setTimeout(() => setCopied(false), 2000) // Reset copied state after 2 seconds
  }

  return (
    <>
      {isLoading && (
        <BottomPopup active={true} close=''>
          <div className='leading-7 text-gray_r-12/80 flex justify-center'>Mohon Tunggu</div>
          <div className='container flex justify-center my-4'>
            <LogoSpinner width={48} height={48} />
          </div>
        </BottomPopup>
      )}
      {!isLoading && (
        <BottomPopup
          key={manifests?.waybillNumber}
          title='Detail Pengiriman'
          active={idAWB}
          close={closePopup}
        >
          <div className='flex justify-between items-center mb-5'>
            <h1 className='text-body-1'>Status Pesanan</h1>
            {manifests?.delivered && (
              <div className='bg-green-100 p-2 rounded '>
                <p className='text-green-600 text-sm'>Pesanan Tiba</p>
              </div>
            )}
            {!manifests?.delivered && (
              <div className='bg-red-100 p-2 rounded '>
                <p className='text-red-600 text-sm'>Sedang Dikirim</p>
              </div>
            )}
          </div>
          <div className=''>
            <h1 className='text-body-1'>
              Estimasi tiba pada <span className='text-gray_r-11 text-sm'>({manifests?.eta})</span>
            </h1>
            <h1 className='text-sm mt-2 mb-3'>
              Dikirim Menggunakan{' '}
              <span className='text-red-500 font-semibold'>{manifests?.deliveryOrder.carrier}</span>
            </h1>
            {manifests?.waybillNumber && (
              <div className='flex justify-between items-center'>
                <h1>No. Resi</h1>
                <div className='flex justify-between gap-x-2 items-center'>
                  <h1 className='font-semibold'>{manifests?.waybillNumber}</h1>
                  <button
                    className={`${copied ? 'text-gray-400' : 'text-red-600 '}`}
                    onClick={() => handleCopyClick()}
                  >
                    <svg
                      aria-hidden='true'
                      fill='none'
                      stroke='currentColor'
                      stroke-width='1.5'
                      viewBox='0 0 24 24'
                      className='w-5 h-6'
                    >
                      <path
                        d='M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 01-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 011.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 00-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 01-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 00-3.375-3.375h-1.5a1.125 1.125 0 01-1.125-1.125v-1.5a3.375 3.375 0 00-3.375-3.375H9.75'
                        stroke-linecap='round'
                        stroke-linejoin='round'
                      ></path>
                    </svg>
                  </button>
                </div>
              </div>
            )}
          </div>
          <hr className='mt-4' />
          <div className='pt-4'>
            <ol class='relative border-l border-gray_r-7'>
              {manifests?.manifests?.map((manifest, index) => (
                <>
                  <li class='mb-6 ml-4' key={index}>
                    {manifests.delivered == true && index == 0 ? (
                      <div
                        class={`absolute w-6 h-6 rounded-full mt-1.5 -left-3 border ${
                          index == 0 ? 'bg-green-100 border-green-100' : 'bg-gray_r-7 border-white'
                        }`}
                      >
                        <ImageNext src='/images/open-box(1).svg' width={30} height={20} />
                      </div>
                    ) : (
                      <div
                        class={`absolute w-3 h-3 rounded-full mt-1.5 -left-1.5 border bg-gray_r-7 border-white`}
                      />
                    )}
                    {manifests.delivered != true && (
                      <div
                        class={`absolute w-3 h-3 rounded-full mt-1.5 -left-1.5 border ${index == 0 ? 'bg-green-600 border-green-600' : 'bg-gray_r-7 border-white'} `}
                      />
                    )}

                    <time class='text-sm leading-none text-gray-400'>
                      {formatCustomDate(manifest.datetime)}
                    </time>
                    {manifests.delivered == true && index == 0 && (
                      <p class={`leading-6 font-semibold text-sm text-green-600 `}>Sudah Sampai</p>
                    )}
                    <p class={`leading-6 text-[12px] text-gray_r-11`}>{manifest.description}</p>
                  </li>
                </>
              ))}
            </ol>
          </div>
        </BottomPopup>
      )}
    </>
  )
}

export default Manifest
