import { Outlet, NavLink, useNavigate } from 'react-router-dom';
import { useEffect, useRef } from 'react';
import { useAuthStore } from '../store/auth';
import { useOnlineStatus } from '../hooks/useOnlineStatus';
import { useOfflineQueue } from '../hooks/useOfflineQueue';
import api from '../api/client';
import toast from 'react-hot-toast';

// ─── Icônes ─────────────────────────────────────────────────

function IconPlus({ active }: { active: boolean }) {
  return (
    <svg className={`w-6 h-6 ${active ? 'text-indigo-600' : 'text-gray-400'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
    </svg>
  );
}

function IconList({ active }: { active: boolean }) {
  return (
    <svg className={`w-6 h-6 ${active ? 'text-indigo-600' : 'text-gray-400'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
    </svg>
  );
}

function IconSettings({ active }: { active: boolean }) {
  return (
    <svg className={`w-6 h-6 ${active ? 'text-indigo-600' : 'text-gray-400'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
      <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
    </svg>
  );
}

// ─── Layout principal ────────────────────────────────────────

export default function Layout() {
  const { user, refreshToken, logout } = useAuthStore();
  const navigate   = useNavigate();
  const isOnline   = useOnlineStatus();
  const { count: queueCount, processing, processQueue } = useOfflineQueue();

  // Auto-traitement de la file dès la reconnexion
  const wasOnline = useRef(isOnline);
  useEffect(() => {
    if (!wasOnline.current && isOnline) {
      // Petite temporisation pour laisser le réseau se stabiliser
      const timer = setTimeout(() => processQueue(), 2000);
      return () => clearTimeout(timer);
    }
    wasOnline.current = isOnline;
  }, [isOnline, processQueue]);

  async function handleLogout() {
    try {
      await api.post('/auth/logout', { refreshToken });
    } catch {
      // Ignore silencieusement
    }
    logout();
    navigate('/login', { replace: true });
  }

  const navLinkClass = ({ isActive }: { isActive: boolean }) =>
    `flex flex-col items-center gap-0.5 py-2 px-4 min-w-[64px] transition-colors ${
      isActive ? 'text-indigo-600' : 'text-gray-400'
    }`;

  return (
    <div className="flex flex-col min-h-screen bg-gray-50">

      {/* ── Header ── */}
      <header className="sticky top-0 z-40 bg-white border-b border-gray-100 shadow-sm">
        <div className="max-w-2xl mx-auto px-4 h-14 flex items-center justify-between">
          <span className="font-bold text-gray-900 text-lg">NotesFrais</span>

          <div className="flex items-center gap-3">
            {/* Traitement file en cours */}
            {processing && (
              <span className="inline-flex items-center gap-1 text-xs bg-indigo-100 text-indigo-700 px-2 py-1 rounded-full font-medium">
                <svg className="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"/>
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
                </svg>
                Envoi…
              </span>
            )}

            {/* Indicateur hors ligne */}
            {!isOnline && (
              <span className="inline-flex items-center gap-1 text-xs bg-amber-100 text-amber-700 px-2 py-1 rounded-full font-medium">
                <span className="w-1.5 h-1.5 rounded-full bg-amber-500 inline-block" />
                Hors ligne
                {queueCount > 0 && (
                  <span className="ml-0.5 bg-amber-500 text-white rounded-full px-1 text-[10px] font-bold">
                    {queueCount}
                  </span>
                )}
              </span>
            )}

            {/* Nom utilisateur + déconnexion */}
            <div className="flex items-center gap-2">
              <span className="text-sm text-gray-600 font-medium">{user?.name}</span>
              <button
                onClick={handleLogout}
                className="p-1.5 rounded-lg text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors"
                title="Se déconnecter"
              >
                <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* ── Contenu principal ── */}
      <main className="flex-1 max-w-2xl w-full mx-auto px-4 py-6 pb-24">
        <Outlet />
      </main>

      {/* ── Barre de navigation du bas ── */}
      <nav className="fixed bottom-0 left-0 right-0 z-40 bg-white border-t border-gray-100 shadow-[0_-1px_3px_rgba(0,0,0,0.06)]"
           style={{ paddingBottom: 'env(safe-area-inset-bottom)' }}>
        <div className="max-w-2xl mx-auto flex justify-around items-center">

          <NavLink to="/new" className={navLinkClass}>
            {({ isActive }) => (
              <>
                <IconPlus active={isActive} />
                <span className={`text-xs font-medium ${isActive ? 'text-indigo-600' : 'text-gray-400'}`}>
                  Nouvelle
                </span>
              </>
            )}
          </NavLink>

          <NavLink to="/invoices" className={navLinkClass}>
            {({ isActive }) => (
              <>
                <div className="relative">
                  <IconList active={isActive} />
                  {queueCount > 0 && (
                    <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-0.5 rounded-full bg-red-500
                                     text-white text-[10px] font-bold flex items-center justify-center">
                      {queueCount > 9 ? '9+' : queueCount}
                    </span>
                  )}
                </div>
                <span className={`text-xs font-medium ${isActive ? 'text-indigo-600' : 'text-gray-400'}`}>
                  Mes factures
                </span>
              </>
            )}
          </NavLink>

          <NavLink to="/settings" className={navLinkClass}>
            {({ isActive }) => (
              <>
                <IconSettings active={isActive} />
                <span className={`text-xs font-medium ${isActive ? 'text-indigo-600' : 'text-gray-400'}`}>
                  Paramètres
                </span>
              </>
            )}
          </NavLink>

        </div>
      </nav>

    </div>
  );
}
