import React from 'react';
import { Box, Text, useInput, useApp } from 'ink';
import { useMonitorLogic } from './monitor/use-monitor-logic.js';
import { SystemStatus } from './monitor/system-status.js';
import { ActiveMission } from './monitor/active-mission.js';
import { DaemonFeed } from './monitor/daemon-feed.js';
import { CommandBar } from './monitor/command-bar.js';
import { NexusAlerts } from './monitor/nexus-alerts.js';
import { PredictiveInsights } from './monitor/predictive-insights.js';

interface DashboardProps {
    projectId: string;
}

export const Dashboard: React.FC<DashboardProps> = ({ projectId }) => {
    const { exit } = useApp();
    const { state, command, setCommand, handleCommandSubmit, pendingDestructive } = useMonitorLogic(projectId);
    const secureMode = pendingDestructive !== null;

    useInput((input, key) => {
        if (input === 'q' || (key.ctrl && input === 'c')) exit();
    });

    return (
        <Box flexDirection="column" padding={1}>
            {/* ── Header ─────────────────────────────────────────────── */}
            <Box justifyContent="space-between" marginBottom={1}>
                <Box gap={2}>
                    <Text bold color="magenta">🚀 RIGSTATE MONITOR</Text>
                    <Text dimColor>v2.0</Text>
                    <Text dimColor>│</Text>
                    <Text dimColor color="cyan">{state.projectId.substring(0, 8)}…</Text>
                </Box>
                <Box gap={2}>
                    <Text color="yellow">{state.time}</Text>
                    <Text dimColor>q to quit</Text>
                </Box>
            </Box>

            {/* ── Nexus Alerts (Global Hive Signals) ─────────────────── */}
            <NexusAlerts alerts={state.nexusAlerts || []} />

            {/* ── Predictive Insights (Entropy tracking) ─────────────── */}
            <PredictiveInsights insights={state.systemInsights || []} />

            {/* ── Quadrant Row: System Status + Active Mission ────────── */}
            <Box gap={1} marginBottom={1}>
                <Box width="35%">
                    <SystemStatus state={state} />
                </Box>
                <Box flexGrow={1}>
                    <ActiveMission state={state} />
                </Box>
            </Box>

            {/* ── Daemon Feed ─────────────────────────────────────────── */}
            <Box marginBottom={1}>
                <DaemonFeed logs={state.logs} secureMode={secureMode} />
            </Box>

            {/* ── Command Bar ─────────────────────────────────────────── */}
            <CommandBar
                value={command}
                onChange={setCommand}
                onSubmit={handleCommandSubmit}
                secureMode={secureMode}
            />
        </Box>
    );
};
