import { Link, usePage, router } from "@inertiajs/react"
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"
import Table from "@/Components/Table"
import { ModalButton } from "@/Components/WithModal"
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 { Eye, Check, X } from "lucide-react"

import RejectedModal from "@/Components/Modal/RejectedModal"
import useLang from "@/utils/useLang"
import TransactionIndex from "../Transaction/Index"

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

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

  const { props } = usePage()
  if (!tableHeader) {
    tableHeader = useTableHeader()
  }

  const filterOptions = useFilterOptions()

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

  return (
    <>
      <Table
        search
        filter
        filterOptions={filterOptions}
        tableHeader={tableHeader}
        addButton={false}
        tableBody={props?.[props?.page?.name]?.data ?? []}
        tablePage={props?.[props?.page?.name]}
        tableAction={(data) => {
          let isDisabled = !['manager'].includes(props?.auth?.user?.role) || !['pending'].includes(data.status)
          if (['director'].includes(props?.auth?.user?.role) && ['review'].includes(data.status)) {
            isDisabled = false
          }

          return (
            <>
              <li className="mb-1">
                <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 className="mb-1">
                  <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}
              <li className="mb-1">
                <button
                  className="menu-item-action"
                  onClick={() => router.get(`/admin/payments/${data?.id}/payment_approvals`)}
                  disabled={isDisabled}
                >
                  <Check className="w-4 h-4 text-green-600" />
                  <span className="text-green-700">Setujui Pembayaran</span>
                </button>
              </li>
              <li className="mb-1">
                <ModalButton disabled={isDisabled} id={`rejected_${data?.id}`} onClick={() => handleShow(data)} className="menu-item-action">
                  <X className="w-4 h-4 text-red-600" />
                  <span className="text-red-700">Tolak Pembayaran</span>
                </ModalButton>
              </li>
            </>
          )
        }}
        tableFooter={(tableProps) => {
          const { tableBody, tableHeader, defaultClassName: { tdBodyClassName, trBodyClassName }, isTable = true } = tableProps
          const dataSum = props?.paymentSum ?? {}

          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={4} 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" />
          <RejectedModal id={show?.id} isLabel={true} data={show} handleClick={() => handleShow(null)} content={(data) => DetailModalContent(data, tableHeader)} />
          <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}
    </>
  )
}

const useTableHeader = () => {
  const { page, isAdmin, location } = usePage().props
  const { params } = useSearchParams(location)

  const header = [
    {
      label: "#",
      value: "id",
      type: "numbering",
    },
    {
      value: "code",
      label: "Kode Pembayaran",
      isSearchable: true,
    },
    {
      value: "budget.name",
      label: "Nama Anggaran",
      isSearchable: true,
    },
    {
      value: "budget.type",
      label: "Jenis Anggaran",
      type: "status",
      prefix: "budget.type",
    },
    {
      value: "amount",
      label: "Jumlah",
      type: "currency",
    },
    {
      value: "payment_date",
      label: "Tanggal Bayar",
      dateFormat: "DD MMM YYYY",
      type: "date",
      isSearchable: true,
    },
    {
      value: "due_date",
      label: "Jatuh Tempo",
      dateFormat: "DD MMM YYYY",
      type: "date",
      isDetail: true,
      isSearchable: true,
    },
    {
      value: "status",
      label: "Status",
      type: "status",
      prefix: "payment.status",
    },
    {
      value: "status_message",
      label: "Catatan Penolakan",
      isDetail: true,
      isHidden: 'not null'
    },
    {
      value: "method",
      label: "Metode",
      type: "status",
      prefix: "payment.method",
    },
    {
      value: "cheque_number",
      label: "Nomor Cek / Giro",
      isDetail: true,
      isSearchable: true,
      isHidden: 'not null'
    },
    {
      label: "Waktu",
      value: "created_at",
      type: "date",
      isSearchable: true,
      className: "text-[13px] w-[10%] md:w-[100px] !whitespace-pre",
    },
    {
      label: "Diperbarui",
      value: "updated_at",
      type: "date",
      isSearchable: true,
      className: "text-[13px] w-[10%] md:w-[100px] !whitespace-pre",
      isDetail: true,
    },
    {
      label: "Dihapus",
      value: "deleted_at",
      type: "date",
      className: "text-[13px] w-[10%] md:w-[100px] !whitespace-pre",
      isHidden: params.get("deleted_at") != "show",
    },
    {
      label: `Di Review Oleh`,
      value: "reviewer.name",
      className: 'text-[13px] w-[10%] md:w-[100px]',
      isDetail: true,
      isHidden: 'not null',
    },
    {
      label: "Aksi",
      value: "id",
      type: "action",
    },
    {
      value: "attachments",
      label: "Bukti Pembayaran",
      type: "gallery",
      wrapperClassName: "flex flex-col",
      valueClassName: "border py-2 px-4",
      isDetail: true,
      isHidden: 'not null'
    },
  ]

  return header
}

const useFilterOptions = () => {
  const { props } = usePage()
  const filterOptions = [
    {
      name: "status",
      data: props?.status ?? [],
      label: "Filter Status",
      prefix: "payment.status",
    },
    {
      name: "method",
      data: props?.method ?? [],
      label: "Filter Metode Pembayaran",
      prefix: "payment.method",
    },
    {
      name: "type",
      data: props?.type ?? [],
      label: "Filter Tipe Pembayaran",
      prefix: "payment.type",
    },
  ]

  return filterOptions
}

const HeaderProvider = ({ children }) => {
  const header = useTableHeader()
  return children(header)
}

const FilterProvider = ({ children }) => {
  const filterOptions = useFilterOptions()
  return children(filterOptions)
}

Index.Table = TableIndex
Index.HeaderProvider = HeaderProvider
Index.FilterProvider = FilterProvider

const PaymentIndex = Index
export default PaymentIndex
