'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { loadComponent } from '@/lib/material-components';

interface TopNavigationBarProps {
  title?: string;
  user?: any;
  onLogout?: () => void;
}

export function TopNavigationBar({ title, user, onLogout }: TopNavigationBarProps) {
  const router = useRouter();
  const [componentsLoaded, setComponentsLoaded] = useState(false);

  useEffect(() => {
    Promise.all([
      loadComponent('icon-button'),
      loadComponent('icon'),
    ]).then(() => {
      setComponentsLoaded(true);
    });
  }, []);

  const handleLogout = () => {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    if (onLogout) {
      onLogout();
    } else {
      router.push('/login');
    }
  };

  if (!componentsLoaded) {
    return (
      <div style={{
        height: '64px',
        background: 'var(--md-sys-color-surface)',
        borderBottom: '1px solid var(--md-sys-color-outline-variant)',
      }} />
    );
  }

  return (
    <header style={{
      position: 'sticky',
      top: 0,
      zIndex: 999,
      background: 'var(--ios-blur-bg)',
      backdropFilter: 'var(--ios-blur)',
      WebkitBackdropFilter: 'var(--ios-blur)',
      borderBottom: '1px solid var(--md-sys-color-outline-variant)',
      padding: '12px 16px',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
        <img 
          src="/logo/logo.svg" 
          alt="Logo" 
          style={{ height: '32px', width: 'auto', cursor: 'pointer' }} 
          onClick={() => router.push('/dashboard')}
        />
        <h1 style={{
          fontSize: '20px',
          fontWeight: '500',
          color: 'var(--md-sys-color-on-surface)',
          margin: 0,
        }}>
          {title || 'Uchill Platform'}
        </h1>
      </div>

      <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
        {user && (
          <span style={{
            fontSize: '14px',
            color: 'var(--md-sys-color-on-surface-variant)',
            marginRight: '8px',
          }}>
            {user.first_name || user.email}
          </span>
        )}
        <md-icon-button onClick={handleLogout} title="Выйти">
          <md-icon>logout</md-icon>
        </md-icon-button>
      </div>
    </header>
  );
}
