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

const truncate = (text, limit = 80) => {
  if (!text) return "-"
  return text.length > limit ? text.slice(0, limit) + "..." : text
}

export default function Courses() {
  const classMap = {
  "Class 9": "69832042fb89f5a43daeb364",
  "Class 10": "69832050fb89f5a43daeb366",
  "Class 11": "694fb288e971b4b480fd25d2",
  "Class 12": "698313c359f634c957f5119c"
}

  const [showAddModal, setShowAddModal] = useState(false)
  const [newCourseName, setNewCourseName] = useState("")
  const [courses, setCourses] = useState([])
  const [selectedClass, setSelectedClass] = useState("Class 9")
  const [newCourseClass, setNewCourseClass] = useState(selectedClass)
  const [newCourseDescription, setNewCourseDescription] = useState("")
  const [selectedImage, setSelectedImage] = useState(null)
  const [newCoursePrice, setNewCoursePrice] = useState("")
  const [dropdownPos, setDropdownPos] = useState({ top: 0, left: 0 })
  const [newCourse, setNewCourse] = useState({
    name: "",
    class: selectedClass,
    description: "",
    price: 0,
    subject: ""
  })
  const [subjects, setSubjects] = useState([])
  const [selectedSubject, setSelectedSubject] = useState("")
  const [openActionCourseId, setOpenActionCourseId] = useState(null)

  const [editingCourseId, setEditingCourseId] = useState(null)
  const [editCourseName, setEditCourseName] = useState("")
  const [editCourseDescription, setEditCourseDescription] = useState("")
  const [editThumbnail, setEditThumbnail] = useState(null)

  const navigate = useNavigate()

  const fetchCourses = async () => {
    try{
      let url = "/courses"

      if (selectedClass !== "All"){
        url += `?class=${selectedClass}`
      }

      const res = await api.get(url)
      setCourses(res.data)

    }  catch (err) {
      console.error(err)
    }
  }

  const fetchSubjects = async () => {
    try{
      const classId = classMap[newCourseClass]
      if (!classId) return

      const res = await api.get(`/subjects/${classId}`)
      console.log("Subjects from API:", res.data)
      setSubjects(res.data)
    } catch(err){
      console.error("Subjects fetch error:", err)
    }
  }

  const handleChange = (e) => {
    const {name, value} = e.target
    setNewCourse(prev => ({
      ...prev,
      [name]: value
    }))
  }

  useEffect(() => {
    console.log("Selected class:", selectedClass)
    fetchCourses()
    fetchSubjects()
    setNewCourseClass(selectedClass)
  }, [selectedClass])

  useEffect(() => {
    fetchSubjects()
  }, [newCourseClass])

  const startEdit = (course) => {
    setEditingCourseId(course._id)
    setEditCourseName(course.name)
    setEditCourseDescription(course.description || "")
    setOpenActionCourseId(null)
  }

  const saveEdit = async (id) => {
    try{
      const form = new FormData()
      form.append("name", editCourseName)
      form.append("description", editCourseDescription)

      if (editThumbnail){
        form.append("thumbnail", editThumbnail)
      }

      await api.patch(`/courses/${id}`, form)

      setEditingCourseId(null)
      setEditThumbnail(null)
      fetchCourses()
    }catch(err){
      console.log("EDIT ERROR:", err)
    }
  }

  const togglePaid = (id) =>
    api.patch(`/courses/${id}/toggle-paid`)
      .then(fetchCourses)
      .catch(err => console.error(err))

  const toggleFreeze = (id) =>
    api.patch(`/courses/${id}/toggle-freeze`)
      .then(fetchCourses)
      .catch(err => console.error(err))

  const toggleContentLock = (id) =>
    api.patch(`/courses/${id}/toggle-content-lock`)
      .then(fetchCourses)
      .catch(err => console.error(err))

  const toggleArchive = (id) =>
    api.patch(`/courses/${id}/archive`)    
       .then(fetchCourses)
       .catch(err => console.error(err))

  const createCourse = async () => {
    try{
      if(!newCourseName || !selectedSubject){
        alert("Course name & subject required")
        return
      }

      const form = new FormData()

      form.append("name", newCourseName)
      form.append("slug", newCourseName.toLowerCase(). replace(/\s+/g,"-"))
      form.append("class", newCourseClass)
      form.append("description", newCourseDescription)
      form.append("price", Number(newCoursePrice) || 0)
      form.append("subject", selectedSubject)
      form.append("thumbnail", selectedImage)

      await api.post("/courses", form, {
        headers: {"Content-Type": "multipart/form-data"}
      })

      setShowAddModal(false)
      setNewCourseName("")
      setEditCourseDescription("")
      setNewCoursePrice("")
      setSelectedSubject("")
      fetchCourses()

    } catch (err) {
      console.error("Create course error:", err)
      alert("Failed to create course")
    }
  }    

  return (
    <div className="content">
      <div className="page-header">
        <h2>Courses ({courses.length})</h2>
        <button
         className="primary-btn"
         onClick={() => setShowAddModal(true)}>
          + Add Course
        </button>
      </div>

      <div className="class-filters">
        {["All", "Class 9", "Class 10", "Class 11", "Class 12"].map(c => (
          <button
          key={c}
          onClick={() => setSelectedClass(c)}
          style={{
            background: selectedClass === c ? "#111" : "#e5e7eb",
            color: selectedClass === c ? "#fff" : "#111",
            border: "1px solid #d1d5db",
            padding: "8px 14px",
            borderRadius: "8px",
            cursor: "pointer",
            fontWeight: 500
          }}
          >
            {c}
          </button>
        ))}
      </div>

      <div className="courses-scroll">

       <div className="table-card">
        <table className="modern-table">
          <thead>
            <tr>
              <th>Course Name</th>
              <th>Description</th>
              <th>Thumbnail</th>
              <th>Subject</th>
              <th>Type</th>
              <th>Status</th>
              <th>Edit</th>
              <th>Actions</th>
              <th>Chapters</th>
            </tr>
          </thead>

          <tbody>
            {courses.filter(course =>
             selectedClass === "All" || course.class === selectedClass
            ).length === 0 ? (
              <tr>
                <td colSpan="7" style={{ textAlign: "center", padding: "20px"}}>
                  No Course Present, Click + to add course
                </td>
              </tr>
            ) : (
              courses
              .filter(course =>
                 selectedClass === "All" || course.class === selectedClass
                )
              .map(course => (
                <tr key={course._id}>
                  <td className="course-name">
                    {editingCourseId === course._id ? (
                      <input
                        value={editCourseName}
                        onChange={e => setEditCourseName(e.target.value)}
                      />
                    ) : course.name}
                  </td>

                <td className="muted">
                  {editingCourseId === course._id ? (
                    <>
                    <textarea value={editCourseDescription} onChange={e => setEditCourseDescription(e.target.value)}/>

                      <input type="file" accept="image/*" onChange={e => setEditThumbnail(e.target.files[0])}/>
                      </>
                  ): truncate(course.description)}
                </td>

                <td>
                  {course.thumbnail ? (
                    <img src={`http://localhost:500/uploads/${course.thumbnail}`}
                    alt="thumb"
                    style={{width: 70, height: 70, objectFit: "cover", borderRadius: "8px"}}/>
                  ): "-"}
                </td>

                <td>{course.subject?.name || "-"}</td>

                <td>
                  <span className={`badge ${course.isPaid ? "paid" : "free"}`}>
                    {course.isPaid ? "Paid" : "Free"}
                  </span>
                </td>

                <td>
                  <span className={`badge ${course.isFrozen ? "frozen" : "active"}`}>
                    {course.isFrozen ? "Frozen" : "Active"}
                  </span>
                </td>

                <td>
                  {editingCourseId === course._id ? (
                    <>
                      <button onClick={() => saveEdit(course._id)}>Save</button>
                      <button onClick={() => setEditingCourseId(null)}>Cancel</button>
                    </>
                  ) : (
                    <button className="icon-btn" onClick={() => startEdit(course)}>
                      ✏️
                    </button>
                  )}
                </td>

                <td className="dropdown-cell">
                  <button
                    className={`icon-btn gear-btn ${openActionCourseId === course._id ? "active" : ""}`}
                      onClick={(e) =>{
                        const rect = e.currentTarget.getBoundingClientRect()

                        setDropdownPos({
                          top: rect.bottom +6,
                          left: rect.right -200
                        })
                      setOpenActionCourseId(
                      openActionCourseId === course._id ? null : course._id
                      )
                    }}
                    >
                    <i className="fa-solid fa-gear"></i>
                  </button>


                  {openActionCourseId === course._id && (
                    <div className="dropdown"
                    style={{
                      top: dropdownPos.top,
                      left: dropdownPos.left
                    }}>
                      <button onClick={() => togglePaid(course._id)}>
                        {course.isPaid ? "Mark as Free" : "Mark as Paid"}
                      </button>

                      <button onClick={() => toggleFreeze(course._id)}>
                        {course.isFrozen ? "Unfreeze Course" : "Freeze Course"}
                      </button>

                      <button onClick={() => toggleContentLock(course._id)}>
                        {course.isContentLocked ? "Unlock Content" : "Lock Content"}
                      </button>

                      <button onClick={() => toggleArchive(course._id)}>
                        {course.isArchived ? "Unarchive Course" : "Archive Course"}
                      </button>
                    </div>
                  )}
                </td>

                <td>
                  <button
                    className="link-btn"
                    onClick={() =>
                      navigate(`/admin/courses/${course._id}/chapters`)
                    }
                  >
                    Manage
                  </button>
                </td>
              </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
     </div>

     {showAddModal && (
      <div className="modal-overlay">
        <div className="modal-box">
          <h3>Add Course</h3>

          <input placeholder="Course Name" value={newCourseName} onChange={e => setNewCourseName(e.target.value)}/>

          <select value={newCourseClass}
          onChange={e => setNewCourseClass(e.target.value)}>
            <option>Class 9</option>
            <option>Class 10</option>
            <option>Class 11</option>
            <option>Class 12</option>
          </select>

          <select value={selectedSubject} onChange={e => setSelectedSubject(e.target.value)}>

            <option value="">Select Subject</option>
            {subjects.map(s => (
              <option key={s._id} value={s._id}>
                {s.name}
              </option>
            ))}
          </select>

          <textarea placeholder="Description" value={newCourseDescription} onChange={e => setNewCourseDescription(e.target.value)}/>

            <input type="number" placeholder="Enter Price (leave empty for free)" value={newCoursePrice} onChange={e => setNewCoursePrice(e.target.value)}/>

            <input type="file" accept="image/*" onChange={e => setSelectedImage(e.target.files[0])} />

          <div style={{ display: "flex", gap:"10px", marginTop: "10px"}}>
            <button onClick={createCourse}>
              Create Course
            </button>

            <button onClick={() => setShowAddModal(false)}>
              Cancel
            </button>
          </div>
        </div>
      </div>
     )}


    </div>
  )
}
