import { useState, useEffect, useRef } from 'react';
import { socketClient } from '../lib/socket';

export type ConnectionStatus = 'connected' | 'connecting' | 'error' | 'disconnected';

interface StatusBarProps {
  statusMessage?: string;
  projectSlug?: string | null;
  sessionMode?: string;
}

function ConnectionIndicator({ status }: { status: ConnectionStatus }) {
  const statusStyles = {
    connected: 'text-green-500 animate-pulse',
    connecting: 'text-yellow-500',
    error: 'text-red-500 animate-pulse',
    disconnected: 'text-gray-600',
  };

  const statusIcons = {
    connected: '●',
    connecting: '●',
    error: '●',
    disconnected: '●',
  };

  return (
    <span className={`${statusStyles[status]} text-lg leading-none`}>
      {statusIcons[status]}
    </span>
  );
}

export default function StatusBar({ statusMessage = 'Ready.', projectSlug, sessionMode }: StatusBarProps) {
  const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('disconnected');
  const [displayMessage, setDisplayMessage] = useState<string>(statusMessage);
  const clearTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (clearTimerRef.current) {
      clearTimeout(clearTimerRef.current);
    }

    setDisplayMessage(statusMessage);
    clearTimerRef.current = setTimeout(() => {
      setDisplayMessage('');
    }, 10000);

    return () => {
      if (clearTimerRef.current) {
        clearTimeout(clearTimerRef.current);
      }
    };
  }, [statusMessage]);

  useEffect(() => {
    const updateStatus = () => {
      if (socketClient.connected) {
        setConnectionStatus('connected');
      } else {
        setConnectionStatus('disconnected');
      }
    };

    updateStatus();

    socketClient.on('connect', updateStatus);
    socketClient.on('disconnect', updateStatus);
    socketClient.on('error', () => setConnectionStatus('error'));

    return () => {
      socketClient.off('connect', updateStatus);
      socketClient.off('disconnect', updateStatus);
      socketClient.off('error', updateStatus);
    };
  }, []);

  return (
    <footer className="h-status flex items-center justify-between px-4 bg-bg-secondary border-t border-border-subtle text-sm text-text-muted shrink-0">
      <div className="flex-1 truncate">
        {displayMessage}
      </div>

      <div className="flex items-center gap-4">
        {projectSlug && (
          <span className="text-text-secondary">{projectSlug}</span>
        )}
        {sessionMode && (
          <span className="text-text-secondary font-mono">{sessionMode}</span>
        )}
        <ConnectionIndicator status={connectionStatus} />
      </div>
    </footer>
  );
}