"use client";
import { useEffect, useState } from "react";
import apiClient from "@/app/lib/apiClient";

import "./registerAlta.css";
import toast from "react-hot-toast";
import { useRouter } from "next/navigation";
import Swal from "sweetalert2";

type Carrera = {
  id_carrera: number;
  carrera: string;
};

interface urlProp {
  numCount: string | null;
}

export default function RegisterAlta(props: urlProp) {
  const router = useRouter();
  const [listMajor, setListMajor] = useState<Carrera[]>([]);
  const [saved, setSaved] = useState(false);

  const [form, setForm] = useState({
    cuenta: String(props.numCount),
    nombre: "",
    apellidoP: "",
    apellidoM: "",
    email: `${props.numCount}@pcpuma.acatlan.unam.mx`,
    genero: "",
    carrera: "",
  });

  useEffect(() => {
    const fetchCarreras = async () => {
      try {
        const response = await apiClient.get("/carrera");
        const sorted = response.data.sort((a: Carrera, b: Carrera) =>
          a.carrera.localeCompare(b.carrera),
        );
        setListMajor(sorted);
      } catch (error) {
        console.error("Error al obtener carreras:", error);
      }
    };

    fetchCarreras();
  }, []);

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
  ) => {
    const { name, value } = e.target;
    setForm((prev) => ({ ...prev, [name]: value }));
  };

  const isFormComplete = Object.values(form).every(
    (value) => value.trim() !== "",
  );

  const handleSave = async (e: React.MouseEvent) => {
    e.preventDefault();

    try {
      const payload = {
        id_cuenta: Number(form.cuenta),
        nombre: `${form.apellidoP} ${form.apellidoM} ${form.nombre}`.trim(),
        correo: form.email || undefined,
        id_carrera: Number(form.carrera),
        genero: form.genero || undefined,
      };

      await apiClient.post("/student", payload);

      setSaved(true);
    
       Swal.fire({
            title: "Alumno registrado correctamente!",
            icon: "success",
            draggable: true,
          });
      
    } catch (error) {
      console.error("Error al guardar alumno:", error);
 
       Swal.fire({
            title: "Error al guardar alumno:!",
            icon: "error",
            draggable: true,
          });
      
    }
  };

  const handleInscripcion = (e: React.MouseEvent) => {
    e.preventDefault();
    router.push(`/Inscripcion?numAcount=${form.cuenta}`);
  };

  return (
    <form className="containerAlta gap gridAlta">
      <div className="containerForm">
        <label className="label">No. Cuenta</label>
        <input
          type="text"
          name="cuenta"
          value={form.cuenta}
          onChange={handleChange}
          placeholder="Coloca un número de cuenta..."
          required
        />
      </div>

      <div className="containerForm">
        <label className="label">Nombre</label>
        <input
          type="text"
          name="nombre"
          value={form.nombre}
          onChange={handleChange}
          placeholder="Coloca el nombre"
          required
        />
      </div>

      <div className="containerForm">
        <label className="label">Apellido Paterno</label>
        <input
          type="text"
          name="apellidoP"
          value={form.apellidoP}
          onChange={handleChange}
          placeholder="Coloca el apellido paterno"
          required
        />
      </div>

      <div className="containerForm">
        <label className="label">Apellido Materno</label>
        <input
          type="text"
          name="apellidoM"
          value={form.apellidoM}
          onChange={handleChange}
          placeholder="Coloca el apellido materno"
          required
        />
      </div>

      <div className="containerForm">
        <label className="label">Email</label>
        <input
          type="email"
          name="email"
          value={form.email}
          onChange={handleChange}
          placeholder="Coloca el email"
        />
      </div>

      <div className="containerForm">
        <label className="label">Género</label>
        <select
          name="genero"
          value={form.genero}
          onChange={handleChange}
          required
        >
          <option value="">Selecciona género</option>
          <option value="Femenino">Femenino</option>
          <option value="Masculino">Masculino</option>
          <option value="Otro">Otro</option>
        </select>
      </div>

      <div className="containerForm">
        <label className="label">Carrera</label>
        <select
          name="carrera"
          value={form.carrera}
          onChange={handleChange}
          required
        >
          <option value="">Selecciona la carrera</option>
          {listMajor.map((c) => (
            <option key={c.id_carrera} value={c.id_carrera}>
              {c.carrera}
            </option>
          ))}
        </select>
      </div>

      <div className="altaContainerButton">
        <button
          className="button buttonSave"
          disabled={!isFormComplete}
          onClick={handleSave}
        >
          Guardar
        </button>

        <button
          className="button buttonInscription"
          disabled={!saved}
          onClick={handleInscripcion}
        >
          Inscripción
        </button>
      </div>
    </form>
  );
}
