import { usePage } from "@inertiajs/react"
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"
import Table from "@/Components/Table"
import { ModalButton } from "@/Components/WithModal"
import { 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 } 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
        search
        filter
        filterOptions={filterOptions}
        tableHeader={tableHeader}
        addButton={false}
        tableBody={props?.[props?.page?.name]?.data ?? []}
        tablePage={props?.[props?.page?.name]}
        tableAction={(data) => {
          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>
            </>
          )
        }}
        {...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 Transaksi",
      isSearchable: true,
    },
    {
      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: "vendor",
      label: "Vendor",
      isDefaultLabel: true,
      isHidden: 'not null',
      wrapperClassName: 'flex flex-col justify-between',
      custom: ({ data, key, header, defaultClassName, isTable = true }) => {
        const Tag = isTable ? "td" : "div"
        const vendor = data?.vendor

        if (!vendor) return <Tag key={key}>-</Tag>

        return (
          <Tag key={key} className={isTable ? defaultClassName : ""}>
            <div className="flex flex-col gap-1 min-w-[200px] p-2 rounded border border-gray-100">
              <div className="font-bold text-gray-800 text-sm">{vendor.company_name || '-'}</div>
              <div className="text-sm text-gray-600 flex items-center gap-1">
                <span className="font-semibold w-8">PIC:</span>
                <span>{vendor.name || '-'}</span>
              </div>
              <div className="text-sm text-gray-500 flex items-center gap-2 mt-1 border-t border-gray-200 pt-1">
                <span>{vendor.phone || '-'}</span>
                <span>&bull;</span>
                <span>{vendor.city || '-'}</span>
              </div>
            </div>
          </Tag>
        )
      }
    },
    {
      value: "attachments",
      label: "Lampiran",
      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: "transaction.status",
    },
    {
      name: "type",
      data: props?.type ?? [],
      label: "Filter Tipe Transaksi",
      prefix: "transaction.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 TransactionIndex = Index
export default TransactionIndex
