import { useState, useEffect, useCallback } from 'react';

// Helper function for random values
const rand = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;
const randFloat = (min: number, max: number) => (Math.random() * (max - min) + min).toFixed(1);

// Types for security data
export interface SecurityEvent {
  id: string;
  time: string;
  event: string;
  severity: 'info' | 'warning' | 'critical';
  source?: string;
}

export interface ThreatData {
  level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  score: number;
  activeThreats: number;
  blockedAttacks: number;
  lastIncident: string;
}

export interface SOCMetrics {
  activeIncidents: number;
  criticalAlerts: number;
  warningAlerts: number;
  infoAlerts: number;
  resolvedToday: number;
  mttd: number;
  mttr: number;
}

export interface NetworkMetrics {
  inboundGbps: number;
  outboundGbps: number;
  packetsPerSec: number;
  activeConnections: number;
  blockedIPs: number;
  ddosStatus: 'normal' | 'elevated' | 'attack';
}

export interface MalwareMetrics {
  detected24h: number;
  ransomware: number;
  trojans: number;
  quarantined: number;
  cleaned: number;
}

export interface FirewallMetrics {
  status: 'active' | 'degraded' | 'offline';
  blocked24h: number;
  allowed24h: number;
  rulesActive: number;
  lastUpdate: string;
}

// Event generators
const eventTemplates = {
  critical: [
    'Ransomware detected on endpoint WKS-{id}',
    'Brute force attack from {ip}',
    'Zero-day exploit attempt detected',
    'Data exfiltration detected to {ip}',
    'Privilege escalation on SRV-{id}',
    'C2 communication blocked',
    'Credential theft attempt detected',
    'SQL injection attack on /api/users',
  ],
  warning: [
    'Multiple failed logins from {ip}',
    'Unusual outbound traffic pattern',
    'New device connected: {device}',
    'Anomalous user behavior: {user}',
    'Port scan detected from {ip}',
    'Suspicious DNS query to {domain}',
    'Certificate expiring in {days} days',
    'High CPU usage on firewall node',
  ],
  info: [
    'Security scan completed successfully',
    'Signature database updated',
    'User {user} logged in from new location',
    'Backup verification complete',
    'Policy update applied',
    'Scheduled vulnerability scan started',
    'System health check passed',
    'New IOC feed synchronized',
  ],
};

const generateIP = () => `${rand(1, 223)}.${rand(0, 255)}.${rand(0, 255)}.${rand(1, 254)}`;
const generateEvent = (severity: 'info' | 'warning' | 'critical'): SecurityEvent => {
  const templates = eventTemplates[severity];
  let event = templates[rand(0, templates.length - 1)];
  
  event = event
    .replace('{id}', String(rand(1, 99)).padStart(2, '0'))
    .replace('{ip}', generateIP())
    .replace('{device}', `Device-${rand(100, 999)}`)
    .replace('{user}', ['admin', 'john.doe', 'api-service', 'backup-svc'][rand(0, 3)])
    .replace('{domain}', ['suspicious.xyz', 'malware.io', 'c2server.net'][rand(0, 2)])
    .replace('{days}', String(rand(5, 30)));

  const now = new Date();
  return {
    id: `evt-${Date.now()}-${rand(1000, 9999)}`,
    time: `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`,
    event,
    severity,
    source: generateIP(),
  };
};

