import { Link, router, 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, number, 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 ApprovedModal from "@/Components/Modal/ApprovedModal"
import RejectedModal from "@/Components/Modal/RejectedModal"
import SubmitModal from "@/Components/Modal/SubmitModal"
import useStatus, { useStatusLabel } from "@/utils/useStatus"
import useLang from "@/utils/useLang"
import { Eye, FileText, History, CreditCard, Check, X, Send, Banknote, ShoppingBag, Pencil, RotateCcw, Trash2 } from "lucide-react"

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
        addButton={['user'].includes(props?.auth?.user?.role)}
        search
        filter
        filterOptions={filterOptions}
        tableHeader={tableHeader}
        tableBody={props?.[props?.page?.name]?.data ?? []}
        tablePage={props?.[props?.page?.name]}
        tableAction={(data) => {
          const { user } = props.auth

          let isDisabled = ![data.approval_level].includes(user.role) || !['review'].includes(data.status)
          let isDisabledRevision = ![data.approval_level].includes(user.role) || !['revision'].includes(data.status)
          let isPaymentRequestDisabled = !['approved'].includes(data.status) || parseInt(data?.paid_percentage ?? 0) >= 100

          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>
              <li className="mb-1">
                <Link href={`${props?.page?.url}/${data.id}/budget_details`} className="menu-item-action">
                  <FileText className="w-4 h-4 text-green-500" />
                  <span>Lihat Anggaran Detail</span>
                </Link>
              </li>
              <li className="mb-1">
                <Link href={`${props?.page?.url}/${data.id}/approval_logs`} className="menu-item-action">
                  <History className="w-4 h-4 text-orange-500" />
                  <span>Lihat Approval Log</span>
                </Link>
              </li>
              <li className="mb-1">
                <button className="menu-item-action" onClick={() => router.get(`/admin/budgets/${data?.id}/payment_details`)}>
                  <CreditCard className="w-4 h-4 text-purple-500" />
                  <span>Detail Pembayaran</span>
                </button>
              </li>

              {props.isAdmin ? (
                <>
                  <li className="mb-1">
                    <button disabled={isDisabled} id={`approved_${data?.id}`} className="menu-item-action" onClick={() => router.get(`/admin/budgets/${data?.id}/budget_approvals`)}>
                      <Check className="w-4 h-4 text-green-600" />
                      <span className="text-green-700">Setujui {props?.page?.label}</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 {props?.page?.label}</span>
                    </ModalButton>
                  </li>
                </>
              ) : (
                <>
                  {['user'].includes(user.role) && (
                    <>
                      <li className="mb-1">
                        <ModalButton disabled={!['draft'].includes(data.status)} id={`submit_${data?.id}`} onClick={() => handleShow(data)} className="menu-item-action">
                          <Send className="w-4 h-4 text-blue-600" />
                          <span className="text-blue-700">Ajukan Persetujuan Anggaran</span>
                        </ModalButton>
                      </li>
                      {['cash_advance'].includes(data.type) ? (
                        <li className="mb-1">
                          <button disabled={isPaymentRequestDisabled} className="menu-item-action" onClick={() => router.get(`/admin/budgets/${data?.id}/payment_requests`)}>
                            <Banknote className="w-4 h-4 text-emerald-600" />
                            <span className="text-blue-700">Ajukan Pencairan Dana</span>
                          </button>
                        </li>
                      ) : null}
                      {['purchase_order'].includes(data.type) ? (
                        <li className="mb-1">
                          <button disabled={isPaymentRequestDisabled} className="menu-item-action" onClick={() => router.get(`/admin/budgets/${data?.id}/purchase_orders`)}>
                            <ShoppingBag className="w-4 h-4 text-indigo-600" />
                            <span className="text-blue-700">Ajukan Pembayaran PO</span>
                          </button>
                        </li>
                      ) : null}
                    </>
                  )}
                  <li className="mb-1">
                    <button disabled={!['draft'].includes(data.status)} className="menu-item-action" onClick={() => router.get(`/admin/budgets/${data?.id}/edit`)}>
                      <Pencil className="w-4 h-4 text-amber-500" />
                      <span>Edit Draft</span>
                    </button>
                  </li>
                </>
              )}

              {['user', 'manager'].includes(user.role) && (
                <li className="mb-1">
                  <button disabled={isDisabledRevision} className="menu-item-action" onClick={() => router.get(`/admin/budgets/${data?.id}/budget_revisions`)}>
                    <RotateCcw className="w-4 h-4 text-purple-700" />
                    <span className="text-purple-700">Revisi Anggaran</span>
                  </button>
                </li>
              )}

              <li className="mb-1">
                <ModalButton disabled={!['draft'].includes(data?.status)} id={`delete_${data?.id}`} onClick={() => handleShow(data)} className="menu-item-action">
                  <Trash2 className="w-4 h-4 text-red-600" />
                  <span className="text-red-700">Hapus Draft</span>
                </ModalButton>
              </li>
            </>
          )
        }}
        tableFooter={(tableProps) => {
          const { tableBody, tableHeader, defaultClassName: { tdBodyClassName, trBodyClassName }, isTable = true } = tableProps
          const dataSum = props?.[`budgetSum`] ?? {}

          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">Debit</span>
                      <span className="font-semibold">{currency(dataSum?.debit_amount ?? 0)}</span>
                    </div>
                    <div className="flex flex-col items-center sm:items-end">
                      <span className="text-gray-500 text-xs">Kredit</span>
                      <span className="font-semibold">{currency(dataSum?.credit_amount ?? 0)}</span>
                    </div>
                    <div className="flex flex-col items-center sm:items-end">
                      <span className="text-gray-500 text-xs">Anggaran Tersedia</span>
                      <span className="font-semibold">{currency(dataSum?.remaining_amount ?? 0)}</span>
                    </div>
                    <div className="flex flex-col items-center sm:items-end">
                      <span className="text-gray-500 text-xs">Jumlah Terbayar</span>
                      <span className="font-semibold">{currency(dataSum?.paid_amount ?? 0)}</span>
                    </div>
                  </div>
                </div>
              </div>
            )
          }

          return (
            <tr className={`${trBodyClassName} bg-white w-full`}>
              <td colSpan={props.isAdmin ? 5 : 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?.debit_amount ?? 0)}
                </span>
              </td>
              <td>
                <span className="font-semibold">
                  {currency(dataSum?.credit_amount ?? 0)}
                </span>
              </td>
              <td>
                <span className="font-semibold">
                  {currency(dataSum?.remaining_amount ?? 0)}
                </span>
              </td>
              <td>
                <span className="font-semibold">
                  {currency(dataSum?.paid_amount ?? 0)}
                </span>
              </td>
              <td colSpan={props.isAdmin ? 4 : 4}></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 id={show?.id} tableHeader={tableHeader} data={show} handleClick={() => handleShow(null)} content={(data) => DetailModalContent(data, tableHeader)} size="max-w-2xl" />
          <ApprovedModal id={show?.id} isLabel={true} data={show} handleClick={() => handleShow(null)} content={(data) => DetailModalContent(data, tableHeader)} />
          <RejectedModal id={show?.id} isLabel={true} data={show} handleClick={() => handleShow(null)} content={(data) => DetailModalContent(data, tableHeader)} />
          <SubmitModal id={show?.id} isLabel={true} data={show} handleClick={() => handleShow(null)} content={(data) => DetailModalContent(data, tableHeader)} />
        </>
      ) : null}
    </>
  )
}

