import { currency, dateFormat, isFunction, isNumber, paginationNumber } from "@/utils/format"
import useLang from "@/utils/useLang"
import useStatus, { useStatusLabel } from "@/utils/useStatus"
import { Link, usePage } from "@inertiajs/react"
import { useSetAtom } from "jotai"
import { showModalAtom } from "@/atoms"
import { ModalButton } from "./WithModal"
import { useState, isValidElement } from "react"
import ImageGallery from "react-image-gallery"
import "react-image-gallery/styles/css/image-gallery.css"
import RowLabel from "@/Components/RowLabel"
import { WithAction } from "./Table"

const TableContentItem = ({ header, item, index, variant = "table", className = "", ...props }) => {
  const { props: pageProps } = usePage()
  const setShow = useSetAtom(showModalAtom)
  const [isFullScreen, setIsFullScreen] = useState(false)

  const defaultRowProps = {
    wrapperClassName: props?.wrapperClassName ?? 'flex flew-row flex-wrap justify-between',
    labelClassName: props?.labelClassName ?? "flex-1 font-medium text-sm md:text-base",
    valueClassName: props?.valueClassName ?? "text-sm md:text-base",
    emptyCheck: props?.emptyCheck ?? false
  }

  let rowProps = { ...defaultRowProps }
  for (const key of Object.keys(rowProps)) {
    if (key in (header || {})) {
      rowProps[key] = header[key]
    }
  }

  // 1. Pre-checks (Hidden, Detail)
  if (variant === "table") {
    if ("isDetail" in (header || {}) && header.isDetail === true) return null
    if ("isHidden" in (header || {}) && header.isHidden === true) return null
  } else if (variant === "modal") {
    if ("isDetail" in (header || {}) && header.isDetail === false) return null
    if ("isHidden" in (header || {}) && header.isHidden === true) return null
  } else if (variant === "card") {
    // 
  }

  // 2. Value Extraction
  let headerValue = header?.value?.split(".")
  let value = headerValue?.reduce((acc, key) => acc?.[key], item)

  if (!value && value !== 0 && value !== false) {
    value = ""
  }

  if ('isHidden' in (header || {}) && header.isHidden === 'not null' && (!value || value === "" || value?.length === 0)) return null;

  // 3. Transformations
  let prefix = header?.prefix
  if (prefix && !prefix?.endsWith(".")) {
    prefix += "."
  }
  if (!!header?.prefix && header?.type !== "status") {
    value = `${prefix ?? ""}${value}`
  }

  // Value Label
  if (!!header?.valueLabel && !!value) {
    if (isFunction(header?.valueLabel)) {
      value = header?.valueLabel({ data: item, value })
    } else {
      value = header?.valueLabel.toString().replaceAll("[value]", value)
    }
  }

  // Default Value
  if ((!value && value !== 0) && !!header?.defaultValue) {
    value = isFunction(header?.defaultValue) ? header?.defaultValue({ data: item, value, key: 0, rowIndex: index, header }) : header?.defaultValue
  }

  // Type Case
  let typeCase = "normal"
  if ("typeCase" in (header || {}) && header.typeCase) {
    typeCase = header.typeCase
  }
  if (typeCase === "lowerCase") {
    value = value?.toLowerCase()
  }

  // 4. Custom Renderer
  if (header?.custom && typeof header?.custom === "function") {
    const Custom = header.custom
    const customProps = {
      data: item,
      key: index,
      rowIndex: index,
      header,
      defaultClassName: { tdBodyClassName: className, trBodyClassName: "" },
      isTable: variant === "table"
    }

    if (variant === "modal" && header?.isDefaultLabel) {
      const wrapperClassName = header?.wrapperClassName ?? "flex flex-col"
      return (
        <RowLabel label={header.label} wrapperClassName={wrapperClassName} {...rowProps} >
          <Custom {...customProps} />
        </RowLabel>
      )
    }

    return <Custom {...customProps} />
  }

  if (!value && value !== 0 && value !== false) {
    const defVal = header?.defaultValue ?? "-"
    if (variant === "table") return <td className={`${className} ${header?.className ?? ""}`}>{defVal}</td>
    if (variant === "modal") return <RowLabel label={header.label} {...rowProps} wrapperClassName="grid">{defVal}</RowLabel>
    return defVal
  }

  if (variant === "modal" && ["numbering", "action"].includes(header.type)) {
    return <></>
  }

  // 5. Specific Types
  // Boolean
  if (header.type === "boolean") {
    value = !!value ? "Ya" : "Tidak"
  }

  if (header.type === "numbering" && variant === "table") {
    let pageData = pageProps?.[pageProps?.page?.name]
    return (
      <th scope="row" className={`text-start w-10 ${className}`}>
        {pageData ? paginationNumber(pageData, index) : index + 1}
      </th>
    )
  }

  // Action (Table only usually)
  if (header.type === "action" && props.tableAction && variant === "table") {
    return <WithAction item={item} actionMenu={props.tableAction} align="right" {...props} />
  }

  // Status
  if (header.type === "status") {
    const statusContent = (
      <div className={`capitalize badge ${variant === 'table' ? 'badge-xs p-2' : 'badge-sm border-0'} ${useStatus(`${prefix ?? ""}${value}`)}`}>
        {useStatusLabel(`${prefix ?? ""}${value}`)}
      </div>
    )

    if (variant === "modal") {
      return (
        <RowLabel label={header.label} {...rowProps} valueClassName={`${rowProps.valueClassName ?? ''} pb-1`}>
          {statusContent}
        </RowLabel>
      )
    }

    if (variant === "table") {
      return (
        <td className={`${className} ${header?.className ?? ""}`}>
          {statusContent}
        </td>
      )
    }

    return statusContent
  }

  // Date
  if (header.type === "date") {
    const formattedDate = !!value && value !== "-" ? dateFormat(value, header.dateFormat ?? null) : (header?.defaultValue ?? "-")

    if (variant === "table") {
      let tdClassName = className
      if (!tdClassName.includes("text-[13px]")) {
        tdClassName = "text-[13px] w-[10%] md:w-[100px] !whitespace-pre "
      }
      const finalCb = Array.from(
        new Set([...(tdClassName?.split(" ") ?? []), ...(header?.className?.split(" ") ?? [])].filter(Boolean)),
      ).join(" ")
      return <td className={finalCb}>{formattedDate}</td>
    }

    if (variant === "modal") {
      return <RowLabel label={header.label} {...rowProps}>{formattedDate}</RowLabel>
    }

    return formattedDate
  }

  // Currency
  if (header.type === "currency") {
    let headerCurrencyCode = header.currency_code?.split(".")
    let currencyCode = "IDR"
    if (headerCurrencyCode) {
      currencyCode = headerCurrencyCode.reduce((acc, key) => acc?.[key], item)
    }

    if (value == 0) {
      value = "-"
    }

    const formattedCurrency = isNumber(parseInt(Math.abs(value))) ? currency(value, "id-ID", currencyCode) : value

    if (variant === "table") {
      return <td className={`${className} ${header?.className ?? ""}`}>{formattedCurrency}</td>
    }

    if (variant === "modal") {
      return <RowLabel label={header.label} {...rowProps}>{formattedCurrency}</RowLabel>
    }

    return formattedCurrency
  }

  // List
  if (header.type === "list") {
    const values = value ? value.toString().split("\n") : []
    let isEmpty = false
    if (values?.length == 0) isEmpty = true
    if (values?.length == 1 && values[0] == "") isEmpty = true

    if (isEmpty && variant === "table") return <td className={`${className} ${header?.className ?? ""}`}>-</td>
    if (isEmpty && variant === "modal") return <RowLabel label={header.label} {...rowProps} wrapperClassName="grid">-</RowLabel>

    let listClassName = header?.listClassName ?? "list-disc list-inside"

    const listContent = (
      <ul className={listClassName}>
        {values.map((v, i) => <li key={i}>{v}</li>)}
      </ul>
    )

    if (variant === "table") {
      return <td className={`${className} ${header?.className ?? ""}`}>{listContent}</td>
    }

    if (variant === "modal") {
      return <RowLabel label={header.label} {...rowProps} wrapperClassName="grid">{listContent}</RowLabel>
    }

    return listContent
  }

  // HTML
  if (header.type === "html") {
    const htmlContent = <div className={header?.className} dangerouslySetInnerHTML={{ __html: value }} />

    if (variant === "modal") {
      return <RowLabel label={header.label} wrapperClassName="flex flex-col" {...rowProps}>{htmlContent}</RowLabel>
    }
    return htmlContent
  }

  // Gallery
  if (header.type === "gallery") {
    const images = value?.map((image) => ({
      original: image?.value,
      thumbnail: image?.value,
      originalClass: `w-full p-4 object-cover ${isFullScreen ? "" : "max-w-[300px] max-h-[300px]"}`
    })) || []

    const galleryOptions = {
      showThumbnails: false,
      showBullets: true,
      showFullscreenButton: true,
      showPlayButton: false,
      onScreenChange: (fullscreen) => setIsFullScreen(fullscreen)
    }

    const galleryContent = images.length > 0 ? <ImageGallery items={images} {...galleryOptions} /> : "-"

    if (variant === "modal") {
      return <RowLabel label={header.label} {...rowProps}>{galleryContent}</RowLabel>
    }
    return galleryContent
  }

  // Image
  if (header.type === "image") {
    const imgContent = value ? (
      <img src={value} alt={header.label} className={`w-full max-w-[12rem] object-cover ${header?.className ?? ""}`} />
    ) : (header?.defaultValue ?? "-")

    if (variant === "modal") {
      return <RowLabel label={header.label} wrapperClassName="flex flex-col" {...rowProps}>{imgContent}</RowLabel>
    }
    return imgContent
  }

  // Video
  if (header.type === "video") {
    const videoContent = value ? (
      <video src={value} controls className={`w-full max-w-[12rem] object-cover ${header?.className ?? ""}`} />
    ) : (header?.defaultValue ?? "-")

    if (variant === "modal") {
      return <RowLabel label={header.label} wrapperClassName="flex flex-col" {...rowProps}>{videoContent}</RowLabel>
    }
    return videoContent
  }

  // Status Message (Modal specific in legacy)
  if (header.type === 'status_message' && variant === 'modal') {
    if (!item?.status_message) return null
    return (
      <RowLabel label={`Alasan Status`} wrapperClassName="flex flex-col" {...rowProps} >
        {item?.status_message}
      </RowLabel>
    )
  }

  // Action URL
  let actionUrl = null
  if (header?.actionUrl && typeof header?.actionUrl === "function") {
    actionUrl = header?.actionUrl({ data: item })
  }

  if (!!actionUrl) {
    const linkContent = (
      <Link href={actionUrl} className={variant === 'card' ? "underline text-blue-600 hover:text-blue-800" : "underline"}>
        {useLang(value)}
      </Link>
    )

    if (variant === "table") {
      return <td className={`${className} ${header?.className ?? ""}`}>{linkContent}</td>
    }
    if (variant === "modal") {
      return <RowLabel label={header.label} {...rowProps}>{linkContent}</RowLabel>
    }
    return linkContent
  }

  // Default Render

  // Modal Detail Button (Table only)
  let isModalDetail = false
  if ("isModalDetail" in (header || {}) && header.isModalDetail === true) {
    isModalDetail = true
  }

  if (variant === "table") {
    return (
      <td className={`${className} ${header?.className ?? ""}`}>
        {isModalDetail ? (
          <ModalButton id={`detail_${item?.id}`} onClick={() => setShow(item)}>
            <span>{value}</span>
          </ModalButton>
        ) : (
          useLang(value)
        )}
      </td>
    )
  }

  if (variant === "modal") {
    return (
      <RowLabel label={header.label} {...rowProps} >
        {isModalDetail ? (
          <ModalButton id={`detail_${item?.id}`} onClick={() => setShow(item)}>
            <span>{value}</span>
          </ModalButton>
        ) : useLang(value)}
      </RowLabel>
    )
  }

  if (isValidElement(value)) return value
  if (value && typeof value === "object") return JSON.stringify(value)
  return useLang(value) || "-"
}

export default TableContentItem
