import Link from 'next/link';
import Image from '~/components/ui/image';
import whatsappUrl from '@/core/utils/whatsappUrl';
import { useEffect, useState } from 'react';
import odooApi from '@/core/api/odooApi';
import useDevice from '@/core/hooks/useDevice';
import useAuth from '@/core/hooks/useAuth';
import axios from 'axios';
import { toast } from 'react-hot-toast';

const FinishTempo = ({ query }) => {
  const [data, setData] = useState();
  const [transactionData, setTransactionData] = useState();
  const { isDesktop, isMobile } = useDevice();
  const auth = useAuth();

  const so_order = query?.order_id?.replaceAll('-', '/');
  useEffect(() => {
    const fetchData = async () => {
      const fetchedData = await odooApi(
        'GET',
        `/api/v1/sale_order_number?sale_number=${so_order}`
      );
      setData(fetchedData[0]);
    };
    fetchData();
  }, [query]);

  // Kirim email ketika komponen ini dimount atau sesuai kondisi
  const sendEmail = async () => {
    try {
      const send = await axios.post(
        `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/finish-checkout?orderName=${query?.order_id}`,
        {}
      );
      if (send.status === 200) {
        toast.success('Berhasil mengirim rincian pesanan');
      } else {
        toast.error('Gagal mengirimkan rincian pesanan');
      }
    } catch (error) {
      console.error(error);
      toast.error('Gagal mengirimkan rincian pesanan');
    }
  };

  return (
    <div className='flex flex-col items-center'>
      <Image
        src='/images/CHECKOUT-PESANAN.svg'
        alt='Checkout Pesanan'
        width={isMobile ? 300 : 450}
        height={isMobile ? 300 : 450}
      />
      <div className='text-title-sm md:text-title-lg text-center font-semibold'>
        Terima Kasih atas Pembelian Kamu
      </div>
      <div className='flex flex-col justify-center items-center text-body-2 md:text-body-1 text-center mt-3 px-24 md:px-36 py-4 border-2 gap-y-2 rounded'>
        <p className='font-bold'>No. Transaksi</p>
        <p className='mb-2 font-medium text-red-500 text-xl'>
          {query?.order_id?.replaceAll('-', '/')}
        </p>
        <Link
          href={`/my/quotations/${data?.id}`}
          className='btn-solid-red rounded-md text-base'
        >
          Cek Detail Transaksi
        </Link>
      </div>
      <div className='mt-2 text-center leading-6 text-base p-4 md:p-0 md:max-w-[700px]'>
        Rincian pembelian sudah kami kirimkan ke email kamu. Mohon dicek
        kembali. jika tidak menerima email, kamu dapat menghubungi kami{' '}
        <a className='text-red-500' href={whatsappUrl()}>
          di sini
        </a>{' '}
        atau{' '}
        <span onClick={sendEmail} className='text-red-500 cursor-pointer'>
          kirim rincian pesanan ulang
        </span>
        .
      </div>
    </div>
  );
};

export default FinishTempo;
