"use client";

import { useState, useEffect } from "react";
import { envConfig } from "@/app/lib/config";
import styleprograms from "./programas.module.css";
import axios from "axios";
import Swal from "sweetalert2";
import Cookies from "js-cookie";

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("");

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

  const cargarProgramas = async () => {
    try {
      const response = await axios.get(`${envConfig.apiUrl}/programa/`, { headers }
      );
      setProgramas(response.data);
    } catch (error: any) {
      console.error("Error al cargar programas:", error);
      Swal.fire({
        title: "Error al cargar programas",
        text: error.response?.data?.message || error.message,
        icon: "error",
      });
    }
  };

  useEffect(() => {
    cargarProgramas();
  }, []);

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

    try {
      await axios.post(`${envConfig.apiUrl}/programa`, {
        programa: nombrePrograma,
      }, { headers }
      );

      await cargarProgramas();

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

      Swal.fire({
        title: "Programa creado correctamente",
        icon: "success",
      });
    } catch (error: any) {
      Swal.fire({
        title: "Error al insertar",
        text: error.response?.data?.message || error.message,
        icon: "error",
      });
    }
  };

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

      await axios.patch(
        `${envConfig.apiUrl}/programa/${programaSeleccionado}`,
        {
          programa: nombrePrograma,
        },
        { headers },
      );

      await cargarProgramas();
      setModo("ver");

      Swal.fire({
        title: "Programa actualizado correctamente",
        icon: "success",
      });
    } catch (error: any) {
      Swal.fire({
        title: "Error al actualizar",
        text: error.response?.data?.message || error.message,
        icon: "error",
      });
    }
  };

  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");
    }
  };

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

    try {
      await axios.delete(
        `${envConfig.apiUrl}/programa/${programaSeleccionado}`,
        { headers },
      );

      await cargarProgramas();
      setProgramaSeleccionado("");

      Swal.fire({
        title: "Programa eliminado exitosamente",
        icon: "success",
      });
    } catch (error: any) {
      Swal.fire({
        title: "Error al eliminar",
        text: error.response?.data?.message || error.message,
        icon: "error",
      });
    }
  };

  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 buttonCharge"
              style={{ margin: "5px" }}
              onClick={handleNuevo}
            >
              Nuevo
            </button>
          </div>
        </section>
      )}

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

          <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>

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

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

          <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>
  );
}
//IO