"use client";

import { useEffect, useState } from "react";
import axios from "axios";
import Cookies from "js-cookie";

interface SearchUserProps {
  value?: string | null;
}

type Alumno = {
  nombre: string;
  carrera: string;
  mesaActiva: boolean;
};

export default function SearchUserTable({ value }: SearchUserProps) {
  const [numAcount, setNumAcount] = useState(value || "");
  const [alumno, setAlumno] = useState<Alumno | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

  useEffect(() => {
    if (value) setNumAcount(value);
  }, [value]);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!numAcount) {
      setError("Ingresa un número de cuenta");
      return;
    }

    setLoading(true);
    setError(null);
    setAlumno(null);

    try {
      const { data } = await axios.get<Alumno>(`/api/alumnos/${numAcount}`,        { headers },
);
      setAlumno(data);
    } catch (err: any) {
      setAlumno(null);
      setError(err.response?.data?.message || "Alumno no encontrado");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="search-user">
      <form className="containerForm" onSubmit={handleSubmit}>
        <label className="label">No. Cuenta</label>
        <div className="groupInput">
          <input
            type="text"
            value={numAcount}
            onChange={(e) => {
              const value = e.target.value;
              // Solo números y máximo 9 dígitos
              if (/^\d*$/.test(value) && value.length <= 9) {
                setNumAcount(value);
              }
            }}
            placeholder="Coloca un número de cuenta..."
            inputMode="numeric"
            pattern="[0-9]*"
          />
          <button className="button buttonSearch" type="submit" disabled={loading}>
            {loading ? "Buscando..." : "Buscar"}
          </button>
        </div>
      </form>

      {error && <p style={{ color: "red", marginTop: "10px" }}>{error}</p>}

      {alumno && (
        <div className="alumno-info" style={{ marginTop: "15px" }}>
          <p><strong>Nombre:</strong> {alumno.nombre}</p>
          <p><strong>Carrera:</strong> {alumno.carrera}</p>
          <p><strong>Mesa activada:</strong> {alumno.mesaActiva ? "Sí" : "No"}</p>
        </div>
      )}
    </div>
  );
}
