'use client';

import React from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import styles from './Header.module.css';

interface HeaderProps {
  activeTab: 'plans' | 'goals' | 'import' | 'none';
}

export default function Header({ activeTab }: HeaderProps) {
  const router = useRouter();
  const [role, setRole] = React.useState<string | null>(null);

  React.useEffect(() => {
    fetch('/api/auth/me')
      .then(res => {
        if (res.ok) return res.json();
        throw new Error('Not authenticated');
      })
      .then(data => {
        setRole(data.user?.role || null);
      })
      .catch(err => {
        console.error('Failed to get session user details', err);
      });
  }, []);

  const handleLogout = async () => {
    try {
      await fetch('/api/auth/logout', { method: 'POST' });
      router.push('/login');
      router.refresh();
    } catch (err) {
      console.error('Failed to log out', err);
    }
  };

  const showImportLink = role === 'admin' || role === 'analyst' || role === 'commercial_leader';

  return (
    <header className={styles.header}>
      <div className={styles.logoArea}>
        <span className={styles.logoText}>Remuneración Estelar</span>
      </div>
      <nav className={styles.nav}>
        <Link
          href="/plans"
          className={`${styles.navLink} ${activeTab === 'plans' ? styles.navLinkActive : ''}`}
        >
          Planes de Comisión
        </Link>
        <Link
          href="/goals"
          className={`${styles.navLink} ${activeTab === 'goals' ? styles.navLinkActive : ''}`}
        >
          Metas Comerciales
        </Link>
        {showImportLink && (
          <Link
            href="/sales/import"
            className={`${styles.navLink} ${activeTab === 'import' ? styles.navLinkActive : ''}`}
            id="nav-import-sales"
          >
            Cargar Ventas
          </Link>
        )}
      </nav>
      <button onClick={handleLogout} className={styles.logoutBtn}>
        Cerrar Sesión
      </button>
    </header>
  );
}
