// =============================================================
// Dashboard.jsx — GALĪGĀ VERSIJA
// =============================================================
// Iekļauti visi moduļi:
//   ✅ Overview    — statistikas kartītes
//   ✅ Projects    — projektu saraksts
//   ✅ Clients     — klientu saraksts (tikai Admin)
//   ✅ Invoices    — rēķini / finanses
//   ✅ NewRequest  — jauna projekta pieteikumi
//   🚧 AI Agent   — nākamā fāze
// =============================================================

import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  FaProjectDiagram, FaUsers, FaRobot,
  FaWallet, FaChartPie, FaFileInvoice, FaPaperPlane,
} 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";
import NewRequest     from "../components/dashboard/NewRequest";

// ─── MATRIX RAIN ─────────────────────────────────────────────
function useMatrixRain(canvasRef) {
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    const CHARS = "ABCDEF0123456789<>/\\|:;DATA_FLOW";
    const FS = 12;
    let cols, drops, animId;
    const resize = () => {
      canvas.width  = window.innerWidth;
      canvas.height = window.innerHeight;
      cols  = Math.floor(canvas.width / FS);
      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 = `${FS}px 'Courier New', monospace`;
      drops.forEach((y, i) => {
        const char    = CHARS[Math.floor(Math.random() * CHARS.length)];
        ctx.fillStyle = Math.random() > 0.98 ? "#ccffcc" : "#0f3d0f";
        ctx.fillText(char, i * FS, y * FS);
        if (y * FS > 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 }) => {
    const tab = tabName ?? title;
    return (
      <button
        style={activeTab === tab
          ? { ...styles.navItem, ...styles.navItemActive }
          : styles.navItem}
        onClick={() => setActiveTab(tab)}
      >
        <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":
        return <Invoices isAdmin={isAdmin} />;
      case "PIETEIKUMI":
        return <NewRequest isAdmin={isAdmin} />;
      case "AI_AGENT":
        return (
          <div style={{ border: "1px dashed #1a7a35", padding: "60px", textAlign: "center", color: "#1a7a35" }}>
            <div style={{ fontSize: "48px", marginBottom: "15px" }}>🤖</div>
            <div style={{ letterSpacing: "2px" }}>MODULE "AI AGENT" — COMING SOON</div>
          </div>
        );
      default:
        return null;
    }
  };

  // ── HEADER VIRSRAKSTS ─────────────────────────────────────
  const headerTitle = () => {
    if (activeTab === "REKINI")   return isAdmin ? "FINANSES" : "MANI RĒĶINI";
    if (activeTab === "AI_AGENT") return "AI AGENT";
    return activeTab;
  };

  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 />}    tabName="AI_AGENT" />
            </>
          )}

          <NavButton
            title={isAdmin ? "FINANSES" : "MANI RĒĶINI"}
            icon={isAdmin ? <FaWallet /> : <FaFileInvoice />}
            tabName={isAdmin ? "FINANSES" : "REKINI"}
          />

          <NavButton
            title="PIETEIKUMI"
            icon={<FaPaperPlane />}
          />
        </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: "22px", letterSpacing: "2px", fontWeight: "bold", textTransform: "uppercase" }}>
              {headerTitle()}
            </h1>
            <p style={{ fontSize: "11px", 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>
  );
}
