import { useEffect, useState } from "react"
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 Archived() {
  const [courses, setCourses] = useState([])
  const [openActionCourseId, setOpenActionCourseId] = useState(null)

  const fetchArchived = async () => {
    const res = await api.get("/courses/archived")
    setCourses(res.data)
  }

  useEffect(() => {
    fetchArchived()
  }, [])

  const unarchive = (id) =>
    api.patch(`/courses/${id}/archive`)
      .then(fetchArchived)

  const deleteForever = (id) => {
    if (!confirm("Permanently delete this course?")) return
    api.delete(`/courses/${id}`)
      .then(fetchArchived)
  }

  return (
    <div className="content">
      <div className="page-header">
        <h2>Archived Courses ({courses.length})</h2>
      </div>

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

            <tbody>
              {courses.length === 0 ? (
                <tr>
                  <td colSpan="6" style={{ textAlign: "center", padding: "20px"}}>
                    No archived courses
                  </td>
                </tr>
              ) : (
                courses.map(course => (
                  <tr key={course._id}>
                    <td>{course.name}</td>
                    <td className="muted">{truncate(course.description)}</td>
                    <td>{course.subject?.name || "-"}</td>

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

                    <td>
                      <span className="badge frozen">Archived</span>
                    </td>

                    <td className="dropdown-cell">
                      <button
                        className={`icon-btn gear-btn ${openActionCourseId === course._id ? "active" : ""}`}
                        onClick={() =>
                          setOpenActionCourseId(
                            openActionCourseId === course._id ? null : course._id
                          )
                        }
                      >
                        ⚙️
                      </button>

                      {openActionCourseId === course._id && (
                        <div className="dropdown">
                          <button onClick={() => unarchive(course._id)}>
                            Restore Course
                          </button>

                          <button
                            style={{ color: "red" }}
                            onClick={() => deleteForever(course._id)}
                          >
                            Permanent Delete
                          </button>
                        </div>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
