"use client";

import { useState, useEffect } from "react";
import axios from "axios";
import styles from "./pregunta2.module.scss";
import Cookies from "js-cookie";
import ToggleButton from "../Toggle/ToggleButton";
type OsEntry = {
  os: string;
  count: number;
  isTotal?: boolean;
};

type PlatformKey =
  | "pc-desktop"
  | "apple-desktop"
  | "pc-laptop"
  | "apple-laptop"
  | "servers";

type PlatformData = Record<PlatformKey, OsEntry[]>;

const PLATFORM_LABELS: Record<PlatformKey, string> = {
  "pc-desktop": "Computadoras de escritorio Plataforma PC",
  "apple-desktop": "Computadoras de escritorio Plataforma Apple",
  "pc-laptop": "Computadoras portátiles Plataforma PC",
  "apple-laptop": "Computadoras portátiles Plataforma Apple",
  servers: "Servidores de alto rendimiento",
};

interface RawOsEntry {
  sistema_operativo: string;
  total: string;
}

const PLATFORM_OS_LIST: Record<PlatformKey, string[]> = {
  "pc-desktop": [
    "Windows 11",
    "Windows 10",
    "Windows 7/8",
    "Windows XP/Vista",
    "Linux",
  ],

  "apple-desktop": [
    "MAC OS (SEQUOIA)",
    "Mac OS (13 - Ventura, 14 - Sonoma)",
    "Mac OS X (Mojave, Catalina, 11 - Big Sur, 12 - Monterrey)",
    "Mac OS X (Snow Leopard, Lion, Mountain Lion, Mavericks)",
    "Mac OS X (Yosemite, El Capitan, Sierra, High Sierra)",
  ],

  "pc-laptop": [
    "Windows 11",
    "Windows 10",
    "Windows 7/8",
    "Windows XP/Vista",
    "Chrome OS",
  ],

  "apple-laptop": [
    "Mac OS (13 - Ventura, 14 - Sonoma)",
    "Mac OS X (Mojave, Catalina, 11 - Big Sur, 12 - Monterrey)",
    "Mac OS X (Snow Leopard, Lion, Mountain Lion, Mavericks)",
    "Mac OS X (Yosemite, El Capitan, Sierra, High Sierra)",
  ],

  servers: [
    "Linux (CentOS, Fedora, Ubuntu, Red Hat Enterprise, entre otros)",
    "UNIX (AIX, MAC OS SERVER, SOLARIS, ENTRE OTROS)",
    "Windows Server 2022/2023",
    "Windows Server 2016/2019",
    "Windows Server 2008/2012",
    "Windows Server 2000/2003",
  ],
};

// reutilizable para normalizar comparaciones
function cleanName(str: string) {
  return (
    str
      .normalize?.("NFKD")
      .replace?.(/\u00A0/g, " ")
      .replace(/\s+/g, " ")
      .trim?.() ?? str
  );
}

function transformPlatform(
  raw: RawOsEntry[],
  platform: PlatformKey
): OsEntry[] {
  const fixedList = PLATFORM_OS_LIST[platform];

  // mapa limpio de los datos que llegan
  const mapRaw: Record<string, number> = {};
  raw.forEach((item) => {
    const name = cleanName(item.sistema_operativo);
    mapRaw[name] = (mapRaw[name] || 0) + Number(item.total || 0);
  });

  // 1) primero los fijos, con su conteo (0 si no vienen)
  const rows: OsEntry[] = fixedList.map((os) => ({
    os,
    count: mapRaw[cleanName(os)] ?? 0,
  }));

  // 2) luego agregamos cualquier SO extra que vino en los datos y no esté en la lista fija
  const fixedCleanSet = new Set(fixedList.map((s) => cleanName(s)));
  const extras = Object.keys(mapRaw)
    .filter((rawName) => !fixedCleanSet.has(cleanName(rawName)))
    // opcional: mantener orden natural o por nombre
    .sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }))
    .map((name) => ({ os: name, count: mapRaw[name] }));

  // append extras after fixed ones
  rows.push(...extras);

  // total (incluye extras)
  const total = rows.reduce((a, r) => a + r.count, 0);
  rows.push({ os: "Total", count: total, isTotal: true });

  return rows;
}

