import { Box, Text, ScrollArea, Code, Group, ActionIcon, Badge } from '@mantine/core';
import { IconTrash, IconDownload } from '@tabler/icons-react';
import { useState, useEffect, useCallback, memo } from 'react';

interface LogEntry {
  id: string;
  timestamp: Date;
  level: 'info' | 'warning' | 'error' | 'success';
  message: string;
}

interface ConsoleDockProps {
  onLogAdd?: (log: LogEntry) => void;
}

function ConsoleDockComponent({ onLogAdd }: ConsoleDockProps) {
  const [logs, setLogs] = useState<LogEntry[]>([
    {
      id: '1',
      timestamp: new Date(),
      level: 'info',
      message: 'Aplicación iniciada correctamente'
    },
    {
      id: '2',
      timestamp: new Date(Date.now() - 5000),
      level: 'success',
      message: 'Dockview configurado exitosamente'
    },
    {
      id: '3',
      timestamp: new Date(Date.now() - 10000),
      level: 'warning',
      message: 'Algunos componentes están en desarrollo'
    }
  ]);

  const addLog = (level: LogEntry['level'], message: string) => {
    const newLog: LogEntry = {
      id: Date.now().toString(),
      timestamp: new Date(),
      level,
      message
    };
    setLogs(prev => [newLog, ...prev]);
    onLogAdd?.(newLog);
  };

  const clearLogs = () => {
    setLogs([]);
  };

  const exportLogs = () => {
    const logText = logs.map(log =>
      `[${log.timestamp.toISOString()}] ${log.level.toUpperCase()}: ${log.message}`
    ).join('\n');

    const blob = new Blob([logText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'console-logs.txt';
    a.click();
    URL.revokeObjectURL(url);
  };

  const getLogColor = (level: LogEntry['level']) => {
    switch (level) {
      case 'error': return 'red';
      case 'warning': return 'yellow';
      case 'success': return 'green';
      default: return 'blue';
    }
  };

  // Simular algunos logs automáticos
  useEffect(() => {
    const interval = setInterval(() => {
      const messages = [
        { level: 'info' as const, message: 'Actualizando estado de componentes...' },
        { level: 'success' as const, message: 'Datos sincronizados correctamente' },
        { level: 'warning' as const, message: 'Conexión lenta detectada' },
      ];
      const randomMessage = messages[Math.floor(Math.random() * messages.length)];
      if (Math.random() > 0.8) { // 20% de probabilidad
        addLog(randomMessage.level, randomMessage.message);
      }
    }, 3000);

    return () => clearInterval(interval);
  }, []);

  return (
    <Box p="md" h="100%">
      <Group justify="space-between" mb="md">
        <Text size="lg" fw={600}>Consola</Text>
        <Group gap="xs">
          <ActionIcon onClick={exportLogs} variant="light" size="sm">
            <IconDownload size={14} />
          </ActionIcon>
          <ActionIcon onClick={clearLogs} variant="light" color="red" size="sm">
            <IconTrash size={14} />
          </ActionIcon>
        </Group>
      </Group>

      <ScrollArea h="calc(100% - 60px)" type="auto">
        {logs.length === 0 ? (
          <Text c="dimmed" ta="center" mt="xl">No hay logs disponibles</Text>
        ) : (
          logs.map((log) => (
            <Box key={log.id} mb="xs" p="xs" style={{
              border: '1px solid #e0e0e0',
              borderRadius: '4px',
              borderLeftColor: getLogColor(log.level),
              borderLeftWidth: '4px'
            }}>
              <Group justify="space-between" mb="xs">
                <Badge size="xs" color={getLogColor(log.level)}>
                  {log.level.toUpperCase()}
                </Badge>
                <Text size="xs" c="dimmed">
                  {log.timestamp.toLocaleTimeString()}
                </Text>
              </Group>
              <Code block style={{ backgroundColor: 'transparent', border: 'none', padding: 0 }}>
                {log.message}
              </Code>
            </Box>
          ))
        )}
      </ScrollArea>
    </Box>
  );
}

export const ConsoleDock = memo(ConsoleDockComponent);