"use client";
import { envConfig } from "@/app/lib/config";
import { useEffect, useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import axios from "axios";

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 searchParams = useSearchParams();
  const pathname = usePathname();
  const router = useRouter();

  const paramSala = Number(searchParams.get("sala")) || 0;
  const [selected, setSelected] = useState<number>(paramSala);

  useEffect(() => {
    setSelected(paramSala);
    onSearch(paramSala);
  }, [paramSala]);

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

    const params = new URLSearchParams(searchParams.toString());

    if (value === 0) {
      params.delete("sala");
    } else {
      params.set("sala", String(value));
    }

    router.push(`${pathname}?${params.toString()}`);
  };

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

    fetchData();
  }, []);

  return (
    <form className="form-container">
      <label>Salas</label>
      <select value={selected} onChange={handleChangeEquipo}>
        <option value={0}>-- Selecciona una sala --</option>
        {sala.map((s) => (
          <option key={s.id_area_ubicacion} value={s.id_area_ubicacion}>
            {s.area}
          </option>
        ))}
      </select>
    </form>
  );
}
//IO