// Main hook
export const useSecuritySimulation = (updateInterval = 3000) => {
  const [threatData, setThreatData] = useState<ThreatData>({
    level: 'LOW',
    score: rand(15, 35),
    activeThreats: rand(0, 3),
    blockedAttacks: rand(800, 1500),
    lastIncident: '2h ago',
  });

  const [socMetrics, setSOCMetrics] = useState<SOCMetrics>({
    activeIncidents: rand(2, 5),
    criticalAlerts: rand(1, 3),
    warningAlerts: rand(8, 15),
    infoAlerts: rand(30, 60),
    resolvedToday: rand(35, 55),
    mttd: parseFloat(randFloat(3, 6)),
    mttr: rand(15, 25),
  });

  const [networkMetrics, setNetworkMetrics] = useState<NetworkMetrics>({
    inboundGbps: parseFloat(randFloat(1.5, 3.5)),
    outboundGbps: parseFloat(randFloat(1.0, 2.5)),
    packetsPerSec: rand(800000, 1400000),
    activeConnections: rand(10000, 50000),
    blockedIPs: rand(10000, 15000),
    ddosStatus: 'normal',
  });

  const [malwareMetrics, setMalwareMetrics] = useState<MalwareMetrics>({
    detected24h: rand(40, 80),
    ransomware: rand(1, 5),
    trojans: rand(8, 20),
    quarantined: rand(30, 60),
    cleaned: rand(20, 40),
  });

  const [firewallMetrics, setFirewallMetrics] = useState<FirewallMetrics>({
    status: 'active',
    blocked24h: rand(1000, 2000),
    allowed24h: rand(40000, 60000),
    rulesActive: rand(2000, 3000),
    lastUpdate: 'Just now',
  });

  const [events, setEvents] = useState<SecurityEvent[]>([
    generateEvent('critical'),
    generateEvent('warning'),
    generateEvent('info'),
  ]);

  const [liveAttacks, setLiveAttacks] = useState(rand(700, 1000));
  const [vpnUsers, setVpnUsers] = useState(rand(200, 300));
  const [complianceScore, setComplianceScore] = useState(rand(82, 95));

  // Update functions
  const updateThreatData = useCallback(() => {
    setThreatData(prev => {
      const newScore = Math.max(0, Math.min(100, prev.score + rand(-5, 5)));
      const newLevel: ThreatData['level'] = 
        newScore > 75 ? 'CRITICAL' : 
        newScore > 50 ? 'HIGH' : 
        newScore > 25 ? 'MEDIUM' : 'LOW';
      
      return {
        ...prev,
        score: newScore,
        level: newLevel,
        activeThreats: Math.max(0, prev.activeThreats + rand(-1, 1)),
        blockedAttacks: prev.blockedAttacks + rand(1, 10),
      };
    });
  }, []);

  const updateSOCMetrics = useCallback(() => {
    setSOCMetrics(prev => ({
      ...prev,
      activeIncidents: Math.max(0, prev.activeIncidents + rand(-1, 2)),
      criticalAlerts: Math.max(0, prev.criticalAlerts + rand(-1, 1)),
      warningAlerts: Math.max(0, prev.warningAlerts + rand(-2, 3)),
      resolvedToday: prev.resolvedToday + rand(0, 2),
      mttd: parseFloat(randFloat(3, 6)),
      mttr: rand(12, 30),
    }));
  }, []);

  const updateNetworkMetrics = useCallback(() => {
    setNetworkMetrics(prev => {
      const ddosChance = Math.random();
      return {
        ...prev,
        inboundGbps: parseFloat(randFloat(1.5, 4.0)),
        outboundGbps: parseFloat(randFloat(1.0, 3.0)),
        packetsPerSec: rand(700000, 1500000),
        activeConnections: rand(8000, 55000),
        blockedIPs: prev.blockedIPs + rand(1, 5),
        ddosStatus: ddosChance > 0.95 ? 'attack' : ddosChance > 0.85 ? 'elevated' : 'normal',
      };
    });
  }, []);

  const updateMalwareMetrics = useCallback(() => {
    setMalwareMetrics(prev => ({
      ...prev,
      detected24h: Math.max(0, prev.detected24h + rand(-2, 5)),
      ransomware: Math.max(0, prev.ransomware + rand(-1, 1)),
      trojans: Math.max(0, prev.trojans + rand(-1, 2)),
      quarantined: prev.quarantined + rand(0, 3),
      cleaned: prev.cleaned + rand(0, 2),
    }));
  }, []);

  const updateFirewallMetrics = useCallback(() => {
    setFirewallMetrics(prev => ({
      ...prev,
      blocked24h: prev.blocked24h + rand(1, 15),
      allowed24h: prev.allowed24h + rand(10, 50),
      lastUpdate: 'Just now',
    }));
  }, []);

  const addNewEvent = useCallback(() => {
    const severityRoll = Math.random();
    const severity: 'info' | 'warning' | 'critical' = 
      severityRoll > 0.95 ? 'critical' : 
      severityRoll > 0.7 ? 'warning' : 'info';
    
    const newEvent = generateEvent(severity);
    setEvents(prev => [newEvent, ...prev].slice(0, 20));
  }, []);

  // Main update effect
  useEffect(() => {
    const interval = setInterval(() => {
      updateThreatData();
      updateSOCMetrics();
      updateNetworkMetrics();
      updateMalwareMetrics();
      updateFirewallMetrics();
      
      // 30% chance to add a new event
      if (Math.random() > 0.7) {
        addNewEvent();
      }

      setLiveAttacks(prev => Math.max(500, Math.min(1500, prev + rand(-50, 50))));
      setVpnUsers(prev => Math.max(100, Math.min(400, prev + rand(-10, 10))));
      setComplianceScore(prev => Math.max(75, Math.min(100, prev + rand(-1, 1))));
    }, updateInterval);

    return () => clearInterval(interval);
  }, [updateInterval, updateThreatData, updateSOCMetrics, updateNetworkMetrics, updateMalwareMetrics, updateFirewallMetrics, addNewEvent]);

  return {
    threatData,
    socMetrics,
    networkMetrics,
    malwareMetrics,
    firewallMetrics,
    events,
    liveAttacks,
    vpnUsers,
    complianceScore,
    addNewEvent,
  };
};

// Context for sharing simulation data across widgets
import { createContext, useContext, ReactNode } from 'react';

interface SecuritySimulationContextType {
  threatData: ThreatData;
  socMetrics: SOCMetrics;
  networkMetrics: NetworkMetrics;
  malwareMetrics: MalwareMetrics;
  firewallMetrics: FirewallMetrics;
  events: SecurityEvent[];
  liveAttacks: number;
  vpnUsers: number;
  complianceScore: number;
}

const SecuritySimulationContext = createContext<SecuritySimulationContextType | null>(null);

export const SecuritySimulationProvider = ({ children }: { children: ReactNode }) => {
  const simulation = useSecuritySimulation(2000);
  
  return (
    <SecuritySimulationContext.Provider value={simulation}>
      {children}
    </SecuritySimulationContext.Provider>
  );
};

export const useSecurityData = () => {
  const context = useContext(SecuritySimulationContext);
  if (!context) {
    throw new Error('useSecurityData must be used within SecuritySimulationProvider');
  }
  return context;
};

