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

export default function Lectures() {
  const { topicId } = useParams()
  const [lectures, setLectures] = useState([])

  const [title, setTitle] = useState("")
  const [contentType, setContentType] = useState("RECORDED")
  const [contentUrl, setContentUrl] = useState("")

  const [editingLectureId, setEditingLectureId] = useState(null)
  const [editTitle, setEditTitle] = useState("")
  const [editContentUrl, setEditContentUrl] = useState("")

  useEffect(() => {
    fetchLectures()
  }, [topicId])

  const fetchLectures = () => {
    console.log("FETCH LECTURES CALLED", topicId)

    api
      .get(`/lectures/topic/${topicId}`)
      .then(res => {
        console.log("LECTURES RESPONSE:", res.data)
        setLectures(res.data)
      })
      .catch(err => console.error("LECTURES FETCH ERROR:", err))
  }

  const addLecture = () => {
    if (!title.trim() ){
      alert("Lecture title is required")
      return
    }

    api
    .post("/lectures", {
      title: title.trim(),
      topic: topicId,
      contentType,
      contentUrl,
      order: lectures.length + 1,
      isFreePreview: true
    })
    .then(() => {
      setTitle("")
      setContentUrl("")
      fetchLectures()
    })
    .catch(err => {
      console.error("ADD LECTURE ERROR:", err)
    })
  }

  const startEdit = (lecture) => {
  setEditingLectureId(lecture._id)
  setEditTitle(lecture.title)
  setEditContentUrl(lecture.contentUrl)
}

const saveEdit = (lectureId) => {
  const confirmEdit = window.confirm(
    "Do you really want to save changes to this lecture?"
  )

  if (!confirmEdit)return

  api
    .put(`/lectures/${lectureId}`, {
      title: editTitle,
      contentUrl: editContentUrl
    })
    .then(() => {
      setEditingLectureId(null)
      fetchLectures()
    })
    .catch(err => console.error("EDIT LECTURE ERROR:", err))
}

const cancelEdit = () => {
  setEditingLectureId(null)
  setEditTitle("")
  setEditContentUrl("")
}

  const deleteLecture = (lectureId) => {
    const confirmDelete = window.confirm(
      "Do you really want to delete this lecture?"
    )
    if (!confirmDelete) return
    api
      .delete(`/lectures/${lectureId}`)
      .then(() => fetchLectures())
      .catch(err => console.error("DELETE LECTURE ERROR:", err))
  }

  return (
    <div>
      <h3>Lectures</h3>

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

      <select
        value={contentType}
        onChange={e => setContentType(e.target.value)}
      >
        <option value="RECORDED">Recorded Video</option>
        <option value="LIVE">Live Class</option>
        <option value="PDF">PDF</option>
      </select>

      <input
        placeholder="Content URL"
        value={contentUrl}
        onChange={e => setContentUrl(e.target.value)}
      />

      <button onClick={addLecture} disabled={!title.trim()}>
        Add Lecture
      </button>

      <hr />

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

      {lectures.map(lecture => (
  <div key={lecture._id} style={{ marginBottom: "1rem" }}>

    {editingLectureId === lecture._id ? (
      <>
        <input
          value={editTitle}
          onChange={e => setEditTitle(e.target.value)}
          placeholder="Lecture title"
        />

        <input
          value={editContentUrl}
          onChange={e => setEditContentUrl(e.target.value)}
          placeholder="Content URL"
        />

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

        <button onClick={() => setEditingLectureId(null)}>
          Cancel
        </button>
      </>
    ) : (
      <>
        <span>
          {lecture.title} ({lecture.contentType})
        </span>

        {lecture.contentType === "LIVE" && (
          <button onClick={() => window.open(lecture.contentUrl, "_blank")}>
            Go Live
          </button>
        )}

        <button onClick={() => startEdit(lecture)}>
          Edit
        </button>

        <button onClick={() => deleteLecture(lecture._id)}>
          Delete
        </button>
      </>
    )}

  </div>
))}

    </div>
  )
}
