"use client";

import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import styles from "./page.module.css";

interface RunnerStatus {
  id: string;
  name: string;
  type: 'mock' | 'claude' | 'claude-docker' | 'claude-ssh' | 'aider' | 'aider-docker';
  status: 'idle' | 'running' | 'stopped';
  createdAt: string;
  logsCount: number;
  workspaceRoot?: string;
  scopedDirs?: string[];
}

// Dynamically import TerminalConsole to bypass SSR errors
const TerminalConsole = dynamic(() => import("./components/TerminalConsole"), {
  ssr: false,
  loading: () => (
    <div 
      style={{ 
        height: "400px", 
        display: "flex", 
        alignItems: "center", 
        justifyContent: "center", 
        backgroundColor: "#05070a", 
        color: "var(--muted)", 
        border: "1px solid var(--border)", 
        borderBottomLeftRadius: "12px", 
        borderBottomRightRadius: "12px" 
      }}
    >
      <span>Initializing terminal emulator...</span>
    </div>
  ),
});

// Dynamically import ContextEditor to bypass SSR errors
const ContextEditor = dynamic(() => import("./components/ContextEditor"), {
  ssr: false,
  loading: () => (
    <div 
      style={{ 
        height: "280px", 
        display: "flex", 
        alignItems: "center", 
        justifyContent: "center", 
        backgroundColor: "var(--card)", 
        border: "1px solid var(--border)", 
        borderRadius: "12px", 
        marginTop: "1.5rem" 
      }}
    >
      <span style={{ color: "var(--muted)" }}>Initializing prompt editor...</span>
    </div>
  ),
});

// Dynamically import SshWizard to bypass SSR errors
const SshWizard = dynamic(() => import("./components/SshWizard"), {
  ssr: false,
});

// Dynamically import AiderWizard to bypass SSR errors
const AiderWizard = dynamic(() => import("./components/AiderWizard"), {
  ssr: false,
});

// Dynamically import ClaudeWizard to bypass SSR errors
const ClaudeWizard = dynamic(() => import("./components/ClaudeWizard"), {
  ssr: false,
});

// Dynamically import IdeLayout to bypass SSR errors
const IdeLayout = dynamic(() => import("./components/IdeLayout"), {
  ssr: false,
});

