import React, { useState, useEffect } from 'react';
import { useAuth } from '../../context/AuthContext';
import { useTheme } from '../../context/ThemeContext';
import { useProject } from '../../context/ProjectContext';
import { useLang } from '../../context/LanguageContext';
import { projectsService } from '../../services/projects.service';

function SunIcon() {
  return (
    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <circle cx="12" cy="12" r="5" />
      <path strokeLinecap="round" d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" />
    </svg>
  );
}

function MoonIcon() {
  return (
    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z" />
    </svg>
  );
}

const RAG_DOT = { VERDE:'bg-emerald-500', AMARILLO:'bg-amber-400', ROJO:'bg-red-500' };

export default function Navbar({ title = 'Dashboard' }) {
  const { user } = useAuth();
  const { dark, toggle } = useTheme();
  const { lang, toggleLang } = useLang();
  const { selectedProjectId, setSelectedProjectId } = useProject();
  const [projects, setProjects] = useState([]);

  useEffect(() => {
    projectsService.getAll().then(d => setProjects(d.projects || []));
  }, []);

  const selected = projects.find(p => p.id === selectedProjectId);

  return (
    <header className="h-16 flex items-center justify-between px-6 bg-white dark:bg-surface-800 border-b border-slate-200 dark:border-surface-700 transition-colors gap-4">
      <h1 className="text-lg font-semibold text-slate-900 dark:text-white flex-shrink-0">{title}</h1>

      {/* ── Global project selector ── */}
      <div className="flex items-center gap-2 flex-1 max-w-xs">
        <svg className="w-4 h-4 text-slate-400 dark:text-gray-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V7z"/>
        </svg>
        <div className="relative flex-1">
          <select
            value={selectedProjectId || ''}
            onChange={e => setSelectedProjectId(e.target.value || null)}
            className="w-full text-sm bg-slate-50 dark:bg-surface-700 border border-slate-200 dark:border-surface-600 rounded-xl px-3 py-1.5 text-slate-700 dark:text-gray-300 cursor-pointer focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500 appearance-none pr-8 transition"
          >
            <option value="">Todos los proyectos</option>
            {projects.map(p => (
              <option key={p.id} value={p.id}>{p.code} — {p.name}</option>
            ))}
          </select>
          <svg className="absolute right-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400 pointer-events-none" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7"/>
          </svg>
        </div>
        {selected && (
          <div className="flex items-center gap-1.5 flex-shrink-0">
            <div className={`w-2 h-2 rounded-full ${RAG_DOT[selected.ragStatus] || 'bg-slate-400'}`}/>
            <button onClick={() => setSelectedProjectId(null)}
              className="text-slate-300 dark:text-gray-600 hover:text-slate-600 dark:hover:text-gray-300 transition cursor-pointer"
              title="Quitar filtro">
              <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/>
              </svg>
            </button>
          </div>
        )}
      </div>

      <div className="flex items-center gap-3 flex-shrink-0">
        <span className="hidden lg:block text-xs text-slate-400 dark:text-gray-500">
          {new Date().toLocaleDateString('es-MX', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}
        </span>
        <span className="text-xs bg-blue-100 dark:bg-primary-500/20 text-blue-700 dark:text-blue-400 px-2.5 py-1 rounded-full font-medium">
          {user?.role?.replace(/_/g, ' ')}
        </span>
        <button onClick={toggleLang} title={lang === 'es' ? 'Switch to English' : 'Cambiar a Español'}
          className="w-8 h-8 flex items-center justify-center rounded-lg bg-slate-100 dark:bg-surface-700 text-slate-500 dark:text-gray-400 hover:bg-slate-200 dark:hover:bg-surface-600 hover:text-slate-700 dark:hover:text-white transition-all cursor-pointer text-xs font-bold tracking-tight">
          {lang === 'es' ? 'EN' : 'ES'}
        </button>
        <button onClick={toggle} title={dark ? 'Modo día' : 'Modo noche'}
          className="w-8 h-8 flex items-center justify-center rounded-lg bg-slate-100 dark:bg-surface-700 text-slate-500 dark:text-gray-400 hover:bg-slate-200 dark:hover:bg-surface-600 hover:text-slate-700 dark:hover:text-white transition-all cursor-pointer">
          {dark ? <SunIcon /> : <MoonIcon />}
        </button>
      </div>
    </header>
  );
}
