import { Link, usePage } from "@inertiajs/react"
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"
import Table from "@/Components/Table"
import { currency, useSearchParams } from "@/utils/format"
import DetailModal from "@/Components/Modal/DetailModal"
import DetailModalContent from "@/Components/Default/DetailModalContent"
import { useAtom } from "jotai"
import { showModalAtom } from "@/atoms"
import { ModalButton } from "@/Components/WithModal"
import useLang from "@/utils/useLang"
import { Eye } from "lucide-react"
import PaymentIndex from "../../Payment/Index"
import TransactionIndex from "../../Transaction/Index"

function Index(props) {
  return (
    <AuthenticatedLayout title={props?.title} Breadcrumb={Breadcrumb}>
      <TableIndex />
    </AuthenticatedLayout>
  )
}

const Breadcrumb = ({ currentLabel }) => {
  const { props } = usePage()
  const { budget_id } = props.request ?? {}

  const urlParts = props.location.split('/')
  const budgetIdIndex = urlParts.indexOf('budgets') + 1
  const budgetId = urlParts[budgetIdIndex]

  return (
    <div className='text-sm text-gray-500 breadcrumbs overflow-auto scrollbar-none'>
      <ul>
        <li><Link href='/admin/budgets' className="text-primary hover:underline">Anggaran</Link></li>
        <li><Link href={props.location} className="hover:underline">Detail Pembayaran</Link></li>
      </ul>
    </div>
  )
}

const TableIndex = (tableProps) => {
  let { tableHeader = null } = tableProps

  const { props } = usePage()

  const [show, setShow] = useAtom(showModalAtom)
  const handleShow = (data) => {
    setShow(data)
  }

  return (
    <PaymentIndex.HeaderProvider>
      {(paymentHeader) => (
        <PaymentIndex.FilterProvider>
          {(filterOptions) => {
            if (!tableHeader) {
              tableHeader = paymentHeader
            }
            return (
              <>
                <Table
                  filter
                  filterOptions={filterOptions}
                  search
                  addButton={false}
                  tableHeader={tableHeader}
                  tableBody={props?.[props?.page?.name]?.data ?? []}
                  tablePage={props?.[props?.page?.name]}
                  tableAction={(data) => {
                    return (
                      <>
                        <li>
                          <ModalButton id={`detail_${data?.id}`} onClick={() => handleShow(data)} className="menu-item-action">
                            <Eye className="w-4 h-4 text-blue-500" />
                            <span>Lihat Selengkapnya</span>
                          </ModalButton>
                        </li>
                        {!!data?.transaction ? (
                          <li>
                            <ModalButton disabled={!data?.transaction} id={`detail_transaction_${data?.id}`} onClick={() => handleShow(data)} className="menu-item-action">
                              <Eye className="w-4 h-4 text-blue-500" />
                              <span>Lihat Transaksi {useLang(`budget.type.${data?.budget?.type}`)}</span>
                            </ModalButton>
                          </li>
                        ) : null}
                      </>
                    )
                  }}
                  tableFooter={(tableProps) => {
                    const { tableBody, tableHeader, defaultClassName: { tdBodyClassName, trBodyClassName }, isTable = true } = tableProps
                    const dataSum = props?.paymentDetailSum ?? {}

                    if (!isTable) {
                      return (
                        <div className="card bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 p-4 mt-4 w-full">
                          <div className="flex flex-col sm:flex-row justify-between items-center gap-4">
                            <span className="font-semibold text-lg text-gray-900 dark:text-gray-100">Total</span>
                            <div className="flex flex-wrap gap-4 justify-center sm:justify-end text-sm">
                              <div className="flex flex-col items-center sm:items-end">
                                <span className="text-gray-500 text-xs">Total Pembayaran</span>
                                <span className="font-semibold">{currency(dataSum?.amount_total ?? 0)}</span>
                              </div>
                            </div>
                          </div>
                        </div>
                      )
                    }

                    return (
                      <tr className={`${trBodyClassName} bg-white w-full`}>
                        <td colSpan={3} className={`${tdBodyClassName}`}>
                          <div className="flex items-center justify-between w-full py-3">
                            <span className="font-semibold">Total</span>
                          </div>
                        </td>
                        <td>
                          <span className="font-semibold">
                            {currency(dataSum?.amount_total ?? 0)}
                          </span>
                        </td>
                        <td colSpan={10}></td>
                      </tr>
                    )
                  }}
                  {...tableProps}
                />

                {show ? (
                  <>
                    <DetailModal id={show?.id} tableHeader={tableHeader} data={show} handleClick={() => handleShow(null)} content={(data) => DetailModalContent(data, tableHeader)} size="max-w-2xl" />
                    <TransactionIndex.HeaderProvider>
                      {(transactionHeader) => (
                        <DetailModal label={`Detail Transaksi ${useLang(`budget.type.${show?.budget?.type}`)}`} id={`transaction_${show?.id}`} tableHeader={transactionHeader} data={show?.transaction} handleClick={() => handleShow(null)} content={(data) => DetailModalContent(data, transactionHeader)} size="max-w-2xl" />
                      )}
                    </TransactionIndex.HeaderProvider>
                  </>
                ) : null}
              </>
            )
          }}
        </PaymentIndex.FilterProvider>
      )}
    </PaymentIndex.HeaderProvider>
  )
}

Index.Table = TableIndex
const PaymentDetailIndex = Index
export default PaymentDetailIndex
