import { AnimatePresence, motion } from 'framer-motion';
import { useLocation, useNavigate } from 'react-router-dom';
import styles from './ControlRoom.module.css';

type Panel = 'system' | 'oracle-admin' | 'comms-config' | 'users' | 'models' | 'meta';

const PANELS: { id: Panel; label: string; icon: string }[] = [
  { id: 'system', label: 'System Health', icon: 'S' },
  { id: 'oracle-admin', label: 'Oracle Admin', icon: 'O' },
  { id: 'comms-config', label: 'Comms Config', icon: 'C' },
  { id: 'users', label: 'Users & Roles', icon: 'U' },
  { id: 'models', label: 'Model Hydration', icon: 'M' },
  { id: 'meta', label: 'Meta Integration', icon: 'A' },
];

export default function ControlRoom() {
  const navigate = useNavigate();
  const location = useLocation();
  const routePanel = location.pathname.split('/').filter(Boolean)[1] as Panel | undefined;
  const active: Panel = PANELS.some((panel) => panel.id === routePanel) ? routePanel! : 'system';

  return (
    <div className={styles.root}>
      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <span className={styles.headerIcon}>CR</span>
          <div>
            <h1 className={styles.title}>Control Room</h1>
            <p className={styles.subtitle}>System Administration · Admin Access Only</p>
          </div>
        </div>
        <button className="btn-ghost" onClick={() => navigate('/command')}>
          ← Back to Command
        </button>
      </div>

      <div className={styles.body}>
        <nav className={styles.sidebar}>
          {PANELS.map(({ id, label, icon }) => (
            <button
              key={id}
              className={`${styles.sideItem} ${active === id ? styles.sideActive : ''}`}
              onClick={() => navigate(`/control-room/${id}`)}
              aria-current={active === id ? 'page' : undefined}
            >
              <span className={styles.sideIcon}>{icon}</span>
              <span>{label}</span>
              {active === id && (
                <motion.div
                  layoutId="cr-indicator"
                  className={styles.indicator}
                  transition={{ type: 'spring', stiffness: 400, damping: 35 }}
                />
              )}
            </button>
          ))}
        </nav>

        <main className={styles.content}>
          <AnimatePresence mode="wait">
            <motion.div
              key={active}
              initial={{ opacity: 0, x: 12 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -8 }}
              transition={{ duration: 0.2, ease: [0.4, 0, 0.2, 1] }}
              className={styles.panelWrap}
            >
              {active === 'system' && <SystemHealthPanel />}
              {active === 'oracle-admin' && <OracleAdminPanel />}
              {active === 'comms-config' && <CommsConfigPanel />}
              {active === 'users' && <UsersPanel />}
              {active === 'models' && <ModelHydrationPanel />}
              {active === 'meta' && <MetaIntegrationPanel />}
            </motion.div>
          </AnimatePresence>
        </main>
      </div>
    </div>
  );
}

