import { useEffect, useState, useRef } from "react"
import useStore, { Syllabus } from "../../utils/store"
import { Lesson, LessonItem } from "../LessonItem"
import { SVGS } from "../../assets/svgs"
import { TMessage } from "../Message"
import Loader from "../Loader"
import { motion, AnimatePresence } from "framer-motion"
// import { randomUUID } from "../../utils/creatorUtils"
import toast from "react-hot-toast"
import { randomUUID } from "../../utils/creatorUtils"

const ContentIndexHeader = ({
  messages,
  syllabus,
}: {
  messages: TMessage[]
  syllabus: Syllabus
}) => {
  const isFirst =
    messages.filter((m) => m.type === "assistant" && m.content.length > 0)
      .length === 2

  const headerText = isFirst
    ? `I've created a detailed structure for your course: ${syllabus.courseInfo.title}`
    : "I've updated the structure based on your feedback."

  return (
    <div className="mt-2 ">
      <AnimatePresence mode="wait">
        <motion.h2
          key={headerText}
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: 10 }}
          transition={{ duration: 0.2 }}
          className="text-lg font-semibold sm:text-lg md:text-xl  xl:text-2xl"
        >
          {headerText}
        </motion.h2>
      </AnimatePresence>
    </div>
  )
}
const ContentSecondaryHeader = ({
  messages,
}: // syllabus,
{
  messages: TMessage[]
}) => {
  const isFirst =
    messages.filter((m) => m.type === "assistant" && m.content.length > 0)
      .length === 2

  const subText = isFirst
    ? `It includes a mix of reading, coding exercises, and quizzes. Give
       it a look and let me know if it aligns with your expectations or if
       there are any changes you'd like to make.`
    : "Based on your input, here is the new syllabus, updates are highlighted in yellow"

  return (
    <AnimatePresence mode="wait">
      <motion.p
        key={subText}
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        transition={{ duration: 0.2, delay: 0.1 }}
        className="text-sm sm:text-md md:text-lg text-gray-600 mb-5"
      >
        {subText}
      </motion.p>
    </AnimatePresence>
  )
}

export const GenerateButton = ({
  handleSubmit,
  openLogin,
}: {
  handleSubmit: () => void
  openLogin: () => void
}) => {
  const history = useStore((state) => state.history)
  const undo = useStore((state) => state.undo)
  const auth = useStore((state) => state.auth)
  const setAuth = useStore((state) => state.setAuth)
  const prev = history[history.length - 2]
  return (
    <div>
      <div className="flex flex-col space-y-2 sm:flex-row sm:space-y-0 sm:space-x-4 justify-end mt-6">
        {prev && prev.lessons.length > 0 && (
          <button
            onClick={() => {
              undo()
              toast.success("Changes reverted!")
            }}
            className="w-full sm:w-auto text-gray-500 bg-gray-200 rounded px-4 py-2 hover:bg-gray-300 flex items-center justify-center gap-2 cursor-pointer"
          >
            {SVGS.undo}
            Revert changes
          </button>
        )}

        <button
          onClick={handleSubmit}
          className="w-full sm:w-auto bg-blue-600 text-white rounded px-4 py-2 hover:bg-blue-700 flex items-center justify-center gap-2 cursor-pointer"
        >
          <span>I'm ready. Create the course for me!</span>
          {SVGS.rigoSoftBlue}
        </button>
      </div>
      <div className="mt-2 justify-end flex">
        {auth.user && (
          <div
            // onClick={handleSubmit}
            className="text-sm text-gray-500 rounded px-4 py-2 flex items-center justify-center gap-1 "
          >
            <span>
              Creating the course as <strong>{auth.user.first_name}</strong> or
            </span>
            <button
              className="text-sm rounded   items-center justify-center cursor-pointer text-blue-600"
              onClick={() => {
                setAuth({
                  rigoToken: "",
                  bcToken: "",
                  userId: "",
                  user: null,
                  publicToken: "",
                })
                openLogin()
              }}
            >
              login as someone else
            </button>
          </div>
        )}
      </div>
    </div>
  )
}

