import { addToast, Button, Input, Spinner } from "@heroui/react"
import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"
import { useSteamStore } from "@/store/steam"
import { open } from "@tauri-apps/plugin-dialog"
import { invoke } from "@tauri-apps/api/core"
import { onOpenUrl } from "@tauri-apps/plugin-deep-link"
import { useDebounce } from "ahooks"
import { useAppStore } from "@/store/app"

/**
 * 检查指定路径的有效性
 * @param path - 需要检查的路径
 * @param suffix - (可选) 路径需要匹配的后缀条件
 * @returns Promise<boolean> 路径是否有效且满足后缀条件
 */
async function check_path(path: string, suffix?: string) {
  if (suffix && !path.toLowerCase().startsWith(suffix)) return false
  const exist = await invoke<boolean>("check_path", { path: path })
  return exist
}

function trim_end_string(str: string, suffix: string): string {
  if (str.endsWith(suffix)) {
    return str.slice(0, -suffix.length)
  }
  return str
}

export function Prepare() {
  const steam = useSteamStore()
  const app = useAppStore()
  const router = useRouter()
  const [loading, setLoading] = useState(true)
  const [inited, setInited] = useState(false)
  const [, setSteamDir] = useState(steam.state.steamDir)
  const [, setCs2Dir] = useState(steam.state.cs2Dir)

  // Init
  useEffect(() => {
    const init = async () => {
      await steam.store.start()
      await app.store.start()
      if (!app.state.inited) await autoGetPaths(false)
      setInited(true)
    }
    void init()
  }, [])

  // valid变动后调整State
  const [checkCount, setCheckCount] = useState(0)
  useEffect(() => {
    setCheckCount((prev) => (prev >= 10 ? 10 : prev + 1))
    // console.log(checkCount, "触发", steam.state.steamDir, steam.state.cs2Dir, app.state.inited)
    if (checkCount <= 2) {
      if (steam.state.steamDir && steam.state.cs2Dir && app.state.inited) {
        setTimeout(() => {
          router.push("/home")
        }, 300)
      } else {
        setTimeout(() => {
          setLoading(false)
        }, 1000)
      }
    } else {
      setTimeout(() => {
        setLoading(false)
      }, 1200)
    }
  }, [inited])

  const handleSelectSteamDir = async () => {
    const selected = await open({
      title: "选择 Steam.exe 文件",
      filters: [{ name: "steam", extensions: ["exe"] }],
    })
    if (selected) {
      const dir = selected.replace(/\\[^\\]+$/, "")
      const pathExist = await invoke("check_path", { path: dir })
      if (!pathExist) {
        addToast({ title: "路径不存在", color: "warning" })
        return
      }
      setSteamDir(dir)
      steam.setDir(dir)
    }
  }

  const autoGetPaths = async (toast?: boolean) => {
    try {
      const steam_path = await invoke<string>("get_steam_path")
      if (steam_path) steam.setDir(steam_path)
    } catch (e) {
      addToast({ title: "自动获取Steam路径失败", color: "danger" })
    }

    try {
      const cs2_path = await invoke<string>("get_cs_path", {
        name: "cs2",
        steamDir: steam.state.steamDir,
      })
      if (cs2_path) {
        steam.setCsDir(cs2_path)
        if (toast) addToast({ title: "自动获取路径成功", color: "success" })
      }
    } catch (e) {
      addToast({ title: "自动获取CS2路径失败", color: "danger" })
      console.log(e)
    }
  }

  const handleSelectCs2Dir = async () => {
    const selected = await open({
      title: "选择 CS2.exe 文件",
      filters: [{ name: "cs2", extensions: ["exe"] }],
    })
    if (selected) {
      const dir = selected.replace(/\\[^\\]+$/, "")
      const pathExist = await invoke("check_path", { path: dir })
      if (!pathExist) {
        addToast({ title: "路径不存在", color: "warning" })
        return
      }
      // setCs2Dir(dir)
      steam.setCsDir(dir)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center gap-4">
        <Spinner size="md" variant="simple" />
        <p>正在检查路径...</p>
      </div>
    )
  }

  return (
    <div className="flex flex-col w-full max-w-3xl gap-2 p-5">
      <p className="text-center">请确认下列设置以确保工具箱正常运行</p>
      <br />
      <h3 className="font-semibold">Steam所在文件夹</h3>
      <div className="flex gap-2">
        <Input
          variant="bordered"
          size="sm"
          value={steam.state.steamDir}
          onValueChange={(value) => {
            setSteamDir(value)
            steam.setDir(value)
          }}
          description="steam.exe所在文件夹"
          errorMessage={"路径无效"}
          isInvalid={!steam.state.steamDirValid}
        />
        <Button
          onPress={handleSelectSteamDir}
          variant="solid"
          color="primary"
          size="sm"
          isLoading={steam.state.steamDirChecking}
        >
          选择
        </Button>
      </div>
      <h3 className="font-semibold">CS2所在文件夹</h3>
      <div className="flex gap-2">
        <Input
          variant="bordered"
          size="sm"
          value={steam.state.cs2Dir}
          onValueChange={(value) => {
            setCs2Dir(value)
            steam.setCsDir(value)
          }}
          description="cs2.exe所在文件夹"
          errorMessage={"路径无效，建议启动游戏后点击自动获取，可以检测运行中的cs2"}
          isInvalid={!steam.state.cs2DirValid}
        />
        <Button
          onPress={handleSelectCs2Dir}
          variant="solid"
          color="primary"
          size="sm"
          isLoading={steam.state.cs2DirChecking}
        >
          选择
        </Button>
      </div>

      <TestDeepLink />

      <section className="flex justify-center w-full gap-3 mt-6">
        <Button
          onPress={() => void autoGetPaths(true)}
          variant="ghost"
          color="default"
          size="md"
          className="w-24"
        >
          自动获取
        </Button>
        <Button
          onPress={() => {
            app.setInited(true)
            router.push("/home")
          }}
          variant="solid"
          color="primary"
          size="md"
          className="w-24"
          isLoading={steam.state.steamDirChecking || steam.state.cs2DirChecking}
          isDisabled={!steam.state.steamDirValid || !steam.state.cs2DirValid}
        >
          进入
        </Button>
      </section>
    </div>
  )
}

function TestDeepLink() {
  const [links, setLinks] = useState<string[]>([])
  const router = useRouter()

  useEffect(() => {
    void onOpenUrl((urls) => {
      console.log("deep link:", urls)
      setLinks(urls)
    })
  }, [router])
  return <>{links.length > 0 && <p className="text-white">{links}</p>}</>
}
