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, loginWithToken, parseLesson } from "./utils/lib"

import { Uploader } from "./components/Uploader"
import toast from "react-hot-toast"
import { ParamsChecker } from "./components/ParamsChecker"
import { 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"

function App() {
  const navigate = useNavigate()

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

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

  useEffect(() => {
    verifyToken()
    checkDescription()
  }, [])

  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 checkDescription = () => {
    const { description, duration, plan, purpose } = checkParams([
      "description",
      "duration",
      "plan",
      "purpose",
    ])
    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 (purpose && purpose.length > 0 && possiblePurposes.includes(purpose)) {
      setFormState({
        purpose: purpose,
        currentStep: "hasContentIndex",
      })
    }
  }

  const handleCreateTutorial = async () => {
    try {
      cleanHistory()

      const res = await publicInteractiveCreation(
        {
          courseInfo: `${JSON.stringify(formState)}         `,
          prevInteractions: "",
        },
        auth.publicToken,
        formState.purpose
      )
      const lessons = res.parsed.listOfSteps.map((lesson: any) => {
        return parseLesson(lesson, [])
      })

      console.log("RES FROM RIGO", res)
      push({
        lessons,
        courseInfo: {
          ...formState,
          title: res.parsed.title,
          description: res.parsed.description,
        },
        messages: [
          {
            type: "assistant",
            content: res.parsed.aiMessage,
          },
        ],
        // sources: uploadedFiles,
      })
      navigate("/creator/syllabus")
      setFormState({
        isCompleted: false,
        currentStep: "description",
      })
    } catch (error) {
      console.error(error, "ERROR CREATING TUTORIAL")
      toast.error("Something went wrong. Please try again.")
      setFormState({
        isCompleted: false,
        currentStep: "hasContentIndex",
      })
    }
  }

  const buildSteps = () => {
    const steps = [
      {
        title: "What do you want to learn?",
        slug: "description",
        isCompleted: formState.description.length > 0,
        required: true,
        content: (
          <textarea
            required
            placeholder="Describe your course"
            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: "What is the estimated duration for this tutorial?",
        slug: "duration",
        isCompleted: formState.duration > 0,
        required: true,
        content: (
          <div className="flex flex-col md:flex-row gap-2">
            <SelectableCard
              title="Around 30 minutes"
              // subtitle="This is a tutorial that will take 30 minutes to complete"
              onClick={() => {
                setFormState({
                  duration: 30,
                  currentStep: "purpose",
                })
              }}
              selected={formState.duration === 30}
            />
            <SelectableCard
              title="Around 1 hour"
              // subtitle="This is a tutorial that will take 1 hour to complete"
              onClick={() => {
                setFormState({
                  duration: 60,
                  currentStep: "purpose",
                })
              }}
              selected={formState.duration === 60}
            />
            <SelectableCard
              title="Around 2 hours"
              // subtitle="This is a tutorial that will take 2 hours to complete"
              onClick={() => {
                setFormState({
                  duration: 120,
                  currentStep: "purpose",
                })
              }}
              selected={formState.duration === 120}
            />
          </div>
        ),
      },
      {
        title: "How would you like to use learnpack?",
        slug: "purpose",
        isCompleted: formState?.purpose?.length > 0,
        required: true,
        content: (
          <PurposeSelector
            onFinish={(purpose) => {
              setFormState({
                purpose: purpose,
                currentStep: "verifyHuman",
              })
            }}
          />
        ),
      },
      {
        title: "Please verify you are a human",
        slug: "verifyHuman",
        isCompleted: false,
        content: (
          <TurnstileChallenge
            // siteKey={"0x4AAAAAABeKMBYYinMU4Ib0"}
            siteKey={"0x4AAAAAABeZ9tjEevGBsJFU"} // This is the learnpack one
            onSuccess={async (token) => {
              const { human, message, token: jwtToken } = await isHuman(token)
              if (human) {
                toast.success("You are a human! 👌🏻")

                console.log("JWT TOKEN received", jwtToken)
                setAuth({
                  ...auth,
                  publicToken: jwtToken,
                })
                setFormState({
                  currentStep: "hasContentIndex",
                })
              } else {
                toast.error(message)
                setFormState({
                  currentStep: "purpose",
                })
              }
            }}
          />
        ),
      },
      {
        title: "Any materials to get this course started?",
        slug: "hasContentIndex",
        isCompleted: false,
        content: (
          <>
            <div className="flex flex-col md:flex-row gap-2 justify-center">
              <SelectableCard
                title="❌ No, help me create one"
                onClick={() => {
                  setFormState({
                    hasContentIndex: false,
                    variables: [
                      ...formState.variables.filter(
                        (v) => v !== "contentIndex"
                      ),
                    ],
                    isCompleted: true,
                  })
                }}
                selected={formState.hasContentIndex === false}
              />
              <SelectableCard
                title="✅ Yes"
                onClick={() => {
                  setFormState({
                    hasContentIndex: true,
                    currentStep: "contentIndex",
                    variables: [...formState.variables, "contentIndex"],
                  })
                }}
                selected={formState.hasContentIndex === true}
              />
            </div>
          </>
        ),
      },
      {
        title: "Any materials to get this course started?",
        slug: "contentIndex",
        helpText:
          "It could be just text, paste an URL or even upload a document.",
        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="Learnpack is setting up your tutorial. It may take a moment..."
          icon={<img src={RIGO_FLOAT_GIF} alt="rigo" className="w-20 h-20" />}
        />
      ) : (
        <>
          {history.length > 0 && (
            <ResumeCourseModal
              onContinue={() => {
                navigate("/creator/syllabus")
              }}
              onStartOver={() => {
                resetFormState()
                cleanHistory()
              }}
            />
          )}
          <StepWizard
            hideLastButton={true}
            formState={formState}
            steps={buildSteps()}
            setFormState={setFormState}
            onFinish={() => {
              setFormState({
                isCompleted: true,
              })
            }}
          />
        </>
      )}
    </>
  )
}

export default App