export default function Home() {
  const [sessions, setSessions] = useState<RunnerStatus[]>([]);
  const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isSshWizardOpen, setIsSshWizardOpen] = useState<boolean>(false);
  const [isAiderWizardOpen, setIsAiderWizardOpen] = useState<boolean>(false);
  const [isAiderDockerLaunch, setIsAiderDockerLaunch] = useState<boolean>(false);
  const [isClaudeWizardOpen, setIsClaudeWizardOpen] = useState<boolean>(false);
  const [isClaudeDockerLaunch, setIsClaudeDockerLaunch] = useState<boolean>(false);

  const activeSession = sessions.find(s => s.id === activeSessionId);
  const isDockerActive = sessions.some(s => (s.type === 'claude-docker' || s.type === 'aider-docker') && s.status === 'running');
  const isSshActive = sessions.some(s => s.type === 'claude-ssh' && s.status === 'running');

  // Fetch all sessions on mount & periodically
  const fetchSessions = async () => {
    try {
      const res = await fetch("/api/sessions");
      const data = await res.json();
      if (data.sessions) {
        setSessions(data.sessions);
      }
    } catch (err) {
      console.error("Failed to fetch sessions:", err);
    }
  };

  useEffect(() => {
    const initFetch = async () => {
      await fetchSessions();
    };
    initFetch();
    const interval = setInterval(fetchSessions, 4000);
    return () => clearInterval(interval);
  }, []);

  // Launch a new Session
  const handleLaunchSession = async (
    type: 'mock' | 'claude' | 'claude-docker' | 'claude-ssh' | 'aider' | 'aider-docker',
    customName?: string,
    customWorkspaceRoot?: string,
    customScopedDirs?: string[]
  ) => {
    setIsLoading(true);
    try {
      let sessionName = customName;
      if (!sessionName) {
        if (type === 'claude') sessionName = "Claude Local";
        else if (type === 'claude-docker') sessionName = "Claude Docker";
        else if (type === 'claude-ssh') sessionName = "Claude SSH";
        else if (type === 'aider') sessionName = "Aider Local";
        else if (type === 'aider-docker') sessionName = "Aider Docker";
        else if (type === 'mock') sessionName = "Mock Session";
      }

      const launchBody: {
        type: string;
        name?: string;
        workspaceRoot?: string;
        scopedDirs?: string[];
      } = { 
        type, 
        name: sessionName, 
        workspaceRoot: customWorkspaceRoot, 
        scopedDirs: customScopedDirs 
      };

      if ((type === 'aider' || type === 'aider-docker') && !customWorkspaceRoot) {
        try {
          const configRes = await fetch("/api/context/aider");
          if (configRes.ok) {
            const configData = await configRes.json();
            if (configData.success && configData.config) {
              launchBody.workspaceRoot = configData.config.workspaceRoot;
              launchBody.scopedDirs = configData.config.scopedDirs;
            }
          }
        } catch (err) {
          console.error("Failed to load aider configuration before launch:", err);
        }
      }

      const res = await fetch("/api/sessions/launch", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(launchBody)
      });
      const data = await res.json();
      if (data.success) {
        await fetchSessions();
        setActiveSessionId(data.session.id);
      }
    } catch (err) {
      console.error("Failed to launch session:", err);
    } finally {
      setIsLoading(false);
    }
  };

  // Stop/Disconnect Session
  const handleStopSession = async (id: string, deletePermanently = false) => {
    try {
      const res = await fetch("/api/sessions/stop", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, delete: deletePermanently })
      });
      const data = await res.json();
      if (data.success) {
        if (deletePermanently && activeSessionId === id) {
          setActiveSessionId(null);
        }
        await fetchSessions();
      }
    } catch (err) {
      console.error("Failed to stop session:", err);
    }
  };

  return (
    <div className={styles.container}>
      {/* Header */}
      <header className={styles.header}>
        <div className={styles.logoArea}>
          <h1 className={styles.title}>NeuralLoom</h1>
          <span className={styles.subtitle}>Unified AI Orchestrator & Context Bridge</span>
        </div>
        <div className={styles.statusIndicator}>
          <span className={styles.pulseDot}></span>
          <span>Orchestrator Online</span>
        </div>
      </header>

      {/* Main Dashboard Grid or Active Session IDE */}
      {activeSession ? (
        <div style={{ padding: "0 2rem", marginBottom: "2rem" }}>
          <IdeLayout
            sessionId={activeSession.id}
            workspaceRoot={activeSession.workspaceRoot || ""}
            scopedDirs={activeSession.scopedDirs || []}
            onClose={() => setActiveSessionId(null)}
            sessions={sessions}
            onSwitchSession={(id) => setActiveSessionId(id)}
          />
        </div>
      ) : (
        <div className={styles.dashboardGrid}>
        
        {/* Left Panel: Active Agents & Interactive Terminal */}
        <main className={styles.mainPanel}>
          <section>
            <h2 className={styles.sectionTitle}>Active AI Agents</h2>
            
            {sessions.length === 0 ? (
              <div className="card" style={{ padding: "3rem 1.5rem", textAlign: "center" }}>
                <p style={{ color: "var(--muted)", marginBottom: "1.5rem" }}>
                  No active agent sessions in this workspace. Launch a simulated session to verify the control bridge.
                </p>
                <button 
                  className={styles.quickLaunchBtn} 
                  onClick={() => handleLaunchSession('mock')}
                  disabled={isLoading}
                  style={{ maxWidth: "240px", margin: "0 auto" }}
                >
                  {isLoading ? "Launching..." : "⚡ Launch Simulated Session"}
                </button>
              </div>
            ) : (
              <div className={styles.agentGrid}>
                {sessions.map(session => (
                  <div key={session.id} className={`${styles.agentCard} card ${activeSessionId === session.id ? styles.activeBorder : ""}`}>
                    <div className={styles.agentHeader}>
                      <span className={styles.agentName}>{session.name}</span>
                      <span className={`${styles.agentBadge} ${session.status === 'stopped' ? styles.stoppedBadge : ""}`}>
                        {session.status}
                      </span>
                    </div>
                    <div className={styles.cardBody}>
                      <p style={{ fontSize: "0.825rem", color: "var(--muted)" }}>
                        ID: <code style={{ fontSize: "0.75rem" }}>{session.id.substring(0, 8)}</code><br />
                        Type: {
                          session.type === 'claude' ? "Claude Local PTY" :
                          session.type === 'claude-docker' ? "Claude Docker PTY" :
                          session.type === 'claude-ssh' ? "Claude SSH PTY" :
                          session.type === 'aider' ? "Aider Local PTY" :
                          session.type === 'aider-docker' ? "Aider Docker PTY" :
                          session.type === 'mock' ? "Simulated Mock PTY" : "Unknown PTY"
                        }<br />
                        Logs: {session.logsCount} captured lines
                      </p>
                      
                      <div style={{ display: "flex", gap: "0.5rem", marginTop: "1rem" }}>
                        {session.status === 'running' ? (
                          <button 
                            onClick={() => handleStopSession(session.id, false)}
                            style={{
                              flex: 1,
                              padding: "0.4rem 0.6rem",
                              borderRadius: "6px",
                              border: "1px solid var(--danger)",
                              backgroundColor: "transparent",
                              fontSize: "0.75rem",
                              fontWeight: 600,
                              color: "var(--danger)"
                            }}
                          >Stop</button>
                        ) : (
                          <button 
                            onClick={() => handleStopSession(session.id, true)}
                            style={{
                              flex: 1,
                              padding: "0.4rem 0.6rem",
                              borderRadius: "6px",
                              border: "1px solid var(--border)",
                              backgroundColor: "transparent",
                              fontSize: "0.75rem",
                              fontWeight: 600,
                              color: "var(--muted)"
                            }}
                          >Delete</button>
                        )}
                        <button 
                          onClick={() => setActiveSessionId(session.id)}
                          style={{
                            flex: 2,
                            padding: "0.4rem 0.6rem",
                            borderRadius: "6px",
                            border: "none",
                            backgroundColor: activeSessionId === session.id ? "var(--border-focus)" : "var(--primary)",
                            fontSize: "0.75rem",
                            fontWeight: 600,
                            color: "#fff"
                          }}
                        >
                          {activeSessionId === session.id ? "Connected" : "Open Session"}
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </section>

          {/* Interactive Session Terminal Display */}
          {activeSessionId && (
            <section className="card" style={{ display: "flex", flexDirection: "column", border: "1px solid var(--border-focus)" }}>
              <div className={styles.agentHeader} style={{ justifyContent: "space-between", background: "rgba(109, 40, 217, 0.08)" }}>
                <span style={{ fontWeight: 600, display: "flex", alignItems: "center", gap: "0.5rem" }}>
                  🖥️ Console Bridge — {sessions.find(s => s.id === activeSessionId)?.name}
                </span>
                <button 
                  onClick={() => setActiveSessionId(null)}
                  style={{
                    border: "none",
                    background: "none",
                    color: "var(--muted)",
                    cursor: "pointer",
                    fontSize: "0.75rem"
                  }}
                >Close Panel ✖</button>
              </div>
              <TerminalConsole sessionId={activeSessionId} />
            </section>
          )}

          {/* Context Hub Staging section */}
          <section>
            <h2 className={styles.sectionTitle}>Shared Context Hub & Slash Commands</h2>
            <div className={styles.contextList}>
              <div className={`${styles.contextItem} card`}>
                <div className={styles.contextMeta}>
                  <span className={styles.contextTitle}>Staged Context & System Rules (/ccc)</span>
                  <span className={styles.contextDetails}>Compiles AGENTS.md guidelines and project files folder hierarchy map.</span>
                </div>
                <button
                  onClick={async () => {
                    if (!activeSessionId) return;
                    await fetch("/api/sessions/inject", {
                      method: "POST",
                      headers: { "Content-Type": "application/json" },
                      body: JSON.stringify({ id: activeSessionId, command: "/ccc" })
                    });
                  }}
                  disabled={!activeSessionId}
                  style={{
                    padding: "0.4rem 0.8rem",
                    borderRadius: "6px",
                    border: "1px solid var(--primary)",
                    backgroundColor: "transparent",
                    color: "var(--primary)",
                    fontSize: "0.75rem",
                    fontWeight: 600,
                    opacity: activeSessionId ? 1 : 0.5,
                    cursor: activeSessionId ? "pointer" : "not-allowed"
                  }}
                >
                  🚀 Mount Context (/ccc)
                </button>
              </div>
              
              <div className={`${styles.contextItem} card`}>
                <div className={styles.contextMeta}>
                  <span className={styles.contextTitle}>Staged Developer Prompt (/ccp)</span>
                  <span className={styles.contextDetails}>Executes instructions written in .ai/neural-loom/cprompt.md.</span>
                </div>
                <button
                  onClick={async () => {
                    if (!activeSessionId) return;
                    await fetch("/api/sessions/inject", {
                      method: "POST",
                      headers: { "Content-Type": "application/json" },
                      body: JSON.stringify({ id: activeSessionId, command: "/ccp" })
                    });
                  }}
                  disabled={!activeSessionId}
                  style={{
                    padding: "0.4rem 0.8rem",
                    borderRadius: "6px",
                    border: "1px solid var(--success)",
                    backgroundColor: "transparent",
                    color: "var(--success)",
                    fontSize: "0.75rem",
                    fontWeight: 600,
                    opacity: activeSessionId ? 1 : 0.5,
                    cursor: activeSessionId ? "pointer" : "not-allowed"
                  }}
                >
                  ⚡ Trigger Prompt (/ccp)
                </button>
              </div>
            </div>
            <ContextEditor />
          </section>
        </main>

        {/* Right Panel: Environments & Actions */}
        <aside className={styles.sidePanel}>
          <section>
            <h2 className={styles.sectionTitle}>Execution Environments</h2>
            <div className={styles.envGrid}>
              <div className={styles.envRow}>
                <span className={styles.envName}>💻 Local host OS</span>
                <span className={styles.envStatus} style={{ color: "var(--success)" }}>Active</span>
              </div>
              <div className={styles.envRow} style={{ opacity: isDockerActive ? 1 : 0.6 }}>
                <span className={styles.envName}>🐳 Docker Sandbox</span>
                <span className={styles.envStatus} style={{ color: isDockerActive ? "var(--success)" : "var(--muted)" }}>
                  {isDockerActive ? "Active" : "Not Mounted"}
                </span>
              </div>
              <div className={styles.envRow} style={{ opacity: isSshActive ? 1 : 0.6 }}>
                <span className={styles.envName}>🌐 Remote VM (SSH)</span>
                <span className={styles.envStatus} style={{ color: isSshActive ? "var(--success)" : "var(--muted)" }}>
                  {isSshActive ? "Active" : "Disconnected"}
                </span>
              </div>
            </div>
          </section>

          <section style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
            <button className={styles.quickLaunchBtn} onClick={() => handleLaunchSession('mock')} disabled={isLoading}>
              <span>⚡</span>
              <span>Launch Mock Agent</span>
            </button>
            <button 
              className={styles.quickLaunchBtn} 
              onClick={() => {
                setIsClaudeDockerLaunch(false);
                setIsClaudeWizardOpen(true);
              }} 
              disabled={isLoading}
              style={{
                background: "linear-gradient(135deg, hsl(262, 83%, 60%) 0%, hsl(195, 100%, 45%) 100%)",
                border: "none"
              }}
            >
              <span>🤖</span>
              <span>Launch Claude PTY</span>
            </button>
            <button 
              className={styles.quickLaunchBtn} 
              onClick={() => {
                setIsClaudeDockerLaunch(true);
                setIsClaudeWizardOpen(true);
              }} 
              disabled={isLoading}
              style={{
                background: "linear-gradient(135deg, hsl(170, 72%, 40%) 0%, hsl(195, 100%, 40%) 100%)",
                border: "none"
              }}
            >
              <span>🐳</span>
              <span>Launch Docker PTY</span>
            </button>
            <button 
              className={styles.quickLaunchBtn} 
              onClick={() => setIsSshWizardOpen(true)} 
              disabled={isLoading}
              style={{
                background: "linear-gradient(135deg, hsl(38, 92%, 50%) 0%, hsl(0, 84%, 60%) 100%)",
                border: "none"
              }}
            >
              <span>🌐</span>
              <span>Launch SSH PTY</span>
            </button>
            <button 
              className={styles.quickLaunchBtn} 
              onClick={() => {
                setIsAiderDockerLaunch(false);
                setIsAiderWizardOpen(true);
              }} 
              disabled={isLoading}
              style={{
                background: "linear-gradient(135deg, hsl(210, 80%, 45%) 0%, hsl(262, 80%, 55%) 100%)",
                border: "none"
              }}
            >
              <span>🐍</span>
              <span>Launch Aider PTY</span>
            </button>
            <button 
              className={styles.quickLaunchBtn} 
              onClick={() => {
                setIsAiderDockerLaunch(true);
                setIsAiderWizardOpen(true);
              }} 
              disabled={isLoading}
              style={{
                background: "linear-gradient(135deg, hsl(195, 100%, 40%) 0%, hsl(262, 80%, 55%) 100%)",
                border: "none"
              }}
            >
              <span>🐳</span>
              <span>Launch Aider Docker</span>
            </button>
          </section>

          <section className="card" style={{ padding: "1.5rem", display: "flex", flexDirection: "column", gap: "0.75rem" }}>
            <h3 style={{ fontSize: "1rem", fontWeight: 700 }}>Quick Actions</h3>
            <ul style={{ listStyle: "none", fontSize: "0.875rem", display: "flex", flexDirection: "column", gap: "0.5rem", color: "var(--muted)" }}>
              <li style={{ display: "flex", justifyContent: "space-between" }}>
                <span>Configure global API Keys</span>
                <span style={{ color: "var(--primary)", cursor: "pointer" }}>→</span>
              </li>
              <li style={{ display: "flex", justifyContent: "space-between" }}>
                <span>Edit rules templates</span>
                <span style={{ color: "var(--primary)", cursor: "pointer" }}>→</span>
              </li>
              <li style={{ display: "flex", justifyContent: "space-between" }}>
                <span>Inspect process locks</span>
                <span style={{ color: "var(--primary)", cursor: "pointer" }}>→</span>
              </li>
            </ul>
          </section>
        </aside>

      </div>
      )}

      {/* Footer */}
      <footer className={styles.footer}>
        <span>NeuralLoom v0.1.0 — Experimental AI Orchestrator Bridge</span>
        <span>Directory: C:\Users\Dave\OneDrive\Projects\JS\neural-loom</span>
      </footer>

      {isSshWizardOpen && (
        <SshWizard
          onClose={() => setIsSshWizardOpen(false)}
          onConfirmLaunch={() => {
            setIsSshWizardOpen(false);
            handleLaunchSession('claude-ssh');
          }}
        />
      )}

      {isAiderWizardOpen && (
        <AiderWizard
          onClose={() => setIsAiderWizardOpen(false)}
          isDocker={isAiderDockerLaunch}
          onConfirmLaunch={() => {
            setIsAiderWizardOpen(false);
            handleLaunchSession(isAiderDockerLaunch ? 'aider-docker' : 'aider');
          }}
        />
      )}

      {isClaudeWizardOpen && (
        <ClaudeWizard
          onClose={() => setIsClaudeWizardOpen(false)}
          isDocker={isClaudeDockerLaunch}
          onConfirmLaunch={(name, workspaceRoot, scopedDirs) => {
            setIsClaudeWizardOpen(false);
            handleLaunchSession(isClaudeDockerLaunch ? 'claude-docker' : 'claude', name, workspaceRoot, scopedDirs);
          }}
        />
      )}
    </div>
  );
}
