import { Suspense, lazy, useEffect, useState } from "react"
import { useScript } from "usehooks-ts"
import useApp from "~/hooks/useApp"

import Disclaimer from "~/components/Disclaimer"
import InvalidConfig from "~/components/InvalidConfig"

import { isImageVaultDAMConfig } from "~/utils/imagevault"
import type { InsertResponse } from "~/types/imagevault"

const ImageVaultDAM = lazy(() => import("~/components/ImageVaultDAM"))

export default function Field() {
  const { sdk, config } = useApp()
  const ivStatus = useScript(
    "/scripts/imagevault-insert-media/insertmediawindow.min.js"
  )

  const [showDisclaimer, setShowDisclaimer] = useState(false)
  const [fieldData, setFieldData] = useState<InsertResponse>()

  const entry = sdk?.location.CustomField?.entry
  const field = sdk?.location.CustomField?.field

  useEffect(() => {
    // If we can get field data from the SDK that means the entry has been
    // saved at least once. If this is true, we are guaranteed entry UID.
    // Entry that has not been saved does not have a entry UID and therefore
    // cannot be referred to by ImageVault. Entry title is also required by us.
    try {
      if (field && entry) {
        const data = field.getData()
        const title = entry.getField("title").getData().toString()
        if (data && title) {
          setFieldData(data as InsertResponse)
        } else {
          throw new Error("Missing data or title for entry")
        }
      }
    } catch (e) {
      setShowDisclaimer(true)
    }
  }, [entry, field])

  if (showDisclaimer) {
    return <Disclaimer />
  }

  const loaded = !!(fieldData && ivStatus === "ready" && sdk && config)

  const initialData =
    fieldData && Object.keys(fieldData).length > 0 ? fieldData : null

  if (!loaded) {
    return <p style={{ fontFamily: "Inter" }}> Loading dependecies...</p>
  }

  return (
    <div id="field">
      {isImageVaultDAMConfig(config) ? (
        <Suspense fallback={<p>Loading field...</p>}>
          <ImageVaultDAM config={config} sdk={sdk} initialData={initialData} />
        </Suspense>
      ) : (
        <InvalidConfig />
      )}
    </div>
  )
}
