import { 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 { ModalButton } from "@/Components/WithModal"
import { useAtom } from "jotai"
import { showModalAtom } from "@/atoms"

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) => (
          <>
            <li>
              <ModalButton id={`detail_${data?.id}`} onClick={() => handleShow(data)}>
                <span>Lihat Selengkapnya</span>
              </ModalButton>
            </li>
          </>
        )}
        tableFooter={(tableProps) => {
          const { tableBody, tableHeader, defaultClassName: { tdBodyClassName, trBodyClassName }, isTable = true } = tableProps
          const summary = props?.summary ?? {}

          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 gap-3">
                  <span className="font-semibold text-lg text-gray-900 dark:text-gray-100">Total Keseluruhan</span>
                  <div className="flex flex-wrap gap-4 text-sm">
                    <div className="flex flex-col">
                      <span className="text-gray-500 text-xs">Total Anggaran</span>
                      <span className="font-semibold text-blue-600">{currency(summary?.total_debit ?? 0)}</span>
                    </div>
                    <div className="flex flex-col">
                      <span className="text-gray-500 text-xs">Total Realisasi</span>
                      <span className="font-semibold text-orange-600">{currency(summary?.total_credit ?? 0)}</span>
                    </div>
                    <div className="flex flex-col">
                      <span className="text-gray-500 text-xs">Sisa Saldo</span>
                      <span className="font-semibold text-green-600">{currency(summary?.total_remaining ?? 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 className={`${tdBodyClassName}`}>
                <span className="font-semibold text-blue-600">
                  {currency(summary?.total_debit ?? 0)}
                </span>
              </td>
              <td className={`${tdBodyClassName}`}>
                <span className="font-semibold text-orange-600">
                  {currency(summary?.total_credit ?? 0)}
                </span>
              </td>
              <td className={`${tdBodyClassName}`}>
                <span className="font-semibold text-green-600">
                  {currency(summary?.total_remaining ?? 0)}
                </span>
              </td>
              <td colSpan={5}></td>
            </tr>
          )
        }}
        {...tableProps}
      />

      {show ? (
        <>
          <DetailModal
            id={show?.id}
            tableHeader={tableHeader}
            data={show}
            handleClick={() => handleShow(null)}
            content={(data) => DetailModalContent(data, tableHeader)}
            size="max-w-2xl"
          />
        </>
      ) : null}
    </>
  )
}

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

  const header = [
    {
      label: "#",
      value: "id",
      type: "numbering",
    },
    {
      value: "code",
      label: "Kode",
      isSearchable: true,
    },
    {
      value: "department.name",
      label: "Departemen",
      isSearchable: true,
    },
    {
      value: "debit_amount",
      label: "Total Anggaran",
      type: "currency",
    },
    {
      value: "credit_amount",
      label: "Realisasi",
      type: "currency",
    },
    {
      value: "remaining_amount",
      label: "Sisa Saldo",
      type: "currency",
      render: (data) => currency((data?.debit_amount ?? 0) - (data?.credit_amount ?? 0)),
    },
    {
      value: "year",
      label: "Tahun",
    },
    {
      value: "user.name",
      label: "PIC",
      isDetail: true,
    },
    {
      value: "company.name",
      label: "Perusahaan",
      isDetail: true,
    },
    {
      label: "Waktu",
      value: "created_at",
      type: "date",
      isSearchable: true,
      className: "text-[13px] w-[10%] md:w-[100px] !whitespace-pre",
    },
    {
      label: "Aksi",
      value: "id",
      type: "action",
    },
  ]

  return header
}

const useFilterOptions = () => {
  const { props } = usePage()
  const filterOptions = []

  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 ReportIndex = Index
export default ReportIndex
