import { useRouter } from 'next/router'
import { useState } from 'react'
import { toast } from 'react-hot-toast'
import { EllipsisVerticalIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline'

import { downloadPurchaseOrder, downloadQuotation } from '../utils/transactions'
import useTransactions from '../hooks/useTransactions'
import currencyFormat from '@/core/utils/currencyFormat'
import cancelTransactionApi from '../api/cancelTransactionApi'
import TransactionStatusBadge from './TransactionStatusBadge'
import Spinner from '@/core/components/elements/Spinner/Spinner'
import Link from '@/core/components/elements/Link/Link'
import BottomPopup from '@/core/components/elements/Popup/BottomPopup'
import Pagination from '@/core/components/elements/Pagination/Pagination'
import { toQuery } from 'lodash-contrib'
import _ from 'lodash'
import Alert from '@/core/components/elements/Alert/Alert'

const Transactions = () => {
  const router = useRouter()
  const { q = '', page = 1 } = router.query

  const limit = 10

  const query = {
    name: q,
    offset: (page - 1) * limit,
    limit
  }
  const { transactions } = useTransactions({ query })

  const [inputQuery, setInputQuery] = useState(q)
  const [toOthers, setToOthers] = useState(null)
  const [toCancel, setToCancel] = useState(null)

  const submitCancelTransaction = async () => {
    const isCancelled = await cancelTransactionApi({
      transaction: toCancel
    })
    if (isCancelled) {
      toast.success('Berhasil batalkan transaksi')
      transactions.refetch()
    }
    setToCancel(null)
  }

  const pageCount = Math.ceil(transactions?.data?.saleOrderTotal / limit)
  let pageQuery = _.omit(query, ['limit', 'offset'])
  pageQuery = _.pickBy(pageQuery, _.identity)
  pageQuery = toQuery(pageQuery)

  const handleSubmit = (e) => {
    e.preventDefault()
    router.push(`/my/transactions?q=${inputQuery}`)
  }

  return (
    <div className='p-4 flex flex-col gap-y-4'>
      <form
        className='flex gap-x-3'
        onSubmit={handleSubmit}
      >
        <input
          type='text'
          className='form-input'
          placeholder='Cari Transaksi...'
          value={inputQuery}
          onChange={(e) => setInputQuery(e.target.value)}
        />
        <button
          className='btn-light bg-transparent px-3'
          type='submit'
        >
          <MagnifyingGlassIcon className='w-6' />
        </button>
      </form>

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

      {!transactions.isLoading && transactions.data?.saleOrders?.length === 0 && (
        <Alert
          type='info'
          className='text-center'
        >
          Tidak ada data transaksi
        </Alert>
      )}

      {transactions.data?.saleOrders?.map((saleOrder, index) => (
        <div
          className='p-4 shadow border border-gray_r-3 rounded-md'
          key={index}
        >
          <div className='grid grid-cols-2'>
            <Link href={`/my/transaction/${saleOrder.id}`}>
              <span className='text-caption-2 text-gray_r-11'>No. Transaksi</span>
              <h2 className='text-red_r-11 mt-1'>{saleOrder.name}</h2>
            </Link>
            <div className='flex gap-x-1 justify-end'>
              <TransactionStatusBadge status={saleOrder.status} />
              <EllipsisVerticalIcon
                className='w-5 h-5'
                onClick={() => setToOthers(saleOrder)}
              />
            </div>
          </div>
          <Link href={`/my/transaction/${saleOrder.id}`}>
            <div className='grid grid-cols-2 mt-3'>
              <div>
                <span className='text-caption-2 text-gray_r-11'>No. Purchase Order</span>
                <p className='mt-1 font-medium text-gray_r-12'>
                  {saleOrder.purchaseOrderName || '-'}
                </p>
              </div>
              <div className='text-right'>
                <span className='text-caption-2 text-gray_r-11'>Total Invoice</span>
                <p className='mt-1 font-medium text-gray_r-12'>{saleOrder.invoiceCount} Invoice</p>
              </div>
            </div>
            <div className='grid grid-cols-2 mt-3'>
              <div>
                <span className='text-caption-2 text-gray_r-11'>Sales</span>
                <p className='mt-1 font-medium text-gray_r-12'>{saleOrder.sales}</p>
              </div>
              <div className='text-right'>
                <span className='text-caption-2 text-gray_r-11'>Total Harga</span>
                <p className='mt-1 font-medium text-gray_r-12'>
                  {currencyFormat(saleOrder.amountTotal)}
                </p>
              </div>
            </div>
          </Link>
        </div>
      ))}

      <Pagination
        pageCount={pageCount}
        currentPage={parseInt(page)}
        url={`/my/transactions${pageQuery}`}
        className='mt-2 mb-2'
      />

      <BottomPopup
        title='Lainnya'
        active={toOthers}
        close={() => setToOthers(null)}
      >
        <div className='flex flex-col gap-y-4 mt-2'>
          <button
            className='text-left disabled:opacity-60'
            disabled={!toOthers?.purchaseOrderFile}
            onClick={() => {
              downloadPurchaseOrder(toOthers)
              setToOthers(null)
            }}
          >
            Download PO
          </button>
          <button
            className='text-left disabled:opacity-60'
            disabled={toOthers?.status != 'draft'}
            onClick={() => {
              downloadQuotation(toOthers)
              setToOthers(null)
            }}
          >
            Download Quotation
          </button>
          <button
            className='text-left disabled:opacity-60'
            disabled={toOthers?.status != 'waiting'}
            onClick={() => {
              setToCancel(toOthers)
              setToOthers(null)
            }}
          >
            Batalkan Transaksi
          </button>
        </div>
      </BottomPopup>

      <BottomPopup
        active={toCancel}
        close={() => setToCancel(null)}
        title='Batalkan Transaksi'
      >
        <div className='leading-7 text-gray_r-12/80'>
          Apakah anda yakin membatalkan transaksi{' '}
          <span className='underline'>{toCancel?.name}</span>?
        </div>
        <div className='flex mt-6 gap-x-4'>
          <button
            className='btn-solid-red flex-1'
            type='button'
            onClick={submitCancelTransaction}
          >
            Ya, Batalkan
          </button>
          <button
            className='btn-light flex-1'
            type='button'
            onClick={() => setToCancel(null)}
          >
            Batal
          </button>
        </div>
      </BottomPopup>
    </div>
  )
}

export default Transactions
