import { useEffect, useState } from "react"
import api from "../../services/api"

export default function Batch() {

  const [batches, setBatches] = useState([])
  const [selectedBatch, setSelectedBatch] = useState(null) 
  const [courses, setCourses] = useState([])
  const [selectedCourses, setSelectedCourses] = useState([])
  const [showAddModal, setShowAddModal] = useState(false)
  const [batchName, setBatchName] = useState("")
  const [batchClass, setBatchClass] = useState("Class 9")
  const [batchStream, setBatchStream] = useState("Medical")
  const [batchGoal, setBatchGoal] = useState("NEET")
  const [viewCourses, setViewCourses] = useState([])
  const [showViewModal, setShowViewModal] = useState(false)
  const [selectedClass, setSelectedClass] = useState("All")
  const [showAssignModal, setShowAssignModal] = useState(false)
  const [openActionBatchId, setOpenActionBatchId] = useState(null)
  const [dropdownPos, setDropdownPos] = useState({ top: 0, left: 0 })
  const [selectedImage, setSelectedImage] = useState(null)
  const [showEditModal, setShowEditModal] = useState(false)
  const [editBatch, setEditBatch] = useState(null)
  const [viewStudents, setViewStudents] = useState([])
  const [showStudentModal, setShowStudentModal] = useState(false)
  const [showAssignStudentModal, setShowAssignStudentModal] = useState(false)
  const [allStudents, setAllStudents] = useState([])

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

  const loadBatches = async () => {
    try {
      const res = await api.get("/batches")
      setBatches(res.data)
    } catch (err) {
      console.error("Failed to load batches", err)
    }
  }

  const openBatch = async (id) => {
    try{
      const res = await api.get(`/batches/${id}/courses`)

      const batch = batches.find(b => b._id ===id)

      setSelectedBatch(id)
      setShowAssignModal(true)
      setCourses(res.data.allCourses)
      setSelectedCourses(res.data.batchCourses)
      setSelectedClass(batch.class)
    } catch (err) {
      console.error("Failed to load batch courses", err)
    }
  }

  const saveCourses = async () => {
    try{
      await api.put(`/batches/${selectedBatch}/courses`, {
        courses: selectedCourses
      })

      await loadBatches()
      setSelectedBatch(null)
      setShowAssignModal(false)

      alert("Courses assigned successfully")

    } catch (err) {
      console.error("Failed to save courses", err)
    }
  }

  const createBatch = async () => {
    try {

      if (!batchName) {
        alert("Batch name required")
        return
      }

      const slug = batchName
        .toLowerCase()
        .replace(/\s+/g, "-")

      const form = new FormData()

      form.append("name", batchName)
      form.append("slug", slug)
      form.append("class", batchClass)
      form.append("stream", batchStream)
      form.append("goal", batchGoal)

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

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

      setShowAddModal(false)
      setBatchName("")
      loadBatches()

    } catch (err) {
      console.error("Create batch failed", err)
    }
  }

  const filteredBatches = batches.filter(batch =>
    selectedClass === "All" || batch.class === selectedClass
  )

  const startEdit = (batch) => {
    setEditBatch(batch)
    setBatchName(batch.name)
    setBatchClass(batch.class)
    setBatchStream(batch.stream || "")
    setBatchGoal(batch.goal || "")
    setSelectedImage(null)

    setShowEditModal(true)
  }
  
  const updateBatch = async () => {
    try{

      const form = new FormData()

      form.append("name", batchName)
      form.append("class", batchClass)
      form.append("stream", batchStream)
      form.append("goal", batchGoal)

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

      await api.put(`/batches/${editBatch._id}`, form, {
        headers: { "Content-Type": "multipart/form-data" }
      })

      await loadBatches()

      setShowEditModal(false)
      setEditBatch(null)

      alert("Batch updated successfully")

    } catch (err) {
      console.error("Update failed", err)
    }
  }

  const loadStudents = async () => {
    try{
      const res = await api.get("/users/all")
      setAllStudents(res.data)
    } catch(err) {
      console.error("Failed to load students", err)
    }
  }

  const archiveBatch = async (id) => {
    try{
      await api.patch(`batches/${id}/archive`)

      await loadBatches()

      alert("Batch archived")
    } catch (err) {
      console.error("Archived failed", err)
    }
  }

  return (
    <div className="content">

      <div className="page-header">
        <h2>Batches ({filteredBatches.length})</h2>

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

      <div className="class-filters" style={{marginTop:"10px"}}>
        {["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,
              marginRight: "8px"
            }}
          >
            {c}
          </button>
        ))}
      </div>
      <div>

        <div className="table-card">
          <table className="modern-table">
            <thead>
              <tr>
                <th>Batch Name</th>
                <th>Class</th>
                <th>Stream</th>
                <th>Goal</th>
                <th>Thumbnail</th>
                <th>Edit</th>
                <th>Courses</th>
                <th>Students</th>
                <th>Actions</th>
              </tr>
            </thead>

            <tbody>
              {filteredBatches.map(batch =>(
                <tr key={batch._id}>
                  <td>{batch.name}</td>
                  <td>{batch.class}</td>
                  <td>{batch.stream}</td>
                  <td>{batch.goal}</td>
                  <td>
                    {batch.thumbnail ? (
                      <img 
                        src={`http://localhost:5000/uploads/${batch.thumbnail}`} 
                        alt="thumb"
                        style={{
                          width: 60,
                          height: 60,
                          objectFit: "cover",
                          borderRadius: "8px"
                        }} 
                      />
                    ) : "-" }
                  </td>

                  <td>
                    <button
                      className="icon-btn"
                      onClick={() => startEdit(batch)}
                    >
                      ✏️
                    </button>
                  </td>

                  <td>
                    {batch.courses?.length || 0} Courses

                    {batch.courses?.length > 0 && (
                      <button
                        className="link-btn"
                        style={{marginLeft:"10px"}}
                        onClick={async () => {

                          setSelectedBatch(batch._id)

                          const res = await api.get(`/batches/${batch._id}/courses`)

                          const assigned = res.data.allCourses.filter(course =>
                            res.data.batchCourses.some(id => id.toString() === course._id.toString())
                          )

                          setViewCourses(assigned)
                          setShowViewModal(true)
                        }}
                      >
                        View
                      </button>
                    )}
                  </td>

                  <td>
                    {batch.students?.length || 0} Students

                      <button
                        className="link-btn"
                        style={{ marginLeft: "10px"}}
                        onClick={() => {
                          setViewStudents(batch.students)
                          setShowStudentModal(true)
                        }}
                      >
                        View
                      </button>
                    
                  </td>
                  <td className="dropdown-cell">
                    <button
                      className={`icon-btn gear-btn ${openActionBatchId === batch._id ? "active" : ""}`}
                      onClick={(e) => {
                        const rect = e.currentTarget.getBoundingClientRect()

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

                        setOpenActionBatchId(
                          openActionBatchId === batch._id ? null : batch._id
                        )
                      }}
                    >
                      <i className="fa-solid fa-gear"></i>
                    </button>

                    {openActionBatchId === batch._id && (
                      <div
                        className="dropdown"
                        style={{
                          top: dropdownPos.top,
                          left: dropdownPos.left
                        }}
                      >

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

                        <button onClick={() => archiveBatch(batch._id)}>
                          Archive Batch
                        </button>
                      </div>
                    )}
                  </td>
                </tr>
              ))
              }
            </tbody>
          </table>
        </div>
      </div>

      {showAddModal && (
        <div className="modal-overlay">
          <div className="modal-box">

            <h3>Add Batch</h3>

            <input
              placeholder="Batch Name"
              value={batchName}
              onChange={(e) => setBatchName(e.target.value)}
            />

            <select
              value={batchClass}
              onChange={(e) => {
                const value = e.target.value
                setBatchClass(value)

                if (value === "Class 9" || value === "Class 10") {
                  setBatchStream("")
                }
              }}
            >
              <option>Class 9</option>
              <option>Class 10</option>
              <option>Class 11</option>
              <option>Class 12</option>
            </select>

            <select
              value={batchStream}
              onChange={(e) => setBatchStream(e.target.value)}
              disabled={batchClass === "Class 9" || batchClass === "Class 10"}
            >
              <option>Medical</option>
              <option>Non-Medical</option>
              <option>Commerce</option>
            </select>

            <select
              value={batchGoal}
              onChange={(e) => setBatchGoal(e.target.value)}
            >
              <option>CBSE</option>
              <option>JEE</option>
              <option>NEET</option>
              <option>Nursing</option>
              <option>NDA</option>
              <option>Para-Medical</option>
            </select>

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

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

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

          </div>
        </div>
      )}

      {showEditModal && (
        <div className="modal-overlay">
          <div className="modal-box">

            <h3>Edit Batch</h3>

            <input
              value={batchName}
              onChange={(e) => setBatchName(e.target.value)}
            />

            <select
              value={batchClass}
              onChange={(e) => {
                const value = e.target.value
                setBatchClass(value)

                if (value === "Class 9" || value === "Class 10") {
                  setBatchStream("")
                }
              }}
            >
              <option>Class 9</option>
              <option>Class 10</option>
              <option>Class 11</option>
              <option>Class 12</option>
            </select>

            <select
              value={batchStream}
              disabled={batchClass === "Class 9" || batchClass === "Class 10"}
              onChange={(e) => setBatchStream(e.target.value)}
              >
                <option value="">Select Stream</option>
                <option>Medical</option>
                <option>Non-Medical</option>
                <option>Commerce</option>
              </select>

              <select
                value={batchGoal}
                onChange={(e) => setBatchGoal(e.target.value)}
              >
                <option>CBSE</option>
                <option>JEE</option>
                <option>NEET</option>
                <option>Nursing</option>
                <option>NDA</option>
                <option>Para-Medical</option>
              </select>

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

              <div style={{display:"flex", gap:"10px", marginTop:"10px"}}>
                <button onClick={updateBatch}>
                  Update Batch
                </button>

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

          </div>
        </div>
      )}

      {showViewModal && (
        <div className="modal-overlay">
          <div className="modal-box">

            <h3>Assigned Courses</h3>

            {viewCourses.map(course => (
              <div key={course._id} style={{marginBottom:"8px"}}>
                {course.name}
              </div>
            ))}

            <button
              style={{marginTop: "12px"}}
              onClick={ async () => {

                setShowViewModal(false)

                const res = await api.get(`/batches/${selectedBatch}/courses`)

                const batch = batches.find(b => b._id === selectedBatch)

                setCourses(res.data.allCourses)
                setSelectedCourses(res.data.batchCourses)
                setSelectedClass(batch.class)

                setShowAssignModal(true)
              }}
            >
              Assign / Modify Courses
            </button>

            <button onClick={() => setShowViewModal(false)}>
              Close
            </button>
            
          </div>
        </div>
      )}

      {showAssignModal && (
        <div className="modal-overlay">
          <div className="modal-box" style={{width:"650px"}}>

            <h3>Assign Courses</h3>

            <div className="class-filters" style={{marginBottom:"10px"}}>
              {["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",
                    padding: "6px 10px",
                    borderRadius: "6px",
                    marginRight: "6px"
                  }}
                >
                {c}
                </button>
              ))}
            </div>

            <div 
              className="table-card" 
              style={{
                maxHeight:"300px", 
                overflowY:"auto",
                overflowX:"auto",
                width: "100%"
              }}>
              <table className="modern-table">
                <thead>
                  <tr>
                    <th>Select</th>
                    <th>Course Name</th>
                    <th>Class</th>
                  </tr>
                </thead>

                <tbody>
                  {courses
                    .filter(course =>
                      selectedClass === "All" || course.class === selectedClass
                    )
                    .map(course => (
                      <tr key={course._id}>
                        <td>
                          <input
                            type="checkbox"
                            checked={selectedCourses.includes(course._id)}
                            onChange={(e) => {
                              if (e.target.checked) {
                                setSelectedCourses([...selectedCourses, course._id])
                              } else {
                                setSelectedCourses(
                                  selectedCourses.filter(id => id !== course._id)
                                )
                              }
                            }}
                          />
                        </td>

                        <td>{course.name}</td>
                        <td>{course.class}</td>
                      </tr>
                    ))}
                </tbody>
              </table>
            </div>

            <div style={{marginTop:"15px", display:"flex", gap:"10px"}}>
              <button onClick={saveCourses}>
                Save
              </button>

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

          </div>
        </div>
      )}

      {showStudentModal && (
        <div className="modal-overlay">
          <div className="modal-box">

            <h3>Students</h3>

            <button
              style={{ marginBottom: "10px" }}
              onClick={() => {
                loadStudents()
                setShowAssignStudentModal(true)
              }}
            >
              + Assign Student
            </button>

            {viewStudents.length === 0 ? (
              <p>No students enrolled</p>
            ): (
              viewStudents.map((student, index) => (
                <div key={index} style={{ marginBottom: "8px" }}>
                  {student.name} ({student.class})
                </div>
              ))
            )}

            <button onClick={() => setShowStudentModal(false)}>
              Close
            </button>
            
          </div>
        </div>
      )}

      {showAssignStudentModal && (
        <div className="modal-overlay">
          <div className="modal-box" style={{ width: "500px" }}>

            <h3>Assign Student</h3>

            <div style={{ maxHeight: "300px", overflowY: "auto" }}>
              {allStudents.map(student => {

                const isAssigned = viewStudents.some(s => s._id === student._id)

                return(
                  <div
                    key={student._id}
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      marginBottom: "8px"
                    }}
                  >
                    <span>
                      {student.name} ({student.class})
                    </span>

                    <button
                      style={{
                        background: isAssigned ? "#f59e0b" : "#2563eb",
                        color: "#fff"
                      }}
                      onClick={async () => {
                        try{
                          await api.put("/users/assign-batch", {
                            userId: student._id,
                            batchId: isAssigned ? null : selectedBatch
                          })

                          alert(isAssigned ? "Student-on hold" : "Assigned successfully")

                          setShowAssignStudentModal(false)
                          loadBatches()

                        } catch(err) {
                          console.error("Action failed", err)
                        }
                      }}
                    >
                      {isAssigned ? "Hold" : "Assign"}
                    </button>
                  </div>
                )
              })}
            </div>

            <button
              style={{ marginTop: "10px" }}
              onClick={() => setShowAssignStudentModal(false)}
            >
              Close
            </button>

          </div>
        </div>
      )}

    </div>
  )
}