const useTableHeader = () => {
  const { page, isAdmin, location } = usePage().props
  const { params } = useSearchParams(location)
  const detailPageUrl = ({ data }) => {
    return `${page?.url}/${data.id}/budget_details`
  }

  const header = [
    {
      label: "#",
      value: "id",
      type: "numbering",
    },
    {
      value: "code",
      label: "Kode",
      isSearchable: true,
      className: "text-[13px] w-[10%] md:w-[100px] !whitespace-pre",
      // actionUrl: detailPageUrl,
    },
    {
      value: "date",
      label: "Tanggal",
      dateFormat: "DD MMM YYYY",
      type: "date",
      className: "text-[13px] w-[10%] md:w-[80px] !whitespace-pre",
      isSearchable: true,
    },
    {
      label: `Disubmit`,
      value: "user.name",
      className: 'text-[13px] w-[10%] md:w-[100px]',
      isSearchable: true,
      isDetail: false,
      isHidden: !isAdmin,
    },
    {
      value: "name",
      label: "Nama Anggaran",
      isSearchable: true,
      isDefaultLabel: true,
      custom: ({ data, key }) => {
        return (
          <td key={key} className={`text-[13px] min-w-[200px] whitespace-normal`}>
            <Link href={`${page?.url}/${data.id}/budget_details`} className="link-hover">
              {data.name}
            </Link>
          </td>
        )
      }
    },
    {
      value: "type",
      label: "Jenis",
      type: "status",
      prefix: "budget.type",
      className: '[&_div]:text-[13px] w-[10%]',
    },
    {
      label: "Debit",
      value: "debit_amount",
      className: 'text-[13px] w-[10%] md:w-[120px]',
      type: 'currency',
      defaultValue: '-'
    },
    {
      label: "Kredit",
      value: "credit_amount",
      className: 'text-[13px] w-[10%] md:w-[120px]',
      type: 'currency',
      defaultValue: '-'
    },
    {
      label: "Anggaran Tersedia",
      value: "remaining_amount",
      className: 'text-[13px] w-[10%] md:w-[120px]',
      type: 'currency',
      defaultValue: '-',
      isSortable: false
    },
    {
      label: "Jumlah Terbayar",
      value: "paid_amount",
      className: 'text-[13px] w-[10%] md:w-[120px]',
      type: 'currency',
      defaultValue: '-',
      isSortable: false
    },
    {
      label: "Persentase Terbayar",
      value: "paid_percentage",
      className: 'text-[13px] w-[10%] md:w-[120px]',
      defaultValue: '-',
      valueLabel: ({ value }) => `${number(value, "id-ID", 2)}%`,
      isSortable: false
    },
    {
      label: "Status",
      value: "status",
      type: "status",
      className: '[&_div]:text-[13px] w-[10%]',
      prefix: `budget.status`,
      isDefaultLabel: true,
      wrapperClassName: 'flex flex-wrap justify-between',
      custom: ({ data, key, header, defaultClassName }) => {
        return (
          <td key={key} className={`${defaultClassName?.tdBodyClassName} ${header?.className ?? ''}`}>
            <div className={`capitalize badge badge-xs py-2 ${useStatus(`${header?.prefix ?? ''}.${data?.status}`)}`}>
              {useStatusLabel(`${header?.prefix ?? ''}.${data?.status}`)}
              {["review", "revision"].includes(data.status) ? ` ${useLang(data.approval_level)}` : ""}
            </div>
          </td>
        )
      }
    },
    {
      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: "Aksi",
      value: "id",
      type: "action",
    },
    {
      label: `Di Submit Oleh`,
      value: "user.name",
      className: 'text-[13px] w-[10%] md:w-[100px]',
      isDetail: true,
      isHidden: !isAdmin,
    },
    {
      label: `Di Review Oleh`,
      value: "reviewer.name",
      className: 'text-[13px] w-[10%] md:w-[100px]',
      isDetail: true,
      isHidden: 'not null',
    },
    {
      label: "Tanggal Review",
      value: "review_at",
      type: "date",
      isHidden: 'not null',
      isDetail: true,
      className: 'text-[13px] w-[10%] md:w-[100px]',
      dateFormat: 'DD MMM YYYY hh:mm'
    },
  ]

  return header
}

const useFilterOptions = () => {
  const { props } = usePage()
  const filterOptions = [
    {
      name: "status",
      data: props?.status ?? [],
      label: "Filter Status",
      prefix: "budget.status",
    },
    {
      name: "type",
      data: props?.types ?? [],
      label: "Filter Jenis",
      prefix: "budget.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 BudgetIndex = Index
export default BudgetIndex
