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

export default function Students() {
  const [students, setStudents] = useState([])
  const [openActionId, setOpenActionId] = useState(null)
  const [dropdownPos, setDropdownPos] = useState({ top:0, left:0 })
  const [assignStudent, setAssignStudent] = useState(null)
  const [courses, setCourses] = useState([])
  const [editStudent, setEditStudent] = useState(null)
  const [editForm, setEditForm] = useState({
    name: "",
    email: "",
    mobile:""
  })
  const [showAddModal, setShowAddModal] = useState(false)
  const [newStudent, setNewStudent] = useState({
    name:"",
    email: "",
    password: "",
    mobile: ""
  })

  const navigate = useNavigate()

  const fetchStudents = async () => {
    try {
      const res = await api.get("/users/all")
      console.log("Students API:", res.data)
      setStudents(res.data)
    } catch (err) {
      console.error("Fetch students error:",err)
    }
  }

  const fetchCourses = async () => {
    try{
      const res = await api.get("/courses")
      setCourses(res.data)
    } catch (err){
      console.error("Courses fetch error", err)
    }
  }

  const approve = id =>
    api.patch(`/users/${id}/approve`).then(fetchStudents)

  const freeze = id =>
    api.patch(`/users/${id}/freeze`).then(fetchStudents)

  const resetPassword = id => {
    const newPassword = prompt("Enter new password")
    if (!newPassword) return
    api.patch(`/users/${id}/reset-password`, { newPassword })
      .then(fetchStudents)
  }

  const remove = id => {
    if (!confirm("Delete student?")) return
    api.delete(`/users/${id}`).then(fetchStudents)
  }

  const createStudent = async () => {
    try{
      await api.post("/users/create", newStudent, {
        headers: { "x-admin": "true" }
      })
      setShowAddModal(false)
      setNewStudent({ name:"", email:"", password:"", mobile:""})
      fetchStudents()
    } catch (err) {
      alert(err.response?.data?.message || "Failed to create student")
    }
  }

  useEffect(() => {
    fetchStudents()
    fetchCourses()
  }, [])

  return (
    <div className="content">
      <div className="page-header">
        <h2>Students ({students.length})</h2>

        <button
        className="primary-btn"
        onClick={() => setShowAddModal(true)}
        >
          + Add Student
        </button>
      </div>

      <div className="table-card">
        <table className="modern-table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Email</th>
              <th>Mobile</th>
              <th>Packages</th>
              <th>Reg Type</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>

          <tbody>
            {students.length === 0 ? (
              <tr>
                <td colSpan="4" style={{ textAlign: "center", padding: "20px" }}>
                  No students found
                </td>
              </tr>
            ) : (
              students.map(s => (
                <tr key={s._id}>
                  <td>{s.name}</td>
                  <td className="muted">{s.email}</td>
                  <td>{s.mobile || "-"}</td>
                  <td>{s.purchasedCourses?.length || 0}</td>
                  <td>{s.registrationType || "-"}</td>
                  <td>
                    <span className={`badge ${s.status}`}>
                      {s.status}
                    </span>
                  </td>

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

                        setDropdownPos({
                          top: rect.bottom +6,
                          left: rect.right -170
                        })

                        setOpenActionId(openActionId === s._id ? null : s._id)
                      }}
                    >
                      <i className="fa-solid fa-gear"></i>
                    </button>

                    {openActionId === s._id && (
                      <div 
                      className="dropdown"
                      style={{
                        top: dropdownPos.top,
                        left: dropdownPos.left
                      }}>
                        {s.status !== "active" ? (
                        <button onClick={() => approve(s._id)}>
                          Approve
                        </button>
                      ):(
                        <button onClick={() => freeze(s._id)}>
                          Freeze
                        </button>
                      )}
                        <button onClick={() => resetPassword(s._id)}>
                          Reset Password
                        </button>

                        <button onClick={() => setAssignStudent(s)}>
                          Assign Course
                        </button>

                        <button
                        onClick={() => {
                          setEditStudent(s)
                          setEditForm({
                            name: s.name,
                            email: s.email,
                            mobile: s.mobile || ""
                          })
                        }}
                        >
                          Update
                        </button>

                        <button onClick={() => remove(s._id)}>
                          Delete
                        </button>
                      </div>
                    )}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
      {assignStudent && (
        <div className="modal-overlay">
          <div className="modal-box">
            <h3>Assign / Lock Course</h3>

            <p>{assignStudent.name}</p>

            <div style={{maxHeight: 300, overflowY: "auto "}}>
              {courses.map(c => {
                const assigned = assignStudent.purchasedCourses?.includes(c._id)
                const locked = assignStudent.lockedCourses?.includes(c._id)

                return(
                  <div key={c._id} style={{ display:"flex", gap: 12, marginBottom: 8}}>
                    <span style={{ flex:1}}>{c.name}</span>

                    <button
                    onClick={() =>
                      api.patch(`/users/${assignStudent._id}/assign/${c._id}`)
                      .then(fetchStudents)
                    }
                    >
                      {assigned ? "Unassign" : "Assign"}
                    </button>

                    <button
                    onClick={() =>
                      api.patch(`/users/${assignStudent._id}/lock/${c._id}`)
                      .then(fetchStudents)
                    }
                    >
                      {locked ? "Unlock" : "Lock"}
                    </button>
                  </div>
                )
              })}
            </div>

            <button onClick={() => setAssignStudent(null)}>Close</button>
          </div>
        </div>
      )}
      {editStudent && (
        <div className="modal-overlay">
          <div className="modal-box">
            <h3>Update Student</h3>

            <input placeholder="Name"
            value={editForm.name}
            onChange={e =>
              setEditForm({ ...editForm, name: e.target.value})
            }/>

            <input placeholder="Email"
            value={editForm.email}
            onChange={e =>
              setEditForm({ ...editForm, email: e.target.value})
            }/>

            <input placeholder="Mobile No."
            value={editForm.mobile}
            onChange={e =>
              setEditForm({ ...editForm, mobile: e.target.value})
            }/>

            <button
            onClick={() =>
              api.patch(`/users/${editStudent._id}/update`, editForm)
              .then(fetchStudents)
              .then(() => setEditStudent(null))
            }
            >Save</button>

            <button onClick={() => setEditStudent(null)}>Cancel</button>
          </div>
        </div>
      )}
      {showAddModal && (
        <div className="modal-overlay">
          <div className="modal-box">
            <h3>Add Student</h3>

            <input placeholder="Name"
            value={newStudent.name}
            onChange={e => setNewStudent({...newStudent, name:e.target.value})}/>

            <input placeholder="E-mail"
            value={newStudent.email}
            onChange={e => setNewStudent({...newStudent, email:e.target.value})}/>

            <input placeholder="Password"
            type="password"
            value={newStudent.password}
            onChange={e => setNewStudent({...newStudent, password:e.target.value})}/>

            <input placeholder="Mobile"
            value={newStudent.mobile}
            onChange={e => setNewStudent({...newStudent, mobile:e.target.value})}/>

            <div style={{display:"flex", gap:10}}>
              <button onClick={createStudent}>Create</button>
              <button onClick={() => setShowAddModal(false)}>Cancel</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
