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';
import { list } from 'postcss';
import InformationSection from './InformationSection';
import Link from 'next/link';

function capitalizeFirstLetter(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

function capitalizeWords(str) {
  return str
    .split(' ')
    .map((word) => capitalizeFirstLetter(word))
    .join(' ');
}

function mappingLiveTracking(kurir, resi){
  let url = null
  switch (kurir){
    case('grab'):
      url = 'https://express.grab.com/track/orders?ids='+resi
      break;
    default:
      url = false
  }

  return url
}

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();
    let list;
    if (auth) {
      list = await odooApi(
        'GET',
        `/api/v1/partner/${auth.partnerId}/stock-picking/${idAWB}/tracking`
      );
    } else {
      list = await odooApi('GET', `/api/v1/stock-picking/${idAWB}/tracking`);
    }
    setManifests(list);
    setIsLoading(false);
  };

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

  const isLiveTracking = mappingLiveTracking(manifests?.deliveryOrder?.carrier.toLowerCase(), manifests?.waybillNumber)

  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='Lacak Pengiriman'
          active={idAWB}
          close={closePopup}
        >
          <div className='flex justify-between items-center mb-5'>
            <h1 className='text-body-1'>Status Pesanan</h1>
            {manifests?.status === 'completed' && (
              <div className='bg-green-100 p-2 rounded '>
                <p className='text-green-600 text-sm'>Pesanan Tiba</p>
              </div>
            )}
            {manifests?.status === 'shipment' && (
              <div className='bg-yellow-100 p-2 rounded '>
                <p className='text-yellow-600 text-sm'>Sedang Dikirim</p>
              </div>
            )}
            {manifests?.status === 'cancelled' && (
              <div className='bg-red-800 p-2 rounded '>
                <p className='text-white text-sm'>Di Batalkan</p>
              </div>
            )}
            {manifests?.status === 'on_hold' && (
              <div className='bg-red-800 p-2 rounded '>
                <p className='text-white text-sm'>Ditunda Sementara </p>
              </div>
            )}
            {manifests?.status === 'pending' && (
              <div className='bg-red-100 p-2 rounded '>
                <p className='text-red-600 text-sm'>Pending</p>
              </div>
            )}
          </div>

          <InformationSection manifests={manifests} />

          <hr className='mt-4' />
          {manifests?.isDelay && (
            <div
              class='flex items-center p-4 mb-4 text-sm text-yellow-800 rounded-lg bg-yellow-50'
              role='alert'
            >
              <svg
                class='flex-shrink-0 inline w-4 h-4 mr-3'
                aria-hidden='true'
                fill='currentColor'
                viewBox='0 0 20 20'
              >
                <path d='M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3H8a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z' />
              </svg>
              <div>Pesanan anda mungkin mengalami keterlambatan tiba</div>
            </div>
          )}
          <div className='pt-4'>
            <ol className='relative'>
              {manifests?.manifests?.map((manifest, index) => {
                const isFirst = index === 0;
                const isDelivered = manifests.delivered === true;
                const isBiteship = manifests.isBiteship === true;
                const statusTitle =
                  isDelivered && isFirst && !isBiteship
                    ? 'Pesanan sampai'
                    : isBiteship
                    ? capitalizeWords(manifest.status)
                    : '';

                return (
                  <li
                    className='grid grid-cols-[80px_20px_1fr] gap-2 mb-6 items-start'
                    key={index}
                  >
                    {/* Kolom 1: Tanggal + Jam */}
                    <div className='text-sm text-gray-400 whitespace-nowrap'>
                      {formatCustomDate(manifest.datetime)}
                    </div>

                    {/* Kolom 2: Bullet/Poin */}
                    <div className='relative flex items-start justify-center pt-1'>
                      <div
                        className={`w-3 h-3 rounded-full border ${
                          index === 0 && manifests.delivered
                            ? 'bg-green-600 border-green-600'
                            : 'bg-gray-400 border-white'
                        }`}
                      />
                    </div>

                    {/* Kolom 3: Status dan Deskripsi */}
                    <div>
                      <p className='text-sm font-semibold text-green-600'>
                        {manifests?.deliveryOrder.carrier != 'Self Pick Up'
                          ? capitalizeWords(manifest.status)
                          : ''}
                      </p>
                      <p
                        className='text-xs text-gray-600'
                        dangerouslySetInnerHTML={{
                          __html: manifest.description,
                        }}
                      />
                    </div>
                  </li>
                );
              })}
            </ol>
          </div>
          <div className='pt-2'>
            {
              isLiveTracking &&
                manifests?.status === 'shipment' && (
                  <Link
                    href={isLiveTracking}
                    target="_blank" 
                    rel="noopener noreferrer"
                    className="inline-block px-4 py-2 bg-red-600 text-white font-semibold rounded-lg shadow-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-400 focus:ring-opacity-75"
                  >
                    Live Tracking
                  </Link>
                )
            }
          </div>
          
        {/* Barang */}
        <div className='mt-1'>
          {Array.isArray(manifests?.products) && manifests.products.length > 0 ? (
            <div className='flex flex-col gap-4'>
              {manifests.products.map((product, idx) => (
                <div key={idx} className='flex gap-4 border-b pb-4'>
                  {/* Gambar Produk */}
                  <img
                    src={product.image}
                    alt={product.name}
                    className='w-16 h-16 object-contain border'
                  />
                  {/* Info Produk */}
                  <div className='flex flex-col flex-1'>
                    <span className='font-semibold'>{product.name}</span>
                    <span className='text-sm text-gray-500'>{product.code}</span>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <span></span>
          )}
        </div>
        </BottomPopup>
      )}
    </>
  );
};

export default Manifest;