export const ContentIndex = ({
  handleSubmit,
  messages,
  isThinking,
  openLogin,
}: {
  handleSubmit: () => void
  messages: TMessage[]
  isThinking: boolean
  openLogin: () => void
}) => {
  const history = useStore((state) => state.history)
  const push = useStore((state) => state.push)
  const mode = useStore((state) => state.mode)
  const containerRef = useRef<HTMLDivElement>(null)
  const [showScrollHint, setShowScrollHint] = useState(false)

  const syllabus = history[history.length - 1]

  const previousSyllabus = history[history.length - 2] || null

  const handleRemove = (lesson: Lesson) => {
    push({
      ...syllabus,
      lessons: syllabus.lessons.filter((l) => l.uid !== lesson.uid),
    })
  }

  const handleChange = (uid: string, newTitle: string) => {
    push({
      ...syllabus,
      lessons: syllabus.lessons.map((lesson) =>
        lesson.uid === uid ? { ...lesson, title: newTitle } : lesson
      ),
    })
  }

  const addLessonAfter = (index: number, id: string) => {
    const newLesson: Lesson = {
      id: (parseFloat(id) + 0.1).toFixed(1),
      title: "Hello World",
      uid: randomUUID(),
      type: "READ",
      duration: 2,
      description: "Hello World",
    }
    const updated = [...syllabus.lessons]
    updated.splice(index + 1, 0, newLesson)
    push({
      ...syllabus,
      lessons: updated,
    })
  }

  useEffect(() => {
    const container = containerRef.current

    const checkScroll = () => {
      if (container) {
        const nearBottom =
          container.scrollHeight >
          container.clientHeight + container.scrollTop + 100

        setShowScrollHint(nearBottom)
      }
    }

    checkScroll()
    container?.addEventListener("scroll", checkScroll)
    return () => container?.removeEventListener("scroll", checkScroll)
  }, [syllabus.lessons])

  const scrollToBottom = (target: "bottom" | "continue") => {
    if (target === "continue") {
      const container = containerRef.current
      if (container) {
        const scrollStep = container.clientHeight * 0.8
        container.scrollBy({ top: scrollStep, behavior: "smooth" })
      }
    } else {
      const container = containerRef.current
      if (container) {
        container.scrollTo({ top: container.scrollHeight, behavior: "smooth" })
      }
    }
  }

  return (
    <div className="relative w-full p-2 sm:p-4 md:p-6 lg:p-8 space-y-6">
      <ContentIndexHeader messages={messages} syllabus={syllabus} />
      <div
        ref={containerRef}
        className="space-y-3 overflow-y-auto max-h-[78vh] pr-2 scrollbar-hide relative pb-20"
      >
        {isThinking ? (
          <Loader text="Thinking..." minheight="min-h-[69vh]" />
        ) : (
          <>
            <ContentSecondaryHeader messages={messages} />
            {syllabus.lessons.map((lesson, index) => (
              <div key={lesson.uid + index}>
                <LessonItem
                  key={lesson.uid}
                  lesson={lesson}
                  onChange={handleChange}
                  onRemove={() => handleRemove(lesson)}
                  isNew={Boolean(
                    previousSyllabus &&
                      previousSyllabus &&
                      previousSyllabus.lessons &&
                      previousSyllabus.lessons.length > 0 &&
                      !previousSyllabus.lessons.some(
                        (l) => l.uid === lesson.uid
                      )
                  )}
                />
                {mode === "teacher" && (
                  <div className="relative h-6">
                    <div className="absolute left-1/2 -translate-x-1/2 -top-3">
                      <button
                        onClick={() => addLessonAfter(index, lesson.id)}
                        className="w-6 h-6 flex items-center justify-center bg-blue-100 text-blue-600 rounded hover:bg-blue-200 shadow-sm text-sm font-semibold cursor-pointer"
                      >
                        +
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ))}
            {syllabus.lessons.length > 0 && (
              <GenerateButton
                handleSubmit={handleSubmit}
                openLogin={openLogin}
              />
            )}
          </>
        )}
      </div>

      {showScrollHint && !isThinking && (
        <div className="pointer-events-none relative">
          <div className="absolute bottom-0 left-0 w-full h-60 bg-gradient-to-t from-white to-transparent z-10" />
          <div className="absolute bottom-10 left-0 w-full flex justify-center z-31">
            <button
              style={{ color: "#0084FF" }}
              onClick={() => scrollToBottom("bottom")}
              className="px-4 py-1 bg-white  text-sm rounded  hover:bg-blue-50 cursor-pointer pointer-events-auto font-bold flex items-center gap-2 "
            >
              Continue scrolling
              {SVGS.downArrow}
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
