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

interface Area {
  id_area_ubicacion: number;
  area: string;
  extra: string;
}

interface Props {
  onSearch: (id: number) => void;
}

export default function SelectorSala({ onSearch }: Props) {
  const [sala, setSala] = useState<Area[]>();
  const [selected, setSelected] = useState<number>();

  const handleChangeEquipo = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setSelected(Number(e.target.value));
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!selected) return;
    onSearch(selected);
  };

  useEffect(() => {
    const fetchData = async () => {
      const response = await axios.get(`${envConfig.apiUrl}/area-ubicacion`);

      setSala(response.data);
    };

    fetchData();
  }, []);

  return (
    <form className="form-container" onSubmit={handleSubmit}>
      <select value={selected} onChange={handleChangeEquipo}>
        <option value="">-- Selecciona una sala --</option>
        {sala &&
          sala.map((sala) => (
            <option key={sala.id_area_ubicacion} value={sala.id_area_ubicacion}>
              {sala.area}
            </option>
          ))}
      </select>
    </form>
  );
}