export default function Pregunta2() {
  const [activeTab, setActiveTab] = useState<PlatformKey>("pc-desktop");
  const [data, setData] = useState<PlatformData | null>(null);
  const [loading, setLoading] = useState<boolean>(true);

  const cargarDatos = async (baja: boolean) => {
    setLoading(true);
    const token = Cookies.get("token");
    const headers = { Authorization: `Bearer ${token}` };

    const body = baja ? ["BAJA"] : ["EN DESUSO", "EN USO"];
    axios
      .post(
        `${process.env.NEXT_PUBLIC_API_URL}/equipos/reporte/tipoEquipos_sistemasOperativos`,
        body,
        { headers }
      )
      .then((res) => {
        const json = res.data;

        const formatted: PlatformData = {
          "pc-desktop": transformPlatform(json[0] || [], "pc-desktop"),
          "apple-desktop": transformPlatform(json[1] || [], "apple-desktop"),
          "pc-laptop": transformPlatform(json[2] || [], "pc-laptop"),
          "apple-laptop": transformPlatform(json[3] || [], "apple-laptop"),
          servers: transformPlatform(json[4] || [], "servers"),
        };

        setData(formatted);
        setLoading(false);
      })
      .catch((err) => {
        console.error("Error cargando datos", err);
        setData({
          "pc-desktop": transformPlatform([], "pc-desktop"),
          "apple-desktop": transformPlatform([], "apple-desktop"),
          "pc-laptop": transformPlatform([], "pc-laptop"),
          "apple-laptop": transformPlatform([], "apple-laptop"),
          servers: transformPlatform([], "servers"),
        });
        setLoading(false);
      });
  };

  useEffect(() => {
    cargarDatos(false);
  }, []);

  const rowsToRender: OsEntry[] = loading
    ? PLATFORM_OS_LIST[activeTab].map((os) => ({ os, count: 0 }))
    : data
    ? data[activeTab]
    : PLATFORM_OS_LIST[activeTab].map((os) => ({ os, count: 0 }));

  const isOsInvalid = (os: string, tab: PlatformKey) => {
    if (os === "Total") return false;
    const fixedList = PLATFORM_OS_LIST[tab];
    // comparamos con cleaned strings
    return !fixedList.some(
      (s) => cleanName(s).toLowerCase() === cleanName(os).toLowerCase()
    );
  };

  return (
    <div className={styles.container_P1}>
      <div className={styles["contenedor-censo_p1"]}>
        Censo de equipos de cómputo - Sistema Operativo
      </div>

      <div className={styles["pregunta-cuadro_p1"]}>
        Número de sistemas Operativos por cada categoría y perfil de usuario.
        <ToggleButton
          onChange={(estado) => {
            cargarDatos(estado);
          }}
        />
      </div>
      <div className={styles.scanView_P1}>
        <div className={styles["main-content_P1"]}>
          <div className={styles.tabs_P1}>
            {Object.entries(PLATFORM_LABELS).map(([key, label]) => (
              <button
                key={key}
                className={`${styles.tab_P1} ${
                  activeTab === key ? styles.active_P1 : ""
                }`}
                onClick={() => setActiveTab(key as PlatformKey)}
              >
                {label}
              </button>
            ))}
          </div>

          <div
            className={`${styles["data-table_P1"]} ${
              loading ? styles.loadingBlur : ""
            }`}
          >
            {rowsToRender.map((item, index) => (
              <div
                key={index}
                className={`
    ${styles["data-row_P1"]}
    ${item.isTotal ? styles["total-row_P1"] : ""}
    ${isOsInvalid(item.os, activeTab) ? styles.invalidRow : ""}
  `}
              >
                <div className={styles["os-name_P1"]}>{item.os}</div>
                <div
                  className={`${styles["count-box_P1"]} ${
                    loading ? "skeleton" : ""
                  }`}
                >
                  {loading ? " " : item.count}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
