import React, { useState, useEffect } from "react"
import { useShallow } from "zustand/react/shallow"
import useStore from "../../utils/store"
import { publicInteractiveCreation } from "../../utils/rigo"
import {
  parseLesson,
  // useConsumableCall,
  validateTokens,
  checkParams,
  loginWithToken,
  createCourse,
  isSlugAvailable,
  reWriteTitle,
} from "../../utils/lib"

import Loader from "../Loader"
import { TMessage } from "../Message"
import { Lesson } from "../LessonItem"
import { ConsumablesManager } from "../ConsumablesManager"
import toast from "react-hot-toast"
import { ContentIndex } from "./ContentIndex"
import { Sidebar } from "./Sidebar"
import Login from "../Login"
import { useNavigate } from "react-router"
import { ParamsChecker } from "../ParamsChecker"
import { slugify } from "../../utils/creatorUtils"
import { RIGO_FLOAT_GIF } from "../../utils/constants"

const SyllabusEditor: React.FC = () => {
  const navigate = useNavigate()

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

  const [messages, setMessages] = useState<TMessage[]>([
    {
      type: "assistant",
      content: "If you're satisfied, type 'OK' in the chat.",
    },
    {
      type: "assistant",
      content:
        "If not, what would you like me to change? You can sat things like:\n  - Add more exercises\n   - Make it more difficult\n   - Remove step 1.1 and replace it with a new step that explains the concept of X ",
    },
  ])
  const [isGenerating, setIsGenerating] = useState(false)
  const [showLoginModal, setShowLoginModal] = useState(false)
  const [isThinking, setIsThinking] = useState(false)

  const syllabus = history[history.length - 1]

  useEffect(() => {
    if (!syllabus) {
      navigate("/creator", { replace: true })
    }
  }, [syllabus, navigate])

  useEffect(() => {
    console.log(formState.description, "DESCRIPTION")

    if (formState.description) {
      setMessages((prevMessages) => {
        if (prevMessages.length === 0 || prevMessages[0].type !== "user") {
          // Si no hay mensajes o el primero no es de usuario, lo agrego al inicio
          return [
            { type: "user", content: formState.description },
            ...prevMessages,
          ]
        } else {
          // Si el primero ya es de usuario, lo reemplazo y mantengo el resto
          const [, ...rest] = prevMessages
          return [{ type: "user", content: formState.description }, ...rest]
        }
      })
    }
  }, [formState.description])

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

  const checkSlug = async () => {
    const slug = slugify(syllabus.courseInfo.title || "")
    const isAvailable = await isSlugAvailable(slug)
    if (!isAvailable) {
      const newTitle = await reWriteTitle(
        syllabus.courseInfo.title || "",
        auth.rigoToken
      )
      push({
        ...syllabus,
        courseInfo: {
          ...syllabus.courseInfo,
          title: newTitle,
        },
      })
    }
  }

  const sendPrompt = async (prompt: string) => {
    setIsThinking(true)

    setMessages([
      ...messages,
      { type: "user", content: prompt },
      { type: "assistant", content: "" },
    ])

    const res = await publicInteractiveCreation(
      {
        courseInfo: JSON.stringify(syllabus.courseInfo),
        prevInteractions:
          messages
            .map((message) => `${message.type}: ${message.content}`)
            .join("\n") + `\nUSER: ${prompt}`,
      },
      auth.publicToken,
      syllabus.courseInfo.purpose
    )

    const lessons: Lesson[] = res.parsed.listOfSteps.map((step: any) =>
      parseLesson(step, syllabus.lessons)
    )
    push({
      ...syllabus,
      lessons: lessons,
      courseInfo: {
        ...syllabus.courseInfo,
        title: res.parsed.title || syllabus.courseInfo.title,
        description: res.parsed.description || syllabus.courseInfo.description,
      },
    })
    setMessages((prev) => {
      const newMessages = [...prev]
      newMessages[newMessages.length - 1].content = res.parsed.aiMessage
      return newMessages
    })
    setIsThinking(false)
  }

  const handleSubmit = async () => {
    if (!auth.bcToken || !auth.rigoToken) {
      setShowLoginModal(true)
      return
    }

    if (!syllabus.courseInfo.title) {
      toast.error("Please provide a title for the course")
      return
    }

    let tokenToUse = auth.rigoToken
    const onValidRigoToken = (rigotoken: string) => {
      setAuth({
        ...auth,
        rigoToken: rigotoken,
      })
      tokenToUse = rigotoken
    }
    const isValid = await validateTokens(auth.bcToken, onValidRigoToken)
    if (!isValid) {
      setShowLoginModal(true)
      return
    }
    // const success = await useConsumableCall(
    //   auth.bcToken,
    //   "ai-course-generation"
    // )
    // if (!success) {
    //   toast.error("You don't have enough credits to generate a course!")
    //   return
    // }
    // syllabus.sources = uploadedFiles
    console.log(syllabus)

    setIsGenerating(true)
    createCourse(syllabus, tokenToUse, auth.bcToken)

    setTimeout(() => {
      cleanHistory()
      setIsGenerating(false)
      window.location.href = `/preview/${slugify(
        syllabus.courseInfo.title || ""
      )}?token=${auth.bcToken}`
    }, 3000)
  }

  if (!syllabus) return null

  return isGenerating ? (
    <>
      <Loader
        listeningTo="course-generation"
        icon={<img src={RIGO_FLOAT_GIF} alt="rigo" className="w-20 h-20" />}
        initialBuffer="🚀 Starting course generation..."
        text="Learnpack is setting up your tutorial.
It may take a moment..."
      />
    </>
  ) : (
    <div className="flex w-full bg-white rounded-md shadow-md overflow-hidden h-screen ">
      <ParamsChecker />
      {showLoginModal && (
        <Login
          onFinish={() => {
            setShowLoginModal(false)
          }}
        />
      )}

      <ConsumablesManager />

      <Sidebar
        messages={messages}
        sendPrompt={sendPrompt}
        handleSubmit={handleSubmit}
      />

      <ContentIndex
        handleSubmit={handleSubmit}
        messages={messages}
        isThinking={isThinking}
        openLogin={() => {
          setShowLoginModal(true)
        }}
      />
    </div>
  )
}

export default SyllabusEditor