function SystemHealthPanel() {
  const services = [
    { name: 'core-api', status: 'healthy', latency: '42ms', replicas: '2/2' },
    { name: 'webos', status: 'healthy', latency: '-', replicas: '2/2' },
    { name: 'media-engine', status: 'healthy', latency: '-', replicas: '1/1' },
    { name: 'postgres', status: 'healthy', latency: '3ms', replicas: '1/1' },
    { name: 'redis', status: 'healthy', latency: '0.4ms', replicas: '1/1' },
  ];

  return (
    <div className={styles.panel}>
      <h2 className={styles.panelTitle}>System Health</h2>
      <div className={styles.serviceGrid}>
        {services.map((svc) => (
          <div key={svc.name} className={`${styles.svcCard} glass-card`}>
            <div className={styles.svcTop}>
              <span
                className={styles.statusDot}
                style={{ background: svc.status === 'healthy' ? 'var(--color-green)' : 'var(--color-red)' }}
              />
              <code className={styles.svcName}>{svc.name}</code>
            </div>
            <div className={styles.svcMeta}>
              <span>Replicas: <code>{svc.replicas}</code></span>
              {svc.latency !== '-' && <span>Latency: <code>{svc.latency}</code></span>}
            </div>
          </div>
        ))}
      </div>

      <div className={`${styles.gpuCard} glass-card`}>
        <h3 className={styles.subTitle}>GPU · 4 x NVIDIA L4 · Shared runtime plane</h3>
        <div className={styles.migSlices}>
          <div className={styles.migSlice}>
            <span className={styles.migLabel}>LLM runtime</span>
            <code className={styles.migService}>SGLang → Qwen3.6 35B</code>
            <span className={styles.migStatus} style={{ color: 'var(--color-green)' }}>Loaded</span>
          </div>
          <div className={styles.migSlice}>
            <span className={styles.migLabel}>Media runtime</span>
            <code className={styles.migService}>ComfyUI → Dream Weaver</code>
            <span className={styles.migStatus} style={{ color: 'var(--color-green)' }}>Loaded</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function OracleAdminPanel() {
  return (
    <div className={styles.panel}>
      <h2 className={styles.panelTitle}>Oracle Administration</h2>
      <p className={styles.panelSubtitle}>
        Canvas management, schema catalog, data health, and component codebook controls.
      </p>
      <div className={styles.adminSection}>
        <h3 className={styles.subTitle}>Active Canvas Sessions</h3>
        <p className={styles.muted}>Query canvas history, fork/merge, and revision management from the Oracle page.</p>
        <button className="btn-ghost" onClick={() => window.location.assign('/oracle')}>Open Oracle Workspace</button>
      </div>
      <div className={styles.adminSection}>
        <h3 className={styles.subTitle}>Schema Catalog</h3>
        <button className="btn-ghost">Browse Schema →</button>
        <button className="btn-ghost">Run Data Health Check →</button>
      </div>
      <div className={styles.adminSection}>
        <h3 className={styles.subTitle}>Component Codebook</h3>
        <p className={styles.muted}>Project Velocity JSON schemas are loaded from the backend Oracle codebook assets.</p>
      </div>
    </div>
  );
}

function CommsConfigPanel() {
  return (
    <div className={styles.panel}>
      <h2 className={styles.panelTitle}>Comms Configuration</h2>
      <p className={styles.panelSubtitle}>WhatsApp provider setup. Never visible to broker-role users.</p>
      <div className={styles.formGroup}>
        <label className={styles.formLabel}>Provider</label>
        <select className={styles.formSelect}>
          <option value="waha">WAHA</option>
          <option value="evolution">Evolution API</option>
        </select>
      </div>
      <div className={styles.formGroup}>
        <label className={styles.formLabel}>API Base URL</label>
        <input type="text" className={styles.formInput} placeholder="https://waha.internal:3000" />
      </div>
      <div className={styles.formGroup}>
        <label className={styles.formLabel}>API Key</label>
        <input type="password" className={styles.formInput} placeholder="••••••••••••••••" />
      </div>
      <button className="btn-primary">Save Configuration</button>
    </div>
  );
}

function UsersPanel() {
  return (
    <div className={styles.panel}>
      <h2 className={styles.panelTitle}>Users & Roles</h2>
      <div className={styles.userToolbar}>
        <button className="btn-primary">+ Invite User</button>
      </div>
      <table className={styles.table}>
        <thead>
          <tr>
            <th>Name</th><th>Email</th><th>Role</th><th>Last Active</th><th></th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Sagnik</td>
            <td>sagnik@desineuron.in</td>
            <td><code>ADMIN</code></td>
            <td>Now</td>
            <td><button className={styles.tableAction}>Edit</button></td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

function ModelHydrationPanel() {
  const models = [
    { name: 'Wan / Dream Weaver media stack', size: 'GPU NVMe', status: 'synced', path: '/opt/dlami/nvme/models/comfy' },
    { name: 'Qwen3.6 35B A3B', size: 'GPU NVMe', status: 'synced', path: '/opt/dlami/nvme/models/Qwen-Qwen3.6-35B-A3B-FP8' },
    { name: 'Oracle component codebook', size: 'local', status: 'loaded', path: 'core/oracle/oracle/oracle_runtime_codebook_merged.json' },
  ];
  return (
    <div className={styles.panel}>
      <h2 className={styles.panelTitle}>Model Hydration</h2>
      <p className={styles.panelSubtitle}>NVMe-backed model store and backend component assets.</p>
      {models.map((m) => (
        <div key={m.name} className={`${styles.modelRow} glass-card`}>
          <div>
            <span className={styles.modelName}>{m.name}</span>
            <code className={styles.modelPath}>{m.path}</code>
          </div>
          <div className={styles.modelRight}>
            <span className={styles.modelSize}>{m.size}</span>
            <span style={{ color: 'var(--color-green)', fontSize: 'var(--text-xs)' }}>{m.status}</span>
            <button className="btn-ghost">Inspect</button>
          </div>
        </div>
      ))}
    </div>
  );
}

function MetaIntegrationPanel() {
  return (
    <div className={styles.panel}>
      <h2 className={styles.panelTitle}>Meta Business Integration</h2>
      <p className={styles.panelSubtitle}>OAuth, Ad Account, and Lookalike Audience configuration.</p>
      <div className={styles.metaStatus}>
        <span className={styles.statusDot} style={{ background: 'var(--color-amber)' }} />
        <span>OAuth not connected</span>
        <button className="btn-primary">Connect Meta Business</button>
      </div>
      <div className={styles.adminSection}>
        <h3 className={styles.subTitle}>Ad Account</h3>
        <input className={styles.formInput} placeholder="Meta Ad Account ID" />
      </div>
      <button className="btn-ghost">Save</button>
    </div>
  );
}
