import { useState, useEffect } from 'react';

export function TitleBar() {
  const [isMaximized, setIsMaximized] = useState(false);

  useEffect(() => {
    let retries = 0;
    const maxRetries = 5;

    const checkMaximized = async () => {
      try {
        const maximized = await window.electron.ipcRenderer.invoke('window:isMaximized');
        setIsMaximized(maximized);
      } catch (error) {
        if (retries < maxRetries) {
          retries++;
          setTimeout(checkMaximized, 200 * retries);
        } else {
          console.error('Failed to check maximized state after retries:', error);
        }
      }
    };

    // Small delay to ensure handlers are registered
    const timer = setTimeout(checkMaximized, 100);
    return () => clearTimeout(timer);
  }, []);

  const handleMinimize = () => {
    window.electron.ipcRenderer.invoke('window:minimize');
  };

  const handleMaximize = async () => {
    try {
      await window.electron.ipcRenderer.invoke('window:maximize');
      const maximized = await window.electron.ipcRenderer.invoke('window:isMaximized');
      setIsMaximized(maximized);
    } catch (error) {
      console.error('Failed to maximize window:', error);
    }
  };

  const handleClose = () => {
    window.electron.ipcRenderer.invoke('window:close');
  };

  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: '40px',
        backgroundColor: '#0f1329',
        borderBottom: '1px solid #50e3c2',
        WebkitAppRegion: 'drag',
        userSelect: 'none',
        padding: '0 15px',
        position: 'sticky',
        top: 0,
        zIndex: 1000,
      } as any}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
        <div
          style={{
            width: '8px',
            height: '8px',
            borderRadius: '50%',
            backgroundColor: '#50e3c2',
            boxShadow: '0 0 8px rgba(80, 227, 194, 0.6)',
          }}
        />
        <span style={{ fontSize: '14px', fontWeight: 'bold', color: '#50e3c2' }}>
          rmtPocketWatcher
        </span>
        <span style={{ fontSize: '11px', color: '#888', marginLeft: '5px' }}>
          Lambda Banking Conglomerate
        </span>
      </div>

      <div
        style={{
          display: 'flex',
          gap: '1px',
          WebkitAppRegion: 'no-drag',
        } as any}
      >
        <button
          onClick={() => window.electron.ipcRenderer.invoke('window:hideToTray')}
          style={{
            width: '46px',
            height: '32px',
            backgroundColor: 'transparent',
            border: 'none',
            color: '#fff',
            cursor: 'pointer',
            fontSize: '14px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            transition: 'background-color 0.2s',
          }}
          onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = '#2a2f4a')}
          onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = 'transparent')}
          title="Hide to Tray"
        >
          ▼
        </button>
        <button
          onClick={handleMinimize}
          style={{
            width: '46px',
            height: '32px',
            backgroundColor: 'transparent',
            border: 'none',
            color: '#fff',
            cursor: 'pointer',
            fontSize: '16px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            transition: 'background-color 0.2s',
          }}
          onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = '#2a2f4a')}
          onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = 'transparent')}
          title="Minimize"
        >
          −
        </button>
        <button
          onClick={handleMaximize}
          style={{
            width: '46px',
            height: '32px',
            backgroundColor: 'transparent',
            border: 'none',
            color: '#fff',
            cursor: 'pointer',
            fontSize: '14px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            transition: 'background-color 0.2s',
          }}
          onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = '#2a2f4a')}
          onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = 'transparent')}
          title={isMaximized ? 'Restore' : 'Maximize'}
        >
          {isMaximized ? '❐' : '□'}
        </button>
        <button
          onClick={handleClose}
          style={{
            width: '46px',
            height: '32px',
            backgroundColor: 'transparent',
            border: 'none',
            color: '#fff',
            cursor: 'pointer',
            fontSize: '16px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            transition: 'background-color 0.2s',
          }}
          onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = '#ff6b9d')}
          onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = 'transparent')}
          title="Close"
        >
          ×
        </button>
      </div>
    </div>
  );
}
