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

export default function ArchivedBatches() {

  const [batches, setBatches] = useState([])

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

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

  const restoreBatch = async (id) => {
    try {
      await api.patch(`/batches/${id}/archive`)
      loadArchived()
      alert("Batch restored")
    } catch (err) {
      console.error("Restore failed", err)
    }
  }

  const deleteBatch = async (id) => {
    try {
      await api.delete(`/batches/${id}`)
      loadArchived()
      alert("Batch deleted permanently")
    } catch (err) {
      console.error("Delete failed", err)
    }
  }

  return (
    <div className="content">

      <h2>Archived Batches ({batches.length})</h2>

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

          <tbody>
            {batches.map(batch => (
              <tr key={batch._id}>
                <td>{batch.name}</td>
                <td>{batch.class}</td>
                <td>{batch.stream}</td>
                <td>{batch.goal}</td>

                <td>
                  <button onClick={() => restoreBatch(batch._id)}>
                    Restore
                  </button>

                  <button 
                    style={{ marginLeft: "10px", background: "red", color: "#fff" }}
                    onClick={() => deleteBatch(batch._id)}
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>

        </table>
      </div>

    </div>
  )
}