'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useSession, signOut } from 'next-auth/react';
import { useTheme } from '@/contexts/ThemeContext';
import { useState, useRef } from 'react';
import { Avatar, RocketIcon } from '@/components/ui';
import { WORKSHOPS } from '@/lib/workshops';
import { useClickOutside } from '@/hooks/useClickOutside';

export function Header() {
  const { theme, toggleTheme } = useTheme();
  const { data: session, status } = useSession();
  const [menuOpen, setMenuOpen] = useState(false);
  const [workshopsOpen, setWorkshopsOpen] = useState(false);
  const workshopsDropdownRef = useRef<HTMLDivElement>(null);
  const userMenuRef = useRef<HTMLDivElement>(null);
  useClickOutside(workshopsDropdownRef, () => setWorkshopsOpen(false), workshopsOpen);
  useClickOutside(userMenuRef, () => setMenuOpen(false), menuOpen);
  const pathname = usePathname();

  const isActiveLink = (path: string) => pathname.startsWith(path);

  return (
    <header className="sticky top-0 z-50 border-b border-border bg-card/80 backdrop-blur-sm">
      <div className="mx-auto flex h-16 max-w-7xl items-center justify-between px-4">
        <Link href="/" className="flex items-center gap-2">
          <RocketIcon className="h-7 w-7 shrink-0 text-primary" />
          <span className="text-xl font-bold text-foreground">Workshop Manager</span>
        </Link>

        <nav className="flex items-center gap-4">
          {status === 'authenticated' && session?.user && (
            <>
              {/* All Workshops Link */}
              <Link
                href="/sessions"
                className={`text-sm font-medium transition-colors ${
                  isActiveLink('/sessions') && !isActiveLink('/sessions/')
                    ? 'text-primary'
                    : 'text-muted hover:text-foreground'
                }`}
              >
                Mes Ateliers
              </Link>

              {/* Objectives Link */}
              <Link
                href="/objectives"
                className={`text-sm font-medium transition-colors ${
                  isActiveLink('/objectives') ? 'text-primary' : 'text-muted hover:text-foreground'
                }`}
              >
                🎯 Mes Objectifs
              </Link>

              {/* Teams Link */}
              <Link
                href="/teams"
                className={`text-sm font-medium transition-colors ${
                  isActiveLink('/teams') ? 'text-primary' : 'text-muted hover:text-foreground'
                }`}
              >
                👥 Équipes
              </Link>

              {/* New Workshop Dropdown */}
              <div className="relative" ref={workshopsDropdownRef}>
                <button
                  onClick={() => setWorkshopsOpen(!workshopsOpen)}
                  className={`flex items-center gap-1 text-sm font-medium transition-colors ${
                    WORKSHOPS.some((w) => isActiveLink(w.path))
                      ? 'text-primary'
                      : 'text-muted hover:text-foreground'
                  }`}
                >
                  Nouvel atelier
                  <svg
                    className={`h-4 w-4 transition-transform ${workshopsOpen ? 'rotate-180' : ''}`}
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M19 9l-7 7-7-7"
                    />
                  </svg>
                </button>

                {workshopsOpen && (
                  <div className="absolute left-0 z-20 mt-2 w-56 rounded-lg border border-border bg-card py-1 shadow-lg">
                    {WORKSHOPS.map((w) => (
                      <Link
                        key={w.id}
                        href={w.newPath}
                        className="flex items-center gap-3 px-4 py-2.5 text-sm text-foreground hover:bg-card-hover"
                        onClick={() => setWorkshopsOpen(false)}
                      >
                        <span className="text-lg">{w.icon}</span>
                        <div>
                          <div className="font-medium">{w.label}</div>
                          <div className="text-xs text-muted">{w.description}</div>
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </div>
            </>
          )}

          <button
            onClick={toggleTheme}
            className="flex h-9 w-9 items-center justify-center rounded-lg border border-border bg-card text-lg transition-colors hover:bg-card-hover"
            aria-label="Toggle theme"
          >
            {theme === 'light' ? '🌙' : '☀️'}
          </button>

          {status === 'loading' ? (
            <div className="h-9 w-20 animate-pulse rounded-lg bg-card-hover" />
          ) : status === 'authenticated' && session?.user ? (
            <div ref={userMenuRef} className="relative">
              <button
                onClick={() => setMenuOpen(!menuOpen)}
                className="flex h-9 items-center gap-2 rounded-lg border border-border bg-card pl-1.5 pr-3 transition-colors hover:bg-card-hover"
              >
                <Avatar email={session.user.email!} name={session.user.name} size={24} />
                <span className="text-sm font-medium text-foreground">
                  {session.user.name || session.user.email?.split('@')[0]}
                </span>
                <svg
                  className={`h-4 w-4 text-muted transition-transform ${menuOpen ? 'rotate-180' : ''}`}
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M19 9l-7 7-7-7"
                  />
                </svg>
              </button>

              {menuOpen && (
                <div className="absolute right-0 z-20 mt-2 w-48 rounded-lg border border-border bg-card py-1 shadow-lg">
                    <div className="border-b border-border px-4 py-2">
                      <p className="text-xs text-muted">Connecté en tant que</p>
                      <p className="truncate text-sm font-medium text-foreground">
                        {session.user.email}
                      </p>
                    </div>
                    <Link
                      href="/profile"
                      onClick={() => setMenuOpen(false)}
                      className="block w-full px-4 py-2 text-left text-sm text-foreground hover:bg-card-hover"
                    >
                      👤 Mon Profil
                    </Link>
                    <Link
                      href="/users"
                      onClick={() => setMenuOpen(false)}
                      className="block w-full px-4 py-2 text-left text-sm text-foreground hover:bg-card-hover"
                    >
                      👥 Utilisateurs
                    </Link>
                    <button
                      onClick={() => signOut({ callbackUrl: '/' })}
                      className="w-full px-4 py-2 text-left text-sm text-destructive hover:bg-card-hover"
                    >
                      Se déconnecter
                    </button>
                  </div>
              )}
            </div>
          ) : (
            <Link
              href="/login"
              className="flex h-9 items-center rounded-lg bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary-hover"
            >
              Connexion
            </Link>
          )}
        </nav>
      </div>
    </header>
  );
}
