// =============================================================
// Dashboard.jsx — Pilnā Versija ar Finanšu Moduli
// =============================================================
// Izmaiņas:
//   1. Importēts Invoices komponents
//   2. Tab "FINANSES" un "MANI RĒĶINI" → rāda Invoices
// =============================================================

import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { FaProjectDiagram, FaUsers, FaRobot, FaWallet, FaChartPie, FaFileInvoice } from "react-icons/fa";

import { styles } from "../dashboardStyles";
import Overview  from "../components/dashboard/Overview";
import Projects  from "../components/dashboard/Projects";
import Clients   from "../components/dashboard/Clients";
import Invoices  from "../components/dashboard/Invoices";   // ← JAUNS

// ─── MATRIX RAIN ─────────────────────────────────────────────
function useMatrixRain(canvasRef) {
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    const CHARS = "ABCDEF0123456789<>/\\|:;DATA_FLOW";
    const FONT_SIZE = 12;
    let cols, drops, animId;
    const resize = () => {
      canvas.width  = window.innerWidth;
      canvas.height = window.innerHeight;
      cols  = Math.floor(canvas.width / FONT_SIZE);
      drops = Array(cols).fill(0).map(() => Math.floor(Math.random() * -100));
    };
    const draw = () => {
      ctx.fillStyle = "rgba(0,0,0,0.08)";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.font = `${FONT_SIZE}px 'Courier New', monospace`;
      drops.forEach((y, i) => {
        const char = CHARS[Math.floor(Math.random() * CHARS.length)];
        const isBright = Math.random() > 0.98;
        ctx.fillStyle = isBright ? "#ccffcc" : "#0f3d0f";
        ctx.fillText(char, i * FONT_SIZE, y * FONT_SIZE);
        if (y * FONT_SIZE > canvas.height && Math.random() > 0.975) drops[i] = 0;
        drops[i]++;
      });
      animId = requestAnimationFrame(draw);
    };
    resize();
    window.addEventListener("resize", resize);
    animId = requestAnimationFrame(draw);
    return () => { cancelAnimationFrame(animId); window.removeEventListener("resize", resize); };
  }, [canvasRef]);
}

// ─── DASHBOARD ────────────────────────────────────────────────
export default function Dashboard() {
  const navigate  = useNavigate();
  const canvasRef = useRef(null);
  useMatrixRain(canvasRef);

  const [user, setUser]         = useState({ full_name: "OPERATOR", role: "UNKNOWN" });
  const [activeTab, setActiveTab] = useState("DASHBOARD");

  useEffect(() => {
    const token    = localStorage.getItem("token");
    const userData = localStorage.getItem("user");
    if (!token) {
      navigate("/login");
    } else if (userData) {
      const parsed = JSON.parse(userData);
      setUser(parsed);
      if (!parsed.full_name) {
        setUser((u) => ({ ...u, full_name: parsed.email?.split("@")[0] || "USER" }));
      }
    }
  }, [navigate]);

  const handleLogout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("user");
    navigate("/login");
  };

  const isAdmin =
    user.role === "admin"      ||
    user.role === "superadmin" ||
    user.is_staff === true     ||
    user.is_superuser === true;

  // ── NAV POGA ──────────────────────────────────────────────
  const NavButton = ({ title, icon, tabName }) => (
    <button
      style={activeTab === (tabName ?? title)
        ? { ...styles.navItem, ...styles.navItemActive }
        : styles.navItem}
      onClick={() => setActiveTab(tabName ?? title)}
    >
      <span style={{ fontSize: "16px" }}>{icon}</span> {title}
    </button>
  );

  // ── SATURA RENDERĒŠANA ────────────────────────────────────
  const renderContent = () => {
    switch (activeTab) {
      case "DASHBOARD":
        return <Overview user={user} isAdmin={isAdmin} />;
      case "PROJEKTI":
        return <Projects user={user} isAdmin={isAdmin} />;
      case "KLIENTI":
        return isAdmin ? <Clients /> : null;
      case "FINANSES":
      case "REKINI":                   // ← Abi tab nosaukumi ved uz Invoices
        return <Invoices isAdmin={isAdmin} />;
      case "AI AGENT":
        return (
          <div style={{ border: "1px dashed #1a7a35", padding: "50px", textAlign: "center", color: "#1a7a35" }}>
            <div style={{ fontSize: "40px", marginBottom: "20px" }}>🤖</div>
            MODULE "AI AGENT" IS UNDER CONSTRUCTION
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div style={styles.container}>
      <canvas ref={canvasRef} style={styles.canvas} />

      {/* SĀNJOSLA */}
      <aside style={styles.sidebar}>
        <div style={styles.logoArea}>
          MIM <span style={{ fontSize: "10px", color: "#1a7a35" }}>v1.0</span>
        </div>

        <nav style={styles.nav}>
          <NavButton title="DASHBOARD" icon={<FaChartPie />} />
          <NavButton title="PROJEKTI"  icon={<FaProjectDiagram />} />

          {isAdmin && (
            <>
              <NavButton title="KLIENTI"  icon={<FaUsers />} />
              <NavButton title="AI AGENT" icon={<FaRobot />} />
            </>
          )}

          {/* Finanses (Admin) vai Mani Rēķini (Klients) */}
          <NavButton
            title={isAdmin ? "FINANSES" : "MANI RĒĶINI"}
            icon={isAdmin ? <FaWallet /> : <FaFileInvoice />}
            tabName={isAdmin ? "FINANSES" : "REKINI"}
          />
        </nav>

        <div style={{ padding: "20px", fontSize: "10px", color: "#1a7a35", borderTop: "1px solid #1a7a35", textAlign: "center" }}>
          SYS_STATUS: <span style={{ color: "#00ff41", fontWeight: "bold", textShadow: "0 0 5px #00ff41" }}>ONLINE</span>
        </div>
      </aside>

      {/* GALVENAIS SATURS */}
      <main style={styles.main}>
        <header style={styles.header}>
          <div>
            <h1 style={{ fontSize: "24px", letterSpacing: "2px", fontWeight: "bold", textTransform: "uppercase" }}>
              {activeTab === "REKINI" ? (isAdmin ? "FINANSES" : "MANI RĒĶINI") : activeTab}
            </h1>
            <p style={{ fontSize: "12px", color: "#1a7a35", marginTop: "5px" }}>
              // ACCESS LEVEL: {isAdmin ? "ROOT_ADMIN" : "STANDARD_USER"}
            </p>
          </div>

          <div style={{ textAlign: "right" }}>
            <div style={{ fontSize: "14px", fontWeight: "bold", color: "#d1fae5" }}>
              {user.full_name?.toUpperCase()}
            </div>
            <div style={{ fontSize: "10px", color: "#1a7a35", marginBottom: "5px" }}>
              ROLE: {user.role?.toUpperCase() || "UNKNOWN"}
            </div>
            <button
              onClick={handleLogout}
              style={styles.logoutBtn}
              onMouseEnter={(e) => { e.target.style.background = "#ff4444"; e.target.style.color = "black"; }}
              onMouseLeave={(e) => { e.target.style.background = "black";   e.target.style.color = "#ff4444"; }}
            >
              TERMINATE SESSION
            </button>
          </div>
        </header>

        {renderContent()}
      </main>
    </div>
  );
}
