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 { interactiveCreation, 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_GIT } from "./utils/constants"
import TurnstileChallenge from "./components/TurnstileChallenge"
// import TurnstileChallenge from "./components/TurnstileChallenge"

function App() {
  const navigate = useNavigate()

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

  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,
      })
    }
  }

  const checkDescription = () => {
    const { description, duration, plan } = checkParams([
      "description",
      "duration",
      "plan",
    ])
    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")
    }
  }

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

      const res = await interactiveCreation({
        courseInfo: `${JSON.stringify(formState)}         
${
  uploadedFiles.length > 0
    ? `These files where uploaded by the user: \n\n${JSON.stringify(
        uploadedFiles
      )}`
    : ""
}`,
        prevInteractions: "",
      })
      const lessons = res.parsed.listOfSteps.map((lesson: any) => {
        return parseLesson(lesson, [])
      })

      push({
        lessons,
        courseInfo: {
          ...formState,
          title: res.parsed.title,
          description: res.parsed.description,
        },
        sources: uploadedFiles,
      })
      navigate("/creator/syllabus")
      setFormState({
        description: "",
        duration: 0,
        targetAudience: "",
        hasContentIndex: false,
        contentIndex: "",
        isCompleted: false,
        currentStep: "description",
        variables: [
          "description",
          "duration",
          "hasContentIndex",
          "verifyHuman",
        ],
      })
    } catch (error) {
      console.error(error)
      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: "hasContentIndex",
                })
              }}
              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: "hasContentIndex",
                })
              }}
              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: "hasContentIndex",
                })
              }}
              selected={formState.duration === 120}
            />
          </div>
        ),
      },
      {
        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,
                    currentStep: "verifyHuman",
                    variables: [
                      ...formState.variables.filter(
                        (v) => v !== "contentIndex"
                      ),
                    ],
                    // isCompleted: true,
                  })
                }}
                selected={false}
              />
              <SelectableCard
                title="✅ Yes"
                onClick={() => {
                  setFormState({
                    hasContentIndex: true,
                    currentStep: "contentIndex",
                    variables: [...formState.variables, "contentIndex"],
                  })
                }}
                selected={false}
              />
            </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,
                currentStep: "verifyHuman",
                // isCompleted: true,
              })
            }}
          />
        ),
      },
      {
        title: "Please verify you are a human",
        slug: "verifyHuman",
        isCompleted: false,
        content: (
          <TurnstileChallenge
            siteKey={"0x4AAAAAABeZ9tjEevGBsJFU"}
            onSuccess={async (token) => {
              const _isHuman = await isHuman(token)
              if (_isHuman) {
                toast.success("You are a human! 👌🏻")
                setFormState({ isCompleted: true })
              } else {
                toast.error("You are not a human! 🤖")
                setFormState({
                  currentStep: "hasContentIndex",
                })
              }
            }}
          />
        ),
      },
    ]

    console.log(formState.variables, "FORM STATE VAIRABLEs")

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

  return (
    <>
      <ParamsChecker />
      {formState.isCompleted ? (
        <Loader
          text="Learnpack is setting up your tutorial. It may take a moment..."
          icon={<img src={RIGO_FLOAT_GIT} alt="rigo" className="w-20 h-20" />}
        />
      ) : (
        <StepWizard
          formState={formState}
          steps={buildSteps()}
          setFormState={setFormState}
          onFinish={() => {
            setFormState({
              isCompleted: true,
            })
          }}
        />
      )}
    </>
  )
}

export default App
