"use client";

import { envConfig } from "@/app/lib/config";
import { useEffect, useState } from "react";
import { GetSancionByStudent } from "@/app/lib/getSancionByStudent";
import { Alumno, AlumnoSancion } from "@/app/types/sanction";
import TableSanction from "../BitacoraSanciones/TableSanction";
import axios from "axios";
import Cookies from "js-cookie";

function QuitarSancion({ id_cuenta }: { id_cuenta: number }) {
  const [alumno, setAlumno] = useState<Alumno>();
  const [alumnoSanciones, setAlumnoSanciones] = useState<AlumnoSancion[]>([]);
  const [loading, setLoading] = useState<boolean>(false)

  const fetchAlumnoSanciones = async () => {
    try {

      const res = await GetSancionByStudent(id_cuenta);

      setAlumno(res.student ?? null);
      setAlumnoSanciones(res.alusancion ?? []);
    } catch {
    }
  };

  useEffect(() => {
    if (!id_cuenta) return;

    fetchAlumnoSanciones();

  }, [id_cuenta]);

  const handleButton = async (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();

    const token = Cookies.get("token");
    const headers = { Authorization: `Bearer ${token}` };

    setLoading(true)
    await axios.delete(`${envConfig.apiUrl}/alumno-sancion/${id_cuenta}`, { headers })
    setAlumnoSanciones([])
    setLoading(false)
  }

  return (
    <section className="containerSection">
      <TableSanction alumnoSanciones={alumnoSanciones} alumno={alumno} />
      {(alumnoSanciones?.length > 0) &&
        <button
          className="button buttonSearch"
          style={{ margin: "1rem 0" }}
          onClick={handleButton}
          disabled={loading}
        >
          Quitar sancion
        </button>
      }
    </section>
  );
}

export default QuitarSancion;
//IO