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

export default function Topics() {
  const { chapterId } = useParams()
  const navigate = useNavigate()

  const [topics, setTopics] = useState([])
  const [title, setTitle] = useState("")

  useEffect(() => {
    fetchTopics()
  }, [chapterId])

  const fetchTopics = () => {
    api
      .get(`/topics/${chapterId}`)
      .then(res => setTopics(res.data))
      .catch(err => console.error(err))
  }

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

    api
      .post("/topics", {
        title: title.trim(),
        chapterId,
        order: topics.length + 1
      })
      .then(() => {
        setTitle("")
        fetchTopics()
      })
      .catch(err => console.error(err))
  }

  const deleteTopic = (id) => {
    if (!window.confirm("Delete this topic?")) return

    api
      .delete(`/topics/${id}`)
      .then(fetchTopics)
      .catch(err => console.error(err))
  }

  return (
    <div>
      <h3>Topics</h3>

      <input
        placeholder="Topic title"
        value={title}
        onChange={e => setTitle(e.target.value)}
      />

      <button onClick={addTopic}>
        Add Topic
      </button>

      <hr />

      {topics.map(topic => (
        <div key={topic._id}>

          <span>{topic.title}</span>

          <button onClick={() => navigate(`/admin/topics/${topic._id}/lectures`)}>
            Manage Lectures
          </button>

          <button onClick={() => deleteTopic(topic._id)}>
            Delete
          </button>
        </div>
      ))}
    </div>
  )
}