"use client";

import { useState, useEffect } from "react";
import styleprograms from "./programas.module.css";
import { envConfig } from "@/app/lib/config";

interface Programa {
  id_programa: number;
  programa: string;
}

export default function Page() {
  const [modo, setModo] = useState("ver");

  const [programaSeleccionado, setProgramaSeleccionado] = useState("");
  const [programas, setProgramas] = useState<Programa[]>([]);
  const [nombrePrograma, setNombrePrograma] = useState("");

  useEffect(() => {
    fetch(`${envConfig.apiUrl}/programa/`)
      .then((res) => res.json())
      .then((data) => setProgramas(data))
      .catch((error) => console.error("Error al cargar programas:", error));
  }, []);

  const handleInsertar = async () => {
  if (!nombrePrograma) return;

  await fetch(`${envConfig.apiUrl}/programa`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      programa: nombrePrograma,
    }),
  });

  const res = await fetch(`${envConfig.apiUrl}/programa/`);
  const data = await res.json();
  setProgramas(data);

  setNombrePrograma("");
  setModo("ver");
};


  const handleGuardar = async () => {
    if (!programaSeleccionado) return;

    await fetch(`${envConfig.apiUrl}/programa/${programaSeleccionado}`, {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        programa: nombrePrograma,
      }),
    });

    const res = await fetch(`${envConfig.apiUrl}/programa/`);
    const data = await res.json();
    setProgramas(data);

    setModo("ver");
  };

  const handleNuevo = () => setModo("nuevo");

  const handleCancelar = () => setModo("ver");
  const handleEditar = () => {
    const programa = programas.find(
      (p) => p.id_programa === Number(programaSeleccionado),
    );

    if (programa) {
      setNombrePrograma(programa.programa);
      setModo("editar");
    }
  };

  return (
    <section className="containerSection">
      {modo === "ver" && (
        <section className="containersection">
          <h3 className="title">PROGRAMAS</h3>
          <label className="label">Selecciona el programa que quieres editar</label>

          <select
            value={programaSeleccionado}
            onChange={(e) => setProgramaSeleccionado(e.target.value)}
          >
            <option value="">Selecciona un programa</option>

            {programas.map((programa) => (
              <option key={programa.id_programa} value={programa.id_programa}>
                {programa.programa}
              </option>
            ))}
          </select>

          <div className="margin">
            <button className="button buttonSearch" onClick={handleEditar}>
              Editar
            </button>

            <button
              className={`button buttonSearch`}
              style={{margin:"5px"}}
              onClick={handleNuevo}
            >
              Nuevo
            </button>
          </div>
        </section>
      )}

      {}
      {modo === "editar" && (
        <section className="containersection">
          <h2 className="title">Editar Programa</h2>
          <label className="label"> {programaSeleccionado}</label>

          <input
            type="text"
            value={nombrePrograma}
            onChange={(e) => setNombrePrograma(e.target.value)}
            placeholder="Nombre del programa"
          />

          <div className="margin">
         <button className="button buttonSearch" onClick={handleGuardar}>
  Guardar
</button>

            

            <button
              className={`button buttonCancel ${styleprograms.button}`}
              onClick={handleCancelar}
            >
              Cancelar
            </button>
          </div>
        </section>
      )}

      {}
      {modo === "nuevo" && (
        <section className="containersection">
          <h2 className="title">Nuevo Programa</h2>

          <label className="label">Programa</label>
          <input
  type="text"
  value={nombrePrograma}
  onChange={(e) => setNombrePrograma(e.target.value)}
  placeholder="Coloca el programa"
/>


          <div className="margin">
            <button className="button buttonSearch" onClick={handleInsertar}>
  Insertar
</button>


            <button
              className={`button buttonCancel ${styleprograms.button}`}
              onClick={handleCancelar}
            >
              Cancelar
            </button>
          </div>
        </section>
      )}
    </section>
  );
}
