import { useEffect, useState } from "react"
import classNames from "classnames"
import Container from "@/components/shared/Container"
import { APP_NAME } from "@/constants/app.constant"
import { PAGE_CONTAINER_GUTTER_X } from "@/constants/theme.constant"
import { useStoreActions, useStoreState } from "@/store"
import { Link, useNavigate } from "react-router-dom"
import { ROUTES_ENUM } from "@/routes/route.constant"
import UiDialog from "@/views/shared/UiDialog"

export type FooterPageContainerType = "gutterless" | "contained"

type FooterProps = {
  pageContainerType: FooterPageContainerType
}

const FooterContent = () => {
  const navigate = useNavigate()
  const { currentUiVersion } = useStoreState((a) => a.locale)
  const { setUiVersion } = useStoreActions((a) => a.locale)

  const apiConfig = useStoreState((state) => state.abpConfig.config?.extraProperties)

  const uiMode = import.meta.env.MODE

  const [latestVersion, setLatestVersion] = useState<string | null>(null)

  // version.json'dan en güncel UI versiyonunu al
  useEffect(() => {
    fetch("/version.json?ts=" + Date.now())
      .then((res) => res.json())
      .then((data) => {
        if (data?.releases?.length > 0) {
          setLatestVersion(data.releases[0].version) // en güncel hep en üstte
        }
      })
      .catch(() => setLatestVersion(null))
  }, [])

  return (
    <>
      <div className="flex flex-col sm:flex-row items-center justify-between w-full">
        <div className="space-x-1">
          <span>Copyright &copy; {new Date().getFullYear()}</span>
          <span className="font-semibold">{APP_NAME}</span>
        </div>
        <Link to={ROUTES_ENUM.protected.admin.changeLog}>
          <div className="text-muted capitalize">
            <span>
              <b>UI: </b>
              {uiMode}:{currentUiVersion}
            </span>
            <span className="mx-2">|</span>
            {apiConfig && (
              <span>
                <b>API: </b>
                {apiConfig["environment"].toString()}:{apiConfig["version"].toString()}
              </span>
            )}
          </div>
        </Link>
      </div>

      {latestVersion && latestVersion !== currentUiVersion && (
        <UiDialog
          key={`version-${latestVersion}`}
          isOpen={true}
          type="info"
          onConfirm={() => {
            setUiVersion(latestVersion)
            navigate(ROUTES_ENUM.protected.admin.changeLog)
          }}
          title="🎉 Yeni Güncelleme"
        >
          Sözsoft Kurs Platform Sistemi <b>v{latestVersion}</b> sürümüne güncellendi.
          <p>Detayları, "Güncelleme Günlüğü" ekranında görebilirsiniz.</p>
        </UiDialog>
      )}
    </>
  )
}

export default function Footer({ pageContainerType = "contained" }: FooterProps) {
  return (
    <footer
      className={classNames(
        `print:hidden footer flex flex-auto items-center h-6 ${PAGE_CONTAINER_GUTTER_X}`
      )}
    >
      {pageContainerType === "contained" ? (
        <Container>
          <FooterContent />
        </Container>
      ) : (
        <FooterContent />
      )}
    </footer>
  )
}
