import Spinner from '@/core/components/elements/Spinner/Spinner';
import NextImage from 'next/image';
import rejectImage from '../../../../public/images/reject.png';
import useTransaction from '../hooks/useTransaction';
import TransactionStatusBadge from './TransactionStatusBadge';
import Divider from '@/core/components/elements/Divider/Divider';
import { useEffect, useMemo, useRef, useState } from 'react';
import ImageNext from 'next/image';
import {
  downloadPurchaseOrder,
  downloadQuotation,
} from '../utils/transactions';
import BottomPopup from '@/core/components/elements/Popup/BottomPopup';
import uploadPoApi from '../api/uploadPoApi';
import { toast } from 'react-hot-toast';
import getFileBase64 from '@/core/utils/getFileBase64';
import currencyFormat from '@/core/utils/currencyFormat';
import VariantGroupCard from '@/lib/variant/components/VariantGroupCard';
import {
  ChevronDownIcon,
  ChevronRightIcon,
  ChevronUpIcon,
} from '@heroicons/react/24/outline';
import Link from '@/core/components/elements/Link/Link';
import checkoutPoApi from '../api/checkoutPoApi';
import cancelTransactionApi from '../api/cancelTransactionApi';
import MobileView from '@/core/components/views/MobileView';
import DesktopView from '@/core/components/views/DesktopView';
import Menu from '@/lib/auth/components/Menu';
import Image from '@/core/components/elements/Image/Image';
import { createSlug } from '@/core/utils/slug';
import toTitleCase from '@/core/utils/toTitleCase';
import useAirwayBill from '../hooks/useAirwayBill';
import Manifest from '@/lib/treckingAwb/component/Manifest';
import useAuth from '@/core/hooks/useAuth';
import StepApproval from './stepper';
import aprpoveApi from '../api/approveApi';
import rejectApi from '../api/rejectApi';
import rejectProductApi from '../api/rejectProductApi';
import { useRouter } from 'next/router';
import { gtagPurchase } from '@/core/utils/googleTag';
import { deleteItemCart } from '@/core/utils/cart';
import axios from 'axios';
const Transaction = ({ id }) => {
  const router = useRouter();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [reason, setReason] = useState('');
  const auth = useAuth();
  const { transaction } = useTransaction({ id });
  const statusApprovalWeb = transaction.data?.approvalStep;
  const [isLoading, setIsLoading] = useState(false);
  const { queryAirwayBill } = useAirwayBill({ orderId: id });
  const [airwayBillPopup, setAirwayBillPopup] = useState(null);

  const poNumber = useRef(null);
  const poFile = useRef(null);
  const [uploadPo, setUploadPo] = useState(false);
  const [idAWB, setIdAWB] = useState(null);
  const openUploadPo = () => setUploadPo(true);
  const closeUploadPo = () => setUploadPo(false);

  const submitUploadPo = async () => {
    const file = poFile.current.files[0];
    const name = poNumber.current.value;
    if (typeof file === 'undefined' || !name) {
      toast.error('Nomor dan Dokumen PO harus diisi');
      return;
    }
    if (file.size > 5000000) {
      toast.error('Maksimal ukuran file adalah 5MB');
      return;
    }
    const data = { name, file: await getFileBase64(file) };
    const isUploaded = await uploadPoApi({ id, data });
    if (isUploaded) {
      toast.success('Berhasil upload PO');
      transaction.refetch();
      closeUploadPo();
      return;
    }
    toast.error(
      'Terjadi kesalahan internal, coba lagi nanti atau hubungi kami'
    );
  };

  const [cancelTransaction, setCancelTransaction] = useState(false);
  const [continueNoPo, setContinueNoPo] = useState(false);
  const [continueTransaction, setContinueTransaction] = useState(false);
  const openCancelTransaction = () => setCancelTransaction(true);
  const openContinueTransaction = () => {
    if (auth.partnerTempo) {
      checkout();
    } else {
      if (!transaction.data?.purchaseOrderFile) {
        setContinueTransaction(true);
      } else {
        checkoutNoPO();
      }
    }
  };
  // const ContinueTransaction = () => {
  //   setContinueNoPo(true);
  //   checkoutNoPO();
  // };
  const closeCancelTransaction = () => setCancelTransaction(false);
  const closeContinueTransaction = () => setContinueTransaction(false);

  const [rejectTransaction, setRejectTransaction] = useState(false);

  const openRejectTransaction = () => setRejectTransaction(true);
  const closeRejectTransaction = () => setRejectTransaction(false);
  const submitCancelTransaction = async () => {
    const isCancelled = await cancelTransactionApi({
      transaction: transaction.data,
    });
    if (isCancelled) {
      toast.success('Berhasil batalkan transaksi');
      transaction.refetch();
    }
    closeCancelTransaction();
  };
  const checkout = async () => {
    if (!transaction.data?.purchaseOrderFile) {
      toast.error('Mohon upload dokumen PO anda sebelum melanjutkan pesanan');
      return;
    }
    await checkoutPoApi({ id, status: true });
    toast.success('Berhasil melanjutkan pesanan');
    transaction.refetch();
  };

  const checkoutNoPO = async () => {
    setIsLoading(true);
    gtagPurchase(
      transaction.data.products,
      transaction.data.deliveryAmount,
      transaction.data.name
    );

    gtag('event', 'conversion', {
      send_to: 'AW-954540379/nDymCL3BhaQYENvClMcD',
      value:
        transaction.data?.amountTotal +
        Math.round(parseInt(transaction.data.deliveryAmount * 1.1) / 1000) *
          1000,
      currency: 'IDR',
      transaction_id: transaction.data.id,
    });

    for (const product of transaction.data.products)
      deleteItemCart({ productId: product.id });
    if (transaction.data?.amountTotal > 0) {
      const payment = await axios.post(
        `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/midtrans-payment?transactionId=${transaction.data.id}`
      );
      setIsLoading(false);
      window.location.href = payment.data.redirectUrl;
    } else {
      window.location.href = `${
        process.env.NEXT_PUBLIC_SELF_HOST
      }/shop/checkout/success?order_id=${transaction.data.name.replace(
        /\//g,
        '-'
      )}`;
    }
    toast.success('Berhasil melanjutkan pesanan');
    transaction.refetch();

    /* const midtrans = async () => {
        for (const product of products) deleteItemCart({ productId: product.id });
        if (grandTotal > 0) {
          const payment = await axios.post(
            `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/midtrans-payment?transactionId=${isCheckouted.id}`
          );
          setIsLoading(false);
          window.location.href = payment.data.redirectUrl;
        } else {
          window.location.href = `${
            process.env.NEXT_PUBLIC_SELF_HOST
          }/shop/checkout/success?order_id=${isCheckouted.name.replace(
            /\//g,
            '-'
          )}`;
        }
      };*/
  };

  const handleApproval = async () => {
    await aprpoveApi({ id });
    toast.success('Berhasil melanjutkan approval');
    transaction.refetch();
  };

  const handleReject = async () => {
    await rejectApi({ id });
    closeRejectTransaction();
    transaction.refetch();
  };

  const memoizeVariantGroupCard = useMemo(
    () => (
      <div className='p-4 pt-0 flex flex-col gap-y-3'>
        <VariantGroupCard variants={transaction.data?.products} buyMore />
        <div className='flex justify-between mt-1'>
          <p className='text-gray_r-12/70'>Subtotal</p>
          <p>{currencyFormat(transaction.data?.amountUntaxed)}</p>
        </div>
        <div className='flex justify-between mt-1'>
          <p className='text-gray_r-12/70'>PPN 11%</p>
          <p>{currencyFormat(transaction.data?.amountTax)}</p>
        </div>
        <div className='flex justify-between mt-1'>
          <p className='text-gray_r-12/70'>Biaya Pengiriman</p>
          <p>{currencyFormat(transaction.data?.deliveryAmount)}</p>
        </div>
        <div className='flex justify-between mt-1 font-medium'>
          <p>Grand Total</p>
          <p>{currencyFormat(transaction.data?.amountTotal)}</p>
        </div>
      </div>
    ),
    [transaction.data]
  );

  const memoizeVariantGroupCardReject = useMemo(
    () => (
      <div className='p-4 pt-0 flex flex-col gap-y-3'>
        <VariantGroupCard
          variants={transaction.data?.productsRejectLine}
          buyMore
        />
      </div>
    ),
    [transaction.data]
  );

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

  const closePopup = () => {
    setIdAWB(null);
  };

  const openModal = (product) => {
    setSelectedProduct(product);
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    setSelectedProduct(null);
    setReason('');
  };

  const handleRejectProduct = async () => {
    try {
      if (!reason.trim()) {
        toast.error('Masukkan alasan terlebih dahulu');
        return;
      } else {
        let idSo = transaction?.data.id;
        let idProduct = selectedProduct?.id;
        await rejectProductApi({ idSo, idProduct, reason });
        closeModal();
        toast.success('Produk berhasil di reject');
        setTimeout(() => {
          window.location.reload();
        }, 1500);
      }
    } catch (error) {
      toast.error('Gagal reject produk. Silakan coba lagi.');
    }
  };

  return (
    transaction.data?.name && (
      <>
        <BottomPopup
          active={continueTransaction}
          close={closeContinueTransaction}
          title='Lanjutkan Transaksi'
        >
          <div className='leading-7 text-gray_r-12/80'>
            Apakah anda yakin melanjutkan tanpa upload PO?{' '}
            <span className='underline'>{transaction.data?.name}</span>?
          </div>
          <div className='flex justify-end mt-6 gap-x-4'>
            <button
              className='btn-solid-red w-full md:w-fit'
              type='button'
              onClick={checkoutNoPO}
            >
              Ya, Lanjutkan
            </button>
            <button
              className='btn-light w-full md:w-fit'
              type='button'
              onClick={closeContinueTransaction}
            >
              Batal
            </button>
          </div>
        </BottomPopup>
        <BottomPopup
          active={cancelTransaction}
          close={closeCancelTransaction}
          title='Batalkan Transaksi'
        >
          <div className='leading-7 text-gray_r-12/80'>
            Apakah anda yakin membatalkan transaksi{' '}
            <span className='underline'>{transaction.data?.name}</span>?
          </div>
          <div className='flex justify-end mt-6 gap-x-4'>
            <button
              className='btn-solid-red w-full md:w-fit'
              type='button'
              onClick={submitCancelTransaction}
            >
              Ya, Batalkan
            </button>
            <button
              className='btn-light w-full md:w-fit'
              type='button'
              onClick={closeCancelTransaction}
            >
              Batal
            </button>
          </div>
        </BottomPopup>

        <BottomPopup
          active={rejectTransaction}
          close={closeRejectTransaction}
          title='Batalkan Transaksi'
        >
          <div className='leading-7 text-gray_r-12/80'>
            Apakah anda yakin Membatalkan transaksi{' '}
            <span className='underline'>{transaction.data?.name}</span>?
          </div>
          <div className='flex justify-end mt-6 gap-x-4'>
            <button
              className='btn-solid-red w-full md:w-fit'
              type='button'
              onClick={handleReject}
            >
              Ya, Batalkan
            </button>
            <button
              className='btn-light w-full md:w-fit'
              type='button'
              onClick={closeRejectTransaction}
            >
              Batal
            </button>
          </div>
        </BottomPopup>

        <BottomPopup title='Upload PO' close={closeUploadPo} active={uploadPo}>
          <div>
            <label>Nomor PO</label>
            <input type='text' className='form-input mt-3' ref={poNumber} />
          </div>
          <div className='mt-4'>
            <label>Dokumen PO</label>
            <input type='file' className='form-input mt-3 py-2' ref={poFile} />
          </div>
          <div className='grid grid-cols-2 gap-x-3 mt-6'>
            <button
              type='button'
              className='btn-light w-full'
              onClick={closeUploadPo}
            >
              Batal
            </button>
            <button
              type='button'
              className='btn-solid-red w-full'
              onClick={submitUploadPo}
            >
              Upload
            </button>
          </div>
        </BottomPopup>
        <Manifest idAWB={idAWB} closePopup={closePopup}></Manifest>

        <MobileView>
          <div className='p-4'>
            {auth?.feature?.soApproval && (
              <StepApproval
                layer={statusApprovalWeb}
                status={transaction?.data?.status}
                className='ml-auto'
              />
            )}
          </div>
          <div className='flex flex-col gap-y-4 p-4'>
            <DescriptionRow label='Status Transaksi'>
              <div className='flex justify-end'>
                <TransactionStatusBadge status={transaction.data?.status} />
              </div>
            </DescriptionRow>
            <DescriptionRow label='No Transaksi'>
              {transaction.data?.name}
            </DescriptionRow>
            <DescriptionRow label='Ketentuan Pembayaran'>
              {transaction.data?.paymentTerm}
            </DescriptionRow>
            <DescriptionRow label='Nama Sales'>
              {transaction.data?.sales}
            </DescriptionRow>
            <DescriptionRow label='Waktu Transaksi'>
              {transaction.data?.dateOrder}
            </DescriptionRow>
          </div>

          <Divider />

          <div className='p-4'>
            <div className='font-medium'>Pengiriman</div>
            <div className='flex flex-col gap-y-3 mt-4'>
              {transaction?.data?.pickings?.map((airway) => (
                <button
                  className='shadow rounded-md p-3 text-gray_r-12 font-normal flex justify-between items-center text-left'
                  key={airway?.id}
                  onClick={() => setIdAWB(airway?.id)}
                >
                  <div>
                    <span className='text-sm text-gray_r-11'>
                      No Resi : {airway?.trackingNumber || '-'}{' '}
                    </span>
                    <p className='mt-1 font-medium'>{airway?.name}</p>
                  </div>
                  <div className='flex gap-x-2'>
                    <div className='text-sm text-gray-600 badge-green leading-[1.5] mt-1'>
                      {airway?.delivered ? 'Pesanan Tiba' : 'Sedang Dikirim'}
                    </div>
                    <ChevronRightIcon className='w-5 stroke-2' />
                  </div>
                </button>
              ))}
            </div>
            {transaction?.data?.pickings == 0 && (
              <div className='badge-red text-sm px-2'>Belum ada pengiriman</div>
            )}
          </div>

          <Divider />

          <div className='p-4'>
            <p className='font-medium'>Invoice</p>
            <div className='flex flex-col gap-y-3 mt-4'>
              {transaction.data?.invoices?.map((invoice, index) => (
                <Link href={`/my/invoices/${invoice.id}`} key={index}>
                  <div className='shadow rounded-md p-4 text-gray_r-12 font-normal flex justify-between'>
                    <div>
                      <p className='mb-2'>{invoice?.name}</p>
                      <div className='flex items-center gap-x-1'>
                        {invoice.amountResidual > 0 ? (
                          <div className='badge-red'>Belum Lunas</div>
                        ) : (
                          <div className='badge-green'>Lunas</div>
                        )}
                        <p className='text-caption-2 text-gray_r-11'>
                          {currencyFormat(invoice.amountTotal)}
                        </p>
                      </div>
                    </div>
                    <ChevronRightIcon className='w-5 stroke-2' />
                  </div>
                </Link>
              ))}
              {transaction.data?.invoices?.length === 0 && (
                <div className='badge-red text-sm px-2'>Belum ada invoice</div>
              )}
            </div>
          </div>

          <Divider />

          {!auth?.feature.soApproval && (
            <div className='p-4 flex flex-col gap-y-4'>
              <DescriptionRow label='Purchase Order'>
                {transaction.data?.purchaseOrderName || '-'}
              </DescriptionRow>
              <div className='flex items-center'>
                <p className='text-gray_r-11 leading-none'>Dokumen PO</p>
                <button
                  type='button'
                  className='inline-block text-danger-500'
                  onClick={
                    transaction.data?.purchaseOrderFile
                      ? () => downloadPurchaseOrder(transaction.data)
                      : transaction?.data.invoices.length < 1
                      ? openUploadPo
                      : ''
                  }
                >
                  {transaction?.data?.purchaseOrderFile
                    ? 'Download'
                    : transaction?.data.invoices.length < 1
                    ? 'Upload'
                    : '-'}
                </button>
              </div>
            </div>
          )}

          <Divider />

          <div className='font-medium p-4'>Detail Produk</div>
          {transaction?.data?.products.length > 0 ? (
            <div>{memoizeVariantGroupCard}</div>
          ) : (
            <div className='badge-red text-sm px-2 ml-4'>
              Semua produk telah di reject
            </div>
          )}

          {transaction?.data?.productsRejectLine.length > 0 && (
            <div>
              <div className='font-medium p-4'>Detail Produk Reject</div>
              {memoizeVariantGroupCardReject}
            </div>
          )}

          <Divider />

          <SectionAddress address={transaction.data?.address} />

          <Divider />

          <div className='p-4 pt-0'>
            {transaction.data?.status == 'draft' &&
              auth?.feature.soApproval && (
                <div className='flex gap-x-2'>
                  <button
                    className='btn-yellow w-full'
                    onClick={checkout}
                    disabled={
                      transaction.data?.status === 'cancel'
                        ? true
                        : false || auth?.webRole === statusApprovalWeb
                        ? true
                        : false
                    }
                  >
                    Approve
                  </button>
                  <button
                    className='btn-solid-red px-7 w-full'
                    onClick={checkout}
                    disabled={
                      transaction.data?.status === 'cancel'
                        ? true
                        : false || auth?.webRole === statusApprovalWeb
                        ? true
                        : false
                    }
                  >
                    Reject
                  </button>
                </div>
              )}
            {transaction.data?.status == 'draft' &&
              !auth?.feature?.soApproval && (
                <button
                  className='btn-yellow w-full mt-4'
                  onClick={openContinueTransaction}
                >
                  Lanjutkan Transaksi
                </button>
              )}
            <button
              className='btn-light w-full mt-4'
              disabled={transaction.data?.status != 'draft'}
              onClick={() => downloadQuotation(transaction.data)}
            >
              Download Quotation
            </button>
            {transaction.data?.status != 'draft' && (
              <button
                className='btn-light w-full mt-4'
                disabled={transaction.data?.status != 'waiting'}
                onClick={openCancelTransaction}
              >
                Batalkan Transaksi
              </button>
            )}
          </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 py-6 bg-white border border-gray_r-6 rounded'>
              <div className='flex justify-between'>
                <h1 className='text-title-sm font-semibold mb-6'>
                  Detail Transaksi
                </h1>
                {auth?.feature?.soApproval && (
                  <StepApproval
                    layer={statusApprovalWeb}
                    status={transaction?.data?.status}
                    className='ml-auto'
                  />
                )}
              </div>

              <div className='flex items-center gap-x-2 mb-3'>
                <span className='text-h-sm font-medium'>
                  {transaction?.data?.name}
                </span>
                <TransactionStatusBadge status={transaction?.data?.status} />
              </div>
              <div className='flex gap-x-4'>
                <button
                  type='button'
                  className='btn-solid-red px-3 py-2 mr-auto'
                  onClick={() => downloadQuotation(transaction.data)}
                >
                  Download
                </button>
                {transaction.data?.status == 'draft' &&
                  auth?.feature?.soApproval &&
                  auth?.webRole && (
                    <div className='flex gap-x-2'>
                      <button
                        className='btn-yellow'
                        onClick={handleApproval}
                        disabled={
                          transaction.data?.status === 'cancel'
                            ? true
                            : false || auth?.webRole === statusApprovalWeb
                            ? true
                            : false || statusApprovalWeb < 1
                            ? true
                            : false
                        }
                      >
                        Approve
                      </button>
                      <button
                        className='btn-solid-red px-7'
                        onClick={openRejectTransaction}
                        disabled={
                          transaction.data?.status === 'cancel'
                            ? true
                            : false || auth?.webRole === statusApprovalWeb
                            ? true
                            : false || statusApprovalWeb < 1
                            ? true
                            : false
                        }
                      >
                        Reject
                      </button>
                    </div>
                  )}
                {transaction.data?.status == 'draft' &&
                  !auth?.feature.soApproval && (
                    <button
                      className='btn-yellow'
                      onClick={openContinueTransaction}
                    >
                      Lanjutkan Transaksi
                    </button>
                  )}
                {transaction.data?.status != 'draft' &&
                  !auth?.feature.soApproval && (
                    <button
                      className='btn-light'
                      disabled={transaction.data?.status != 'waiting'}
                      onClick={openCancelTransaction}
                    >
                      Batalkan Transaksi
                    </button>
                  )}
              </div>

              <div className='grid grid-cols-2 gap-x-6 mt-6'>
                <div className='grid grid-cols-2 gap-y-4'>
                  <div>Nama Sales</div>
                  <div>: {transaction?.data?.sales}</div>

                  <div>Tanggal Transaksi</div>
                  <div>: {transaction?.data?.dateOrder}</div>
                </div>
                <div className='grid grid-cols-2 gap-y-4'>
                  <div>Ketentuan Pembayaran</div>
                  <div>: {transaction?.data?.paymentTerm}</div>

                  {!auth?.feature?.soApproval ? (
                    <>
                      <div>Purchase Order</div>
                      <div>
                        : {transaction?.data?.purchaseOrderName}{' '}
                        <button
                          type='button'
                          className='inline-block text-danger-500'
                          onClick={
                            transaction.data?.purchaseOrderFile
                              ? () => downloadPurchaseOrder(transaction.data)
                              : transaction?.data.invoices.length < 1
                              ? openUploadPo
                              : ''
                          }
                        >
                          {transaction?.data?.purchaseOrderFile
                            ? 'Download'
                            : transaction?.data.invoices.length < 1
                            ? 'Upload'
                            : '-'}
                        </button>
                      </div>
                    </>
                  ) : (
                    <>
                      <div>Site</div>
                      <div>: {transaction?.data?.sitePartner}</div>
                    </>
                  )}
                </div>
              </div>

              <div className='text-h-sm font-semibold mt-10 mb-4'>
                Informasi Pelanggan
              </div>
              <div className='grid grid-cols-2 gap-x-4'>
                <div className='border border-gray_r-6 rounded p-3'>
                  <div className='font-medium mb-4'>Detail Pelanggan</div>
                  <SectionContent
                    address={transaction?.data?.address?.customer}
                  />
                </div>
              </div>
              <div className='flex '>
                <div className='w-1/2'>
                  <div className='text-h-sm font-semibold mt-10 mb-4'>
                    Pengiriman
                  </div>
                  {transaction?.data?.pickings.length == 0 && (
                    <div className='badge-red text-sm'>
                      Belum ada pengiriman
                    </div>
                  )}
                  <div className='grid grid-cols-1 gap-1 w-2/3'>
                    {transaction?.data?.pickings?.map((airway) => (
                      <button
                        className='shadow rounded-md p-3 text-gray_r-12 font-normal flex justify-between items-center text-left h-20'
                        key={airway?.id}
                        onClick={() => setIdAWB(airway?.id)}
                      >
                        <div>
                          <span className='text-sm text-gray_r-11'>
                            No Resi : {airway?.trackingNumber || '-'}{' '}
                          </span>
                          <p className='mt-1 font-medium'>{airway?.name}</p>
                        </div>
                        <div className='flex gap-x-2'>
                          <div className='text-sm text-gray-600 badge-green leading-[1.5] mt-1'>
                            {airway?.delivered
                              ? 'Pesanan Tiba'
                              : 'Sedang Dikirim'}
                          </div>
                          <ChevronRightIcon className='w-5 stroke-2' />
                        </div>
                      </button>
                    ))}
                  </div>
                </div>
                <div className='invoice w-1/2 '>
                  <div className='text-h-sm font-semibold mt-10 mb-4 '>
                    Invoice
                  </div>
                  {transaction.data?.invoices?.length === 0 && (
                    <div className='badge-red text-sm'>Belum ada invoice</div>
                  )}
                  <div className='grid grid-cols-1 gap-1 w-2/3 '>
                    {transaction.data?.invoices?.map((invoice, index) => (
                      <Link href={`/my/invoices/${invoice.id}`} key={index}>
                        <div className='shadow rounded-md p-4 text-gray_r-12 font-normal flex justify-between'>
                          <div>
                            <p className='mb-1'>{invoice?.name}</p>
                            <div className='flex items-center gap-x-1'>
                              {invoice.amountResidual > 0 ? (
                                <div className='badge-red'>Belum Lunas</div>
                              ) : (
                                <div className='badge-green'>Lunas</div>
                              )}
                              <p className='text-caption-2 text-gray_r-11'>
                                {currencyFormat(invoice.amountTotal)}
                              </p>
                            </div>
                          </div>
                          <ChevronRightIcon className='w-5 stroke-2' />
                        </div>
                      </Link>
                    ))}
                  </div>
                </div>
              </div>

              <div className='text-h-sm font-semibold mt-4 mb-4'>
                Rincian Pembelian
              </div>
              {transaction?.data?.products?.length > 0 ? (
                <table className='table-data'>
                  <thead>
                    <tr>
                      <th>Nama Produk</th>
                      {/* <th>Diskon</th> */}
                      <th>Jumlah</th>
                      <th>Harga</th>
                      <th>Subtotal</th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    {transaction?.data?.products?.map((product) => (
                      <tr key={product.id}>
                        <td className='flex'>
                          <Link
                            href={createSlug(
                              '/shop/product/',
                              product?.parent.name,
                              product?.parent.id
                            )}
                            className='w-[20%] flex-shrink-0'
                          >
                            <div className='relative'>
                              <Image
                                src={product?.parent?.image}
                                alt={product?.name}
                                className='object-contain object-center border border-gray_r-6 h-32 w-full rounded-md'
                              />
                              <div className='absolute top-0 right-4 flex  mt-3'>
                                <div className='gambarB '>
                                  {product.isSni && (
                                    <ImageNext
                                      src='/images/sni-logo.png'
                                      alt='SNI Logo'
                                      className='w-2 h-4 object-contain object-top   sm:h-4'
                                      width={50}
                                      height={50}
                                    />
                                  )}
                                </div>
                                <div className='gambarC  '>
                                  {product.isTkdn && (
                                    <ImageNext
                                      src='/images/TKDN.png'
                                      alt='TKDN'
                                      className='w-5 h-4 object-contain object-top  ml-1 sm:h-4'
                                      width={50}
                                      height={50}
                                    />
                                  )}
                                </div>
                              </div>
                            </div>
                          </Link>
                          <div className='px-2 text-left'>
                            <Link
                              href={createSlug(
                                '/shop/product/',
                                product?.parent.name,
                                product?.parent.id
                              )}
                              className='line-clamp-2 leading-6 !text-gray_r-12 font-normal'
                            >
                              {product?.parent?.name}
                            </Link>
                            <div className='text-gray_r-11 mt-2'>
                              {product?.code}{' '}
                              {product?.attributes.length > 0
                                ? `| ${product?.attributes.join(', ')}`
                                : ''}
                            </div>
                            {product.soQty && product.reservedStockQty && (
                              <div className='text-[10px] text-red-500 italic mt-2'>
                                {product.soQty !== product.reservedStockQty
                                  ? 'Barang sedang disiapkan'
                                  : `${product.reservedStockQty} barang bisa di
                              kirim/pickup`}
                              </div>
                            )}
                          </div>
                        </td>
                        {/* <td>
                          {product.price.discountPercentage > 0
                            ? `${product.price.discountPercentage}%`
                            : ''}
                        </td> */}
                        <td>{product.quantity}</td>
                        <td>
                          {/* {product.price.discountPercentage > 0 && (
                            <div className='line-through mb-1 text-caption-1 text-gray_r-12/70'>
                              {currencyFormat(product.price.price)}
                            </div>
                          )} */}
                          <div>
                            {currencyFormat(product.price.priceDiscount)}
                          </div>
                        </td>
                        <td>{currencyFormat(product.price.subtotal)}</td>
                        {/* {auth?.feature.soApproval && (auth.webRole == 2 || auth.webRole == 3) && (transaction.data.isReaject == false) && ( */}
                        {auth?.feature.soApproval &&
                          (auth.webRole == 2 || auth.webRole == 3) &&
                          router.asPath.includes('/my/quotations/') &&
                          transaction.data?.status == 'draft' && (
                            <td>
                              <button
                                className='bg-red-500 text-white py-1 px-3 rounded'
                                onClick={() => openModal(product)}
                              >
                                Reject
                              </button>
                            </td>
                          )}
                      </tr>
                    ))}
                  </tbody>
                </table>
              ) : (
                <div className='badge-red text-sm'>
                  Semua produk telah di reject
                </div>
              )}

              {isModalOpen && (
                <div className='fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center'>
                  <div
                    className='bg-white p-4 rounded w-96
                     ease-in-out opacity-100
                    transform transition-transform duration-300  scale-100'
                  >
                    <h2 className='text-lg mb-2'>Berikan Alasan</h2>
                    <textarea
                      value={reason}
                      onChange={(e) => setReason(e.target.value)}
                      className='w-full p-2 border rounded'
                      rows='4'
                    ></textarea>
                    <div className='mt-4 flex justify-end'>
                      <button
                        className='bg-gray-300 text-black py-1 px-3 rounded mr-2'
                        onClick={closeModal}
                      >
                        Batal
                      </button>
                      <button
                        className='bg-red-500 text-white py-1 px-3 rounded'
                        onClick={handleRejectProduct}
                      >
                        Reject
                      </button>
                    </div>
                  </div>
                </div>
              )}

              {transaction?.data?.products?.length > 0 && (
                <div className='flex justify-end mt-4'>
                  <div className='w-1/4 grid grid-cols-2 gap-y-3 text-gray_r-12/80'>
                    <div className='text-right'>Subtotal</div>
                    <div className='text-right font-medium'>
                      {currencyFormat(transaction.data?.amountUntaxed)}
                    </div>

                    <div className='text-right'>PPN 11%</div>
                    <div className='text-right font-medium'>
                      {currencyFormat(transaction.data?.amountTax)}
                    </div>

                    <div className='text-right whitespace-nowrap'>
                      Biaya Pengiriman
                    </div>
                    <div className='text-right font-medium'>
                      {currencyFormat(transaction.data?.deliveryAmount)}
                    </div>

                    <div className='text-right'>Grand Total</div>
                    <div className='text-right font-medium text-gray_r-12'>
                      {currencyFormat(transaction.data?.amountTotal)}
                    </div>
                  </div>
                </div>
              )}

              {transaction?.data?.productsRejectLine.length > 0 && (
                <div className='text-h-sm font-semibold mt-10 mb-4'>
                  Rincian Produk Reject
                </div>
              )}
              {transaction?.data?.productsRejectLine.length > 0 && (
                <table className='table-data'>
                  <thead>
                    <tr>
                      <th>Nama Produk</th>
                      {/* <th>Diskon</th> */}
                      <th>Jumlah</th>
                      <th>Harga</th>
                      <th>Subtotal</th>
                    </tr>
                  </thead>
                  <tbody>
                    {transaction?.data?.productsRejectLine?.map((product) => (
                      <tr key={product.id}>
                        <td className='flex'>
                          <Link
                            href={createSlug(
                              '/shop/product/',
                              product?.parent.name,
                              product?.parent.id
                            )}
                            className='w-[20%] flex-shrink-0'
                          >
                            <Image
                              src={product?.parent?.image}
                              alt={product?.name}
                              className='object-contain object-center border border-gray_r-6 h-32 w-full rounded-md'
                            />
                          </Link>
                          <div className='px-2 text-left'>
                            <Link
                              href={createSlug(
                                '/shop/product/',
                                product?.parent.name,
                                product?.parent.id
                              )}
                              className='line-clamp-2 leading-6 !text-gray_r-12 font-normal'
                            >
                              {product?.parent?.name}
                            </Link>
                            <div className='text-gray_r-11 mt-2'>
                              {product?.code}{' '}
                              {product?.attributes.length > 0
                                ? `| ${product?.attributes.join(', ')}`
                                : ''}
                            </div>
                          </div>
                        </td>
                        {/* <td>
                            {product.price.discountPercentage > 0
                              ? `${product.price.discountPercentage}%`
                              : ''}
                          </td> */}
                        <td>{product.quantity}</td>
                        <td>
                          {/* {product.price.discountPercentage > 0 && (
                              <div className='line-through mb-1 text-caption-1 text-gray_r-12/70'>
                                {currencyFormat(product.price.price)}
                              </div>
                            )} */}
                          <div>
                            {currencyFormat(product.price.priceDiscount)}
                          </div>
                        </td>
                        <td className='flex justify-center'>
                          <NextImage
                            src={rejectImage}
                            alt='Reject'
                            width={90}
                            height={30}
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </DesktopView>

        {/* {queryAirwayBill.data?.airways?.map((airway) => (
          <BottomPopup
            key={airway.waybillNumber}
            title='Detail Pengiriman'
            active={airwayBillPopup == airway.waybillNumber}
            close={() => setAirwayBillPopup(null)}
          >
            <div className='flex flex-col gap-y-4 my-4'>
              <div className='flex justify-between'>
                <div className='text-gray_r-11'>No Pengiriman</div>
                <div>{airway?.deliveryOrder?.name}</div>
              </div>
              <div className='flex justify-between'>
                <div className='text-gray_r-11'>Kurir</div>
                <div>{airway?.deliveryOrder?.carrier}</div>
              </div>
              <div className='flex justify-between'>
                <div className='text-gray_r-11'>No Resi</div>
                <div>{airway?.waybillNumber}</div>
              </div>
            </div>

            <div className='pt-4'>
              <div className='font-semibold text-body-1 mb-4'>Status Pengiriman</div>
              <ol class='relative border-l border-gray_r-7'>
                {airway?.manifests?.map((manifest, index) => (
                  <li class='mb-6 ml-4' key={index}>
                    <div
                      class={`absolute w-3 h-3 rounded-full mt-1.5 -left-1.5 border ${
                        index == 0 ? 'bg-red-600 border-red-600' : 'bg-gray_r-7 border-white'
                      }`}
                    />
                    <time class='text-sm leading-none text-gray-400'>
                      {manifest.datetime}
                    </time>
                    <p
                      class={`leading-6 font-medium text-body-2 mt-2 ${
                        index == 0 ? 'text-red-600' : 'text-gray_r-11'
                      }`}
                    >
                      {manifest.description}
                    </p>
                  </li>
                ))}
                {(!airway?.manifests || airway?.manifests?.length == 0) && (
                  <div className='badge-red text-sm'>Belum ada pengiriman</div>
                )}
              </ol>
            </div>
          </BottomPopup>
        ))} */}
      </>
    )
  );
};

const SectionAddress = ({ address }) => {
  const [section, setSection] = useState({
    customer: false,
    invoice: false,
    shipping: false,
  });
  const toggleSection = (name) => {
    setSection({ ...section, [name]: !section[name] });
  };

  return (
    <>
      <SectionButton
        label='Detail Pelanggan'
        active={section.customer}
        toggle={() => toggleSection('customer')}
      />

      {section.customer && <SectionContent address={address?.customer} />}

      {/* <Divider />

      <SectionButton
        label='Detail Pengiriman'
        active={section.shipping}
        toggle={() => toggleSection('shipping')}
      />

      {section.shipping && <SectionContent address={address?.shipping} />}

      <Divider />

      <SectionButton
        label='Detail Penagihan'
        active={section.invoice}
        toggle={() => toggleSection('invoice')}
      />
      {section.invoice && <SectionContent address={address?.invoice} />} */}
    </>
  );
};

const SectionButton = ({ label, active, toggle }) => (
  <button
    className='p-4 font-medium flex justify-between w-full'
    onClick={toggle}
  >
    <span>{label}</span>
    {active ? (
      <ChevronUpIcon className='w-5' />
    ) : (
      <ChevronDownIcon className='w-5' />
    )}
  </button>
);

const SectionContent = ({ address }) => {
  let fullAddress = [];
  if (address?.street) fullAddress.push(address.street);
  if (address?.subDistrict?.name)
    fullAddress.push(toTitleCase(address.subDistrict.name));
  if (address?.district?.name)
    fullAddress.push(toTitleCase(address.district.name));
  if (address?.city?.name) fullAddress.push(toTitleCase(address.city.name));
  fullAddress = fullAddress.join(', ');

  return (
    <div className='flex flex-col gap-y-4 p-4 md:p-0 border-t border-gray_r-6 md:border-0'>
      <DescriptionRow label='Nama'>{address.name}</DescriptionRow>
      <DescriptionRow label='Email'>{address.email || '-'}</DescriptionRow>
      <DescriptionRow label='No Telepon'>
        {address.mobile || '-'}
      </DescriptionRow>
      <DescriptionRow label='Alamat'>{fullAddress}</DescriptionRow>
    </div>
  );
};

const DescriptionRow = ({ children, label }) => (
  <div className='grid grid-cols-2'>
    <span className='text-gray_r-11'>{label}</span>
    <span className='text-right leading-6'>{children}</span>
  </div>
);

export default Transaction;
