"use client";
import { envConfig } from "@/app/lib/config";
import axios from "axios";
import { useEffect, useState } from "react";
import Swal from "sweetalert2";
import Cookies from "js-cookie";

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

export default function ProgramSelector({
  ubicacion,
  id,
}: {
  ubicacion?: string | null;
  id?: number | null;
}) {
  const [programas, setProgramas] = useState<Programa[]>([]);
  const [checkboxes, setCheckboxes] = useState<Record<number, boolean>>({});

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

  useEffect(() => {
    const fetchData = async () => {
      const [programasRes] = await Promise.all([
        axios.get(`${envConfig.apiUrl}/programa`, { headers },
        )]);

      setProgramas(programasRes.data);

      const initialCheckboxes: Record<number, boolean> = {};
      programasRes.data.forEach((p: Programa) => {
        initialCheckboxes[p.id_programa] = false;
      });
      setCheckboxes(initialCheckboxes);
    };

    fetchData();
  }, []);

  const handleTogglePrograma = (id: number) => {
    setCheckboxes((prev) => ({
      ...prev,
      [id]: !prev[id],
    }));
  };

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

    const programasSeleccionados = Object.keys(checkboxes)
      .filter((id) => checkboxes[Number(id)])
      .map(Number);

    try {
      if (ubicacion && ubicacion !== "0") {
        await axios.patch(
          `${envConfig.apiUrl}/programa-equipo/equipo/${ubicacion}`,
          {
            programas: programasSeleccionados,
          },
          { headers },
        );


        Swal.fire({
          title: "Programas actualizados en la máquina!",
          icon: "success",
          draggable: true
        });
        return;
      }

      if (id) {
        await axios.patch(`${envConfig.apiUrl}/programa-equipo/sala`,
          {
            sala: id,
            programas: programasSeleccionados,
          },
          { headers },
        );


        Swal.fire({
          title: "Programas actualizados en la sala",
          icon: "success",
          draggable: true
        });
        return;
      }

      Swal.fire({
        title: "No se pudo determinar el destino!",
        icon: "error",
        draggable: true
      });
    } catch (error) {


      Swal.fire({
        title: "Error al guardar cambios!",
        icon: "error",
        draggable: true,
      });
    }
  };

  useEffect(() => {
    if (!programas.length) return;
    if (ubicacion === null && id === null) return;

    const buildCheckboxes = async () => {
      const baseCheckboxes: Record<number, boolean> = {};
      programas.forEach((p) => {
        baseCheckboxes[p.id_programa] = false;
      });

      try {
        let res;

        if (ubicacion && ubicacion !== "0") {
          res = await axios.get(
            `${envConfig.apiUrl}/programa-equipo/${ubicacion}`,
            { headers },
          );
        }

        if (id) {
          res = await axios.get(
            `${envConfig.apiUrl}/area-ubicacion/programs/${id}`,
            { headers },

          );
        }

        res?.data.forEach((item: any) => {
          baseCheckboxes[item.id_programa] = true;
        });
      } catch (error: any) {
        if (axios.isAxiosError(error)) {
          if (error.response?.status === 404) {

            Swal.fire({
              title: "Sin programas asignados!",
              icon: "error",
              draggable: true
            });
          } else {

            Swal.fire({
              title: "Error al cargar programas!",
              icon: "error",
              draggable: true
            });

          }
        } else {

          Swal.fire({
            title: "Error inesperado!",
            icon: "error",
            draggable: true
          });
        }
      }

      setCheckboxes(baseCheckboxes);
    };

    buildCheckboxes();
  }, [programas, ubicacion, id]);

  return (
    <form className="form-container" onSubmit={handleSubmit}>
      <div className="checkbox-grid" style={{ gridAutoFlow: "column" }}>
        {programas.map((prog) => (
          <label key={prog.id_programa}>
            <input
              type="checkbox"
              checked={checkboxes[prog.id_programa] || false}
              onChange={() => handleTogglePrograma(prog.id_programa)}
            />
            {prog.programa}
          </label>
        ))}
      </div>

      <button className="button buttonSearch" type="submit">
        Guardar cambios
      </button>
    </form>
  );
}
//IO