import { Link, usePage } from "@inertiajs/react"
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"
import Table from "@/Components/Table"
import DeleteModal from "@/Components/Modal/DeleteModal"
import { ModalButton } from "@/Components/WithModal"
import { currency, useSearchParams } from "@/utils/format"
import RestoreModal from "@/Components/Modal/RestoreModal"
import DetailModal from "@/Components/Modal/DetailModal"
import DetailModalContent from "@/Components/Default/DetailModalContent"
import { useAtom } from "jotai"
import { showModalAtom } from "@/atoms"
import Select from "@/Components/Form/Select"
import { router } from "@inertiajs/react"
import useStatus, { useStatusLabel } from "@/utils/useStatus"

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

const Breadcrumb = ({ currentLabel }) => {
  const { props } = usePage()

  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 Anggaran</Link></li>
      </ul>
    </div>
  )
}

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)
  }

  const { params } = useSearchParams(props?.location)
  const selectedCategoryIndex = props?.categories?.findIndex((category) => category.value == params.get("category_id"))

  return (
    <>
      <Table
        search
        filter
        addButton={false}
        filterOptions={filterOptions}
        tableHeader={tableHeader}
        tableBody={props?.[props?.page?.name]?.data ?? []}
        tablePage={props?.[props?.page?.name]}
        headerLeftButton={() => {
          return (
            <div className="flex-1 gap-2 flex-col">
              <Select
                placeholder="Pilih Kategori Item"
                isLabel={false}
                name="category_id"
                options={props?.categories ?? []}
                isReactSelect={true}
                isVirtualized={true}
                defaultValue={props?.categories?.[selectedCategoryIndex]}
                handleChange={(e) => {
                  params.set("page", "1")
                  params.set("category_id", e?.value ?? "")
                  return router.visit(`?${params.toString()}`, { method: "get", preserveState: true, preserveScroll: true, async: false })
                }} />
            </div>
          )
        }}
        tableAction={(data) => {
          return (
            <>
              <li>
                <ModalButton id={`detail_${data?.id}`} onClick={() => handleShow(data)}>
                  <span>Lihat Selengkapnya</span>
                </ModalButton>
              </li>
              {['approved'].includes(data.status) && ['user'].includes(props.auth?.user?.role) && (
                <li>
                  <button disabled={!!data?.transaction || !['approved'].includes(data.status)} className="capitalize cursor-pointer text-start whitespace-pre disabled:opacity-50" onClick={() => router.get(`/admin/budgets/${data.budget_id}/budget_details/${data.id}/transactions`)}>
                    <span className="text-green-700">Tambah Pembelian</span>
                  </button>
                </li>
              )}
              <li>
                <ModalButton disabled={!data?.transaction} id={`detail_transaction_${data?.id}`} onClick={() => handleShow(data)}>
                  <span>Lihat Pembelian</span>
                </ModalButton>
              </li>
            </>
          )
        }}
        tableFooter={(tableProps) => {
          const { tableBody, tableHeader, defaultClassName: { tdBodyClassName, trBodyClassName }, isTable = true } = tableProps
          const dataSum = props?.[`budgetCategorySum`] ?? {}

          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 Anggaran</span>
                      <span className="font-semibold">{currency(dataSum?.price_amount_total ?? 0)}</span>
                    </div>
                    <div className="flex flex-col items-center sm:items-end">
                      <span className="text-gray-500 text-xs">Total Realisasi</span>
                      <span className="font-semibold">{currency(dataSum?.transaction_price_total ?? 0)}</span>
                    </div>
                  </div>
                </div>
              </div>
            )
          }

          return (
            <tr className={`${trBodyClassName} bg-white w-full`}>
              <td colSpan={props.isAdmin ? 6 : 6} 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?.price_amount_total ?? 0)}
                </span>
              </td>
              <td>
                <span className="font-semibold">
                  {currency(dataSum?.transaction_price_total ?? 0)}
                </span>
              </td>
              <td colSpan={props.isAdmin ? 2 : 2}></td>
            </tr>
          )
        }}
        {...tableProps}
      />

      {show ? (
        <>
          <DeleteModal id={show?.id} label={show.name} isForceDelete={show.deleted_at != null} handleClick={() => handleShow(null)} />
          <RestoreModal id={show?.id} label={show.name} handleClick={() => handleShow(null)} />
          <DetailModal label="Detail Anggaran" id={show?.id} tableHeader={tableHeader} data={show} handleClick={() => handleShow(null)} content={(data) => DetailModalContent(data, tableHeader)} size="max-w-2xl" />
          <DetailModal label="Detail Pembelian" id={`transaction_${show?.id}`} tableHeader={useTransactionTableHeader()} data={show?.transaction} handleClick={() => handleShow(null)} content={(data) => DetailModalContent(data, useTransactionTableHeader())} size="max-w-2xl" />
        </>
      ) : null}
    </>
  )
}

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

  const header = [
    {
      label: "#",
      value: "id",
      type: "numbering",
    },
    {
      value: "name",
      label: "Nama Barang/Jasa",
      isSearchable: true,
    },
    {
      value: "description",
      label: "Keterangan",
      type: "text",
      isSearchable: true,
    },
    {
      value: "budget_category.category.name",
      label: "Kategori",
      type: "text",
    },
    {
      value: "price",
      label: "Harga",
      type: "currency",
    },
    {
      value: "quantity_units.quantity",
      label: "Kuantitas & Satuan",
      className: 'w-[10%]',
      isDefaultLabel: true,
      wrapperClassName: 'flex flex-wrap justify-between',
      custom: ({ data, key, header, defaultClassName, isTable = true }) => {
        const Tag = isTable ? "td" : "div"
        return (
          <Tag key={key}>
            <ul className={`list-disc list-inside`}>
              {data?.quantity_units?.map((qu, idx) => (
                <li key={idx}>
                  {qu.quantity} {qu.unit_type.name}
                </li>
              ))}
            </ul>
          </Tag>
        )
      }
    },
    {
      value: "price_total",
      label: "Total Anggaran",
      type: "currency",
    },
    {
      value: "transaction.price_total",
      label: "Total Realisasi",
      type: "currency",
      defaultValue: ({ data }) => (
        ['approved'].includes(data.status) && ['cash_advance'].includes(data.budget?.type) && ['user'].includes(auth?.user?.role) ? (
          <button className="btn btn-xs badge-soft" disabled={!!data?.transaction} onClick={() => router.get(`/admin/budgets/${data.budget_id}/budget_details/${data.id}/transactions`)}>
            <i className="fas fa-plus"></i>
            Tambah
          </button>
        ) : '-'
      )
    },
    {
      value: "status",
      label: "Status",
      isDefaultLabel: true,
      custom: ({ data, key, header, defaultClassName, isTable = true }) => {
        const Tag = isTable ? "td" : "div"
        return (
          <Tag key={key} className={defaultClassName.tdBodyClassName}>
            <div className={`flex gap-1 ${isTable ? `flex-col` : 'flex-row flex-wrap items-center'}`}>
              <div className={`capitalize badge badge-xs py-2 ${useStatus(`budget_detail.status.${data?.status}`)}`}>{useStatusLabel(`budget_detail.status.${data?.status}`)}</div>
              {data?.transaction?.status && data.status == 'approved' ? (
                <div className={`capitalize badge badge-xs py-2 ${useStatus(`transaction.status.${data?.transaction?.status}`)}`}>{useStatusLabel(`transaction.status.${data?.transaction?.status}`)}</div>
              ) : null}
            </div>
          </Tag>
        )
      }
    },
    {
      value: "status_message",
      label: "Catatan Penolakan",
      isDetail: true,
      isHidden: 'not null'
    },
    {
      label: "Ditambahkan",
      value: "created_at",
      type: "date",
      isDetail: true,
      className: "text-[13px] w-[10%] md:w-[100px] !whitespace-pre",
    },
    {
      label: "Diperbarui",
      value: "updated_at",
      type: "date",
      isDetail: true,
      className: "text-[13px] w-[10%] md:w-[100px] !whitespace-pre",
    },
    {
      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",
    },
  ]

  return header
}

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

  const header = [
    {
      label: "#",
      value: "id",
      type: "numbering",
    },
    {
      value: "name",
      label: "Nama Barang/Jasa",
      isSearchable: true,
    },
    {
      value: "description",
      label: "Keterangan",
      type: "text",
    },
    {
      value: "price",
      label: "Harga",
      type: "currency",
    },
    {
      value: "quantity_units.quantity",
      label: "Kuantitas & Satuan",
      className: 'w-[10%]',
      isDefaultLabel: true,
      wrapperClassName: 'flex flex-wrap justify-between',
      custom: ({ data, key, header, defaultClassName, isTable = true }) => {
        const Tag = isTable ? "td" : "div"
        return (
          <Tag key={key}>
            <ul className={`list-disc list-inside`}>
              {data?.quantity_units?.map((qu, idx) => (
                <li key={idx}>
                  {qu.quantity} {qu.unit_type.name}
                </li>
              ))}
            </ul>
          </Tag>
        )
      }
    },
    {
      value: "price_total",
      label: "Total Pembelian",
      type: "currency",
    },
    {
      value: "status",
      label: "Status",
      prefix: "transaction.status",
      type: "status",
    },
    {
      value: "status_message",
      label: "Catatan Penolakan",
      isDetail: true,
      isHidden: 'not null'
    },
    {
      label: "Disubmit Pada",
      value: "created_at",
      type: "date",
      isDetail: true,
      className: "text-[13px] w-[10%] md:w-[100px] !whitespace-pre",
    },
    {
      value: "attachments",
      label: "Bukti Pembayaran",
      type: "gallery",
      wrapperClassName: "flex flex-col",
      valueClassName: "border py-2 px-4",
      isDetail: true,
    },
  ]

  return header
}

const useFilterOptions = () => {
  const { props } = usePage()
  const filterOptions = [
    {
      name: "status",
      data: props?.status ?? [],
      label: "Filter Status",
      prefix: "budget.status",
    },
  ]

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