import React, { useState, useEffect } from 'react';
import ResizablePanel from './ResizablePanel';

interface BottomPanelProps {
  leftPanelSize?: number;
  rightPanelSize?: number;
  leftPanelCollapsed?: boolean;
  rightPanelCollapsed?: boolean;
}

const BottomPanel: React.FC<BottomPanelProps> = ({
  leftPanelSize = 250,
  rightPanelSize = 300,
  leftPanelCollapsed = false,
  rightPanelCollapsed = false,
}) => {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [autoScroll, setAutoScroll] = useState(true);
  const [logs, setLogs] = useState<Array<{ level: string; message: string; timestamp: Date }>>([
    { level: 'info', message: 'System initialized', timestamp: new Date() },
    { level: 'info', message: 'Monitoring services started', timestamp: new Date() },
  ]);
  const logsContainerRef = React.useRef<HTMLDivElement>(null);

  const scrollToBottom = React.useCallback(() => {
    if (logsContainerRef.current) {
      logsContainerRef.current.scrollTop = logsContainerRef.current.scrollHeight;
    }
  }, []);

  useEffect(() => {
    if (autoScroll) {
      scrollToBottom();
    }
  }, [logs, autoScroll, scrollToBottom]);

  useEffect(() => {
    const interval = setInterval(() => {
      const levels = ['info', 'warning', 'error'];
      const messages = [
        'Deployment status updated',
        'Health check completed',
        'Metrics collected',
        'Service health changed',
      ];
      const level = levels[Math.floor(Math.random() * levels.length)];
      const message = messages[Math.floor(Math.random() * messages.length)];
      setLogs((prev) => {
        const newLogs = [...prev, { level, message, timestamp: new Date() }];
        // Limit log size
        return newLogs.length > MAX_LOGS ? newLogs.slice(-MAX_LOGS) : newLogs;
      });
    }, 5000);

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

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

  const toggleAutoScroll = () => {
    setAutoScroll((prev) => !prev);
  };

  const formatTime = (date: Date): string => {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
  };

  const exportLogs = () => {
    const logText = logs
      .map(log => `[${formatTime(log.timestamp)}] ${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 = `logs-${new Date().toISOString().split('T')[0]}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  return (
    <ResizablePanel
      position="bottom"
      defaultSize={200}
      minSize={100}
      maxSize={500}
      collapsed={isCollapsed}
      onCollapsedChange={setIsCollapsed}
      leftPanelSize={leftPanelSize}
      rightPanelSize={rightPanelSize}
      leftPanelCollapsed={leftPanelCollapsed}
      rightPanelCollapsed={rightPanelCollapsed}
    >
      <div className="bottom-panel">
        <div className="bottom-header">
          <h3 className="text-lg font-semibold">
            <i className="fas fa-terminal mr-2"></i>
            Console / Logs
          </h3>
          <div className="bottom-actions">
            <button 
              onClick={clearLogs} 
              className="action-btn" 
              title="Clear logs"
              aria-label="Clear all logs"
              type="button"
            >
              <span className="sr-only">Clear all logs</span>
              <i className="fas fa-trash" aria-hidden="true"></i>
            </button>
            <button 
              onClick={toggleAutoScroll} 
              className="action-btn" 
              title={autoScroll ? 'Disable auto-scroll' : 'Enable auto-scroll'}
              aria-label={autoScroll ? 'Disable auto-scroll' : 'Enable auto-scroll'}
              type="button"
            >
              <span className="sr-only">{autoScroll ? 'Disable auto-scroll' : 'Enable auto-scroll'}</span>
              <i className={`fas ${autoScroll ? 'fa-pause' : 'fa-play'}`} aria-hidden="true"></i>
            </button>
            <button 
              onClick={exportLogs} 
              className="action-btn" 
              title="Export logs"
              aria-label="Export logs to file"
              type="button"
            >
              <span className="sr-only">Export logs to file</span>
              <i className="fas fa-download" aria-hidden="true"></i>
            </button>
          </div>
        </div>
        
        <div 
          ref={logsContainerRef} 
          className="bottom-content"
          role="log"
          aria-live="polite"
          aria-label="Console logs"
        >
          {logs.map((log, index) => (
            <div key={`log-${index}-${log.timestamp.getTime()}`} className={`log-entry log-${log.level}`}>
              <span className="log-time">{formatTime(log.timestamp)}</span>
              <span className="log-level" aria-label={`Log level: ${log.level}`}>{log.level.toUpperCase()}</span>
              <span className="log-message">{log.message}</span>
            </div>
          ))}
          {logs.length === 0 && (
            <div className="log-empty">No logs available</div>
          )}
        </div>
      </div>
    </ResizablePanel>
  );
};

export default BottomPanel;

