import { useEffect, useState } from "react"
import { useParams, useNavigate } from "react-router-dom"
import api from "../../services/api"

export default function Chapters() {
  const { courseId } = useParams()
  const navigate = useNavigate()

  const [chapters, setChapters] = useState([])
  const [title, setTitle] = useState("")

  const [editingChapterId, setEditingChapterId] = useState(null)
  const [editTitle, setEditTitle] = useState("")

  useEffect(() => {
    fetchChapters()
  }, [courseId])

  const fetchChapters = () => {
    api.get(`/courses/${courseId}/chapters`)
      .then(res => {
        setChapters(res.data)
      })
      .catch(err => {
        console.error("CHAPTERS ERROR:", err)
      })
  }

  const addChapter = () => {
    if (!title.trim()) return

    api.post(`/courses/${courseId}/chapters`, {
      title,
      courseId,
      order: chapters.length + 1
    }).then(() => {
      setTitle("")
      fetchChapters()
    })
  }

  const startEdit = (chapter) => {
  setEditingChapterId(chapter._id)
  setEditTitle(chapter.title)
  }

  const cancelEdit = () => {
  setEditingChapterId(null)
  setEditTitle("")
  }

  const saveEdit = (chapterId) => {
  api
    .put(`/chapters/${chapterId}`, {
      title: editTitle
    })
    .then(() => {
      setEditingChapterId(null)
      fetchChapters()
    })
    .catch(err => console.error("EDIT CHAPTER ERROR:", err))
}

  return (
    <div>
      <h3>Chapters</h3>

      <div>
        <input
          placeholder="Chapter title"
          value={title}
          onChange={e => setTitle(e.target.value)}
        />
        <button onClick={addChapter}>Add Chapter</button>
      </div>

      <hr />

      {chapters.length === 0 && <p>No chapters created yet</p>}

      {chapters.map(chapter => (
        <div key={chapter._id}>
          
          {editingChapterId === chapter._id? (
            <>
            <input value={editTitle}
            onChange={e => setEditTitle(e.target.value)}
            />

            <button onClick={() => saveEdit(chapter._id)}>
              Save
            </button>

            <button onClick={() => setEditingChapterId(null)}>
              Cancel
            </button>
            </>
          ):(
            <>
            <span>{chapter.title}</span>

            <button onClick={() => {
              setEditingChapterId(chapter._id)
              setEditTitle(chapter.title)
            }}>
              Edit
            </button>

            <button onClick={() => navigate(`/admin/chapters/${chapter._id}/topics`)}>
              Topics
            </button>
            </>
          )}
        </div>
      ))}
    </div>
  )
}
