import Spinner from '@/core/components/elements/Spinner/Spinner'
import useInvoice from '../hooks/useInvoice'
import { downloadInvoice, downloadTaxInvoice } from '../utils/invoices'
import Divider from '@/core/components/elements/Divider/Divider'
import VariantGroupCard from '@/lib/variant/components/VariantGroupCard'
import currencyFormat from '@/core/utils/currencyFormat'
import MobileView from '@/core/components/views/MobileView'
import DesktopView from '@/core/components/views/DesktopView'
import Menu from '@/lib/auth/components/Menu'
import Link from '@/core/components/elements/Link/Link'
import Image from '@/core/components/elements/Image/Image'
import { createSlug } from '@/core/utils/slug'
import { useEffect, useState } from 'react'

const Invoice = ({ id }) => {
  const { invoice } = useInvoice({ id })

  const [totalAmount, setTotalAmount] = useState(0)
  const [totalDiscountAmount, setTotalDiscountAmount] = useState(0)

  useEffect(() => {
    if (invoice?.data?.products) {
      let calculateTotalAmount = 0
      let calculateTotalDiscountAmount = 0
      invoice.data.products.forEach((product) => {
        calculateTotalAmount += product.price.price * product.quantity
        calculateTotalDiscountAmount +=
          (product.price.price - product.price.priceDiscount) * product.quantity
      })
      setTotalAmount(calculateTotalAmount)
      setTotalDiscountAmount(calculateTotalDiscountAmount)
    }
  }, [invoice])

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

  const address = invoice.data?.customer
  let fullAddress = []
  if (address?.street) fullAddress.push(address.street)
  if (address?.subDistrict?.name) fullAddress.push(address.subDistrict.name)
  if (address?.district?.name) fullAddress.push(address.district.name)
  if (address?.city?.name) fullAddress.push(address.city.name)
  fullAddress = fullAddress.join(', ')

  return (
    invoice.data?.name && (
      <>
        <MobileView>
          <div className='flex flex-col gap-y-4 p-4'>
            <DescriptionRow label='No Invoice'>{invoice.data?.name}</DescriptionRow>
            <DescriptionRow label='Status Transaksi'>
              {invoice.data?.amountResidual > 0 ? (
                <span className='badge-solid-red'>Belum Lunas</span>
              ) : (
                <span className='badge-solid-green'>Lunas</span>
              )}
            </DescriptionRow>
            <DescriptionRow label='Purchase Order'>
              {invoice.data?.purchaseOrderName || '-'}
            </DescriptionRow>
            <DescriptionRow label='Ketentuan Pembayaran'>
              {invoice.data?.paymentTerm}
            </DescriptionRow>
            {invoice.data?.amountResidual > 0 && invoice.invoiceDate != invoice.invoiceDateDue && (
              <DescriptionRow label='Tanggal Jatuh Tempo'>
                {invoice.data?.invoiceDateDue}
              </DescriptionRow>
            )}
            <DescriptionRow label='Nama Sales'>{invoice.data?.sales}</DescriptionRow>
            <DescriptionRow label='Tanggal Invoice'>{invoice.data?.invoiceDate}</DescriptionRow>
            <div className='flex items-center'>
              <p className='text-gray_r-11 leading-none'>Invoice</p>
              <button
                type='button'
                className='btn-light py-1.5 px-3 ml-auto'
                onClick={() => downloadInvoice(invoice.data)}
              >
                Download
              </button>
            </div>
            <div className='flex items-center'>
              <p className='text-gray_r-11 leading-none'>Faktur Pajak</p>
              <button
                type='button'
                className='btn-light py-1.5 px-3 ml-auto'
                onClick={() => downloadTaxInvoice(invoice.data)}
                disabled={!invoice.data?.efaktur}
              >
                Download
              </button>
            </div>
          </div>

          <Divider />

          <div className='p-4 font-medium'>Detail Penagihan</div>

          <div className='flex flex-col gap-y-4 p-4 border-t border-gray_r-6'>
            <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>

          <Divider />

          <div className='font-medium p-4'>Detail Produk</div>

          <div className='p-4 pt-0 flex flex-col gap-y-3'>
            <VariantGroupCard variants={invoice.data?.products} buyMore />
            <div className='flex justify-between mt-3 font-medium'>
              <p>Total Belanja</p>
              <p>{currencyFormat(invoice.data?.amountTotal)}</p>
            </div>
          </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 bg-white border border-gray_r-6 rounded'>
              <h1 className='text-title-sm font-semibold mb-6'>Invoice & Faktur Pajak</h1>

              <div className='flex items-center gap-x-2 mb-3'>
                <span className='text-h-sm font-medium'>{invoice?.data?.name}</span>
                {invoice?.data?.amountResidual > 0 ? (
                  <div className='badge-solid-red h-fit'>Belum Lunas</div>
                ) : (
                  <div className='badge-solid-green h-fit'>Lunas</div>
                )}
              </div>

              <button
                type='button'
                className='btn-solid-red px-3 py-2'
                onClick={() => downloadInvoice(invoice.data)}
              >
                Download
              </button>

              <div className='grid grid-cols-2 gap-x-6 mt-6'>
                <div className='h-fit grid grid-cols-2 gap-y-4'>
                  <div>Tanggal Invoice</div>
                  <div>: {invoice?.data?.invoiceDate}</div>

                  <div>Purchase Order</div>
                  <div>: {invoice?.data?.purchaseOrderName || '-'}</div>

                  <div>Ketentuan Pembayaran</div>
                  <div>: {invoice?.data?.paymentTerm}</div>
                </div>
                <div className='h-fit grid grid-cols-2 gap-y-4'>
                  <div>Nama Sales</div>
                  <div>: {invoice?.data?.sales}</div>

                  <div>Faktur Pajak</div>
                  <div>
                    :{' '}
                    {invoice.data?.efaktur ? (
                      <button
                        type='button'
                        className='inline-block text-danger-500'
                        onClick={() => downloadTaxInvoice(invoice?.data)}
                      >
                        Download
                      </button>
                    ) : (
                      '-'
                    )}
                  </div>
                </div>
              </div>

              <div className='text-h-sm font-semibold mt-6 mb-4'>Rincian Pembelian</div>
              <table className='table-data'>
                <thead>
                  <tr>
                    <th>Nama Produk</th>
                    <th>Jumlah</th>
                    <th>Harga</th>
                    <th>Diskon</th>
                    <th>Subtotal</th>
                  </tr>
                </thead>
                <tbody>
                  {invoice?.data?.products?.map((product) => (
                    <tr key={product.id}>
                      <td className='flex'>
                        <Link
                          href={createSlug(
                            '/shop/product/',
                            product?.parent.name,
                            product?.parent.id
                          )}
                          className='w-[30%] flex-shrink-0'
                        >
                          <Image
                            src={product?.parent?.image}
                            alt={product?.name}
                            className='object-contain object-center border border-gray_r-6 h-40 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.quantity}</td>
                      <td>{currencyFormat(product.price.price)}</td>
                      <td>
                        {product.price.discountPercentage > 0
                          ? `${product.price.discountPercentage}%`
                          : ''}
                      </td>
                      <td>{currencyFormat(product.price.priceDiscount * product.quantity)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>

              <div className='flex justify-end mt-4'>
                <div className='w-1/4 grid grid-cols-2 gap-y-2 text-gray_r-12/80'>
                  <div className='text-right'>Subtotal</div>
                  <div className='text-right font-medium'>{currencyFormat(totalAmount)}</div>

                  <div className='text-right'>Total Diskon</div>
                  <div className='text-right font-medium'>
                    {currencyFormat(-totalDiscountAmount)}
                  </div>

                  <div className='text-right'>Grand Total</div>
                  <div className='text-right font-medium text-gray_r-12'>
                    {currencyFormat(invoice.data?.amountTotal)}
                  </div>
                  
                  <div className='text-right'>PPN 11% (Incl.)</div>
                  <div className='text-right font-medium'>{currencyFormat(totalAmount * 0.11)}</div>
                </div>
              </div>
            </div>
          </div>
        </DesktopView>
      </>
    )
  )
}

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

export default Invoice
