import { useEffect } from "react"
import StepWizard from "./components/StepWizard"
import SelectableCard from "./components/SelectableCard"
import Loader from "./components/Loader"
import { useNavigate } from "react-router"
import { useShallow } from "zustand/react/shallow"
import useStore from "./utils/store"

import { publicInteractiveCreation, isHuman } from "./utils/rigo"
import {
  checkParams,
  isValidRigoToken,
  loginWithToken,
  parseLesson,
  fixTitleLength,
  getTechnologies,
} from "./utils/lib"

import { Uploader } from "./components/Uploader"
import toast from "react-hot-toast"
import { ParamsChecker } from "./components/ParamsChecker"
import { DEV_MODE, RIGO_FLOAT_GIF } from "./utils/constants"
import TurnstileChallenge from "./components/TurnstileChallenge"
// import TurnstileChallenge from "./components/TurnstileChallenge"
import ResumeCourseModal from "./components/ResumeCourseModal"
import { possiblePurposes, PurposeSelector } from "./components/PurposeSelector"
import { useTranslation } from "react-i18next"

function App() {
  const navigate = useNavigate()
  const { t, i18n } = useTranslation()

  const {
    formState,
    setFormState,
    setAuth,
    push,
    cleanHistory,
    setPlanToRedirect,
    history,
    uploadedFiles,
    auth,
    resetFormState,
    cleanAll,
    setMessages,
    technologies,
    setTechnologies,
  } = useStore(
    useShallow((state) => ({
      formState: state.formState,
      setFormState: state.setFormState,
      setAuth: state.setAuth,
      technologies: state.technologies,
      setTechnologies: state.setTechnologies,
      push: state.push,
      history: state.history,
      cleanHistory: state.cleanHistory,
      setPlanToRedirect: state.setPlanToRedirect,
      uploadedFiles: state.uploadedFiles,
      auth: state.auth,
      resetFormState: state.resetFormState,
      cleanAll: state.cleanAll,
      setMessages: state.setMessages,
    }))
  )

  useEffect(() => {
    if (formState.isCompleted) {
      handleCreateTutorial()
    }
  }, [formState])

  useEffect(() => {
    verifyToken()
    checkQueryParams()
    checkTechs()
  }, [])

  const verifyToken = async () => {
    const { token } = checkParams(["token"])
    if (token) {
      const user = await loginWithToken(token)
      setAuth({
        bcToken: token,
        userId: user.id,
        rigoToken: user.rigobot.key,
        user: user,
        publicToken: "",
      })
    }
  }

  const checkQueryParams = () => {
    const {
      description,
      duration,
      plan,
      purpose,
      language,
      new: newParam,
    } = checkParams([
      "description",
      "duration",
      "plan",
      "purpose",
      "language",
      "new",
    ])
    if (description) {
      console.log("description", description)
      setFormState({
        description: description,
        currentStep: "duration",
      })
    }
    if (duration && description && !isNaN(parseInt(duration))) {
      if (["30", "60", "120"].includes(duration)) {
        const durationInt = parseInt(duration)
        console.log("duration", durationInt)
        setFormState({
          duration: durationInt,
          currentStep: "hasContentIndex",
        })
      } else {
        console.log("Invalid duration received in params", duration)
      }
    }

    if (plan) {
      setPlanToRedirect(plan)
    } else {
      console.debug("No plan received in params")
    }

    if (language && language.length === 2) {
      setFormState({
        language: language,
      })
    }

    if (purpose && purpose.length > 0 && possiblePurposes.includes(purpose)) {
      setFormState({
        purpose: purpose,
        currentStep: "hasContentIndex",
      })
    }

    if (newParam && newParam.toLowerCase().trim() === "true") {
      cleanAll()
    }
  }

  const handleCreateTutorial = async () => {
    try {
      let isAuthenticated = false
      if (auth.publicToken) {
        isAuthenticated = await isValidRigoToken(auth.publicToken)
      }
      if (!isAuthenticated && auth.rigoToken) {
        setAuth({
          ...auth,
          rigoToken: "",
          bcToken: "",
          userId: "",
          user: null,
        })
      }

      let techs = technologies.filter((t) => t.lang === formState.language)

      if (techs.length === 0) {
        techs = technologies.filter((t) => t.lang === "us")
      }

      const res = await publicInteractiveCreation(
        {
          courseInfo: `${JSON.stringify(
            formState
          )}. The following technologies are available, choose up to 3 from the following list: <techs>${techs
            .map((t) => t.slug)
            .join(", ")}</techs>`,
          prevInteractions: "USER: " + formState.description,
        },
        auth.rigoToken && isAuthenticated ? auth.rigoToken : auth.publicToken,
        formState.purpose || "learnpack-lesson-writer",
        auth.rigoToken && isAuthenticated ? false : true
      )
      const lessons = res.parsed.listOfSteps.map((lesson: any) => {
        return parseLesson(lesson, [])
      })

      push({
        lessons,
        courseInfo: {
          ...formState,
          title: fixTitleLength(res.parsed.title),
          description: res.parsed.description,
          language: res.parsed.languageCode || formState.language || "en",
          technologies:
            res.parsed.technologies.length > 0
              ? res.parsed.technologies
              : ["education", "quizzes"],
        },
      })

      if (res.parsed.languageCode) {
        i18n.changeLanguage(res.parsed.languageCode)
      }

      navigate("/creator/syllabus")
      setFormState({
        isCompleted: false,
        currentStep: "description",
      })
      setMessages([
        {
          type: "user",
          content: formState.description,
        },
        {
          type: "assistant",
          content: res.parsed.aiMessage,
        },
        {
          type: "assistant",
          content: t("contentIndex.okMessage"),
        },
        {
          type: "assistant",
          content: t("contentIndex.instructionsMessage"),
        },
      ])
    } catch (error) {
      console.error(error, "ERROR CREATING TUTORIAL")
      toast.error("Something went wrong. Please try again.")
      setFormState({
        isCompleted: false,
        currentStep: "hasContentIndex",
      })
    }
  }

  const checkTechs = async () => {
    if (technologies.length === 0) {
      const technologies = await getTechnologies()
      console.log("TECHNOLOGIES", technologies)
      setTechnologies(technologies)
    }
  }

  const buildSteps = () => {
    const steps = [
      {
        title: t("stepWizard.description"),
        slug: "description",
        isCompleted: formState.description.length > 0,
        required: true,
        content: (
          <textarea
            required
            placeholder={t("stepWizard.descriptionPlaceholder")}
            className="w-full h-24 border-2 border-gray-300 rounded-md p-2 bg-white"
            value={formState.description}
            onChange={(e) => {
              setFormState({
                description: e.target.value,
              })
            }}
          />
        ),
      },

      {
        title: t("stepWizard.duration"),
        slug: "duration",
        isCompleted: formState.duration > 0,
        required: true,
        content: (
          <div className="flex flex-col md:flex-row gap-2">
            <SelectableCard
              title={t("stepWizard.durationCard.30")}
              // subtitle="This is a tutorial that will take 30 minutes to complete"
              onClick={() => {
                setFormState({
                  duration: 30,
                  currentStep: "purpose",
                })
              }}
              selected={formState.duration === 30}
            />
            <SelectableCard
              title={t("stepWizard.durationCard.60")}
              // subtitle="This is a tutorial that will take 1 hour to complete"
              onClick={() => {
                setFormState({
                  duration: 60,
                  currentStep: "purpose",
                })
              }}
              selected={formState.duration === 60}
            />
            <SelectableCard
              title={t("stepWizard.durationCard.120")}
              // subtitle="This is a tutorial that will take 2 hours to complete"
              onClick={() => {
                setFormState({
                  duration: 120,
                  currentStep: "purpose",
                })
              }}
              selected={formState.duration === 120}
            />
          </div>
        ),
      },
      {
        title: t("stepWizard.purpose"),
        slug: "purpose",
        isCompleted: formState?.purpose?.length > 0,
        required: true,
        content: (
          <PurposeSelector
            onFinish={(purpose) => {
              setFormState({
                purpose: purpose,
                currentStep: "verifyHuman",
              })
            }}
          />
        ),
      },
      {
        title: t("stepWizard.verifyHuman"),
        slug: "verifyHuman",
        isCompleted: false,
        required: true,
        content: (
          <TurnstileChallenge
            siteKey={
              DEV_MODE ? "0x4AAAAAABeKMBYYinMU4Ib0" : "0x4AAAAAABeZ9tjEevGBsJFU"
            }
            onSuccess={async (token) => {
              const { human, message, token: jwtToken } = await isHuman(token)
              if (human) {
                toast.success(t("stepWizard.humanSuccess"))

                console.log("JWT TOKEN received", jwtToken)
                setAuth({
                  ...auth,
                  publicToken: jwtToken,
                })
                setFormState({
                  currentStep: "hasContentIndex",
                })
              } else {
                toast.error(message)
                setFormState({
                  currentStep: "purpose",
                })
              }
            }}
          />
        ),
      },
      {
        title: t("stepWizard.hasContentIndex"),
        slug: "hasContentIndex",
        isCompleted: false,
        content: (
          <>
            <div className="flex flex-col md:flex-row gap-2 justify-center">
              <SelectableCard
                title={t("stepWizard.hasContentIndexCard.no")}
                onClick={() => {
                  setFormState({
                    hasContentIndex: false,
                    variables: [
                      ...formState.variables.filter(
                        (v) => v !== "contentIndex"
                      ),
                    ],
                    isCompleted: true,
                  })
                }}
                // selected={formState.hasContentIndex === false}
              />
              <SelectableCard
                title={t("stepWizard.hasContentIndexCard.yes")}
                onClick={() => {
                  setFormState({
                    hasContentIndex: true,
                    currentStep: "contentIndex",
                    variables: [...formState.variables, "contentIndex"],
                  })
                }}
                // selected={formState.hasContentIndex === true}
              />
            </div>
          </>
        ),
      },
      {
        title: t("stepWizard.contentIndex"),
        slug: "contentIndex",
        helpText: t("stepWizard.contentIndexHelpText"),
        isCompleted:
          formState.contentIndex.length > 0 || uploadedFiles.length > 0,
        required: true,
        content: (
          <Uploader
            onFinish={(text) => {
              setFormState({
                contentIndex: text,
                isCompleted: true,
              })
            }}
          />
        ),
      },
    ]

    return steps.filter(
      (step) =>
        formState.variables.includes(step.slug) ||
        step.slug === formState.currentStep
    )
  }

  return (
    <>
      <ParamsChecker />
      {formState.isCompleted && history.length === 0 ? (
        <Loader
          text={t("loader.text")}
          icon={<img src={RIGO_FLOAT_GIF} alt="rigo" className="w-20 h-20" />}
        />
      ) : (
        <>
          {/* {formState.language && (
            <div className="flex flex-col items-center justify-center">
              <p>
                <span className="font-bold">Language:</span>{" "}
                {formState.language}
              </p>
              <p>
                <span className="font-bold">Technologies:</span>{" "}
                {formState.technologies?.join(", ")}
              </p>
            </div>
          )} */}
          {history.length > 0 && (
            <ResumeCourseModal
              onContinue={() => {
                navigate("/creator/syllabus")
              }}
              onStartOver={() => {
                resetFormState()
                cleanAll()
                cleanHistory()
              }}
            />
          )}
          <StepWizard
            hideLastButton={true}
            formState={formState}
            steps={buildSteps()}
            setFormState={setFormState}
            onFinish={() => {
              setFormState({
                isCompleted: true,
              })
            }}
          />
        </>
      )}
    </>
  )
}

export default App
