import { useState } from 'react'
import { Link } from '@tanstack/react-router'
import { LogOut, UserPen, Shield } from 'lucide-react'
import { useAuth } from '@/auth/AuthContext'
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu'
import { ProfileSheet } from './ProfileSheet'

function initials(name: string): string {
  const parts = name.trim().split(/\s+/)
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase()
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase()
}

function UserAvatar({ name, avatarUrl }: { name: string; avatarUrl?: string }) {
  if (avatarUrl) {
    return (
      <img
        src={avatarUrl}
        alt={name}
        className="h-7 w-7 rounded-full object-cover border border-white/40"
      />
    )
  }
  return (
    <div
      className="h-7 w-7 rounded-full flex items-center justify-center text-[11px] font-medium text-white border border-white/40"
      style={{ background: '#F59845' }}
    >
      {initials(name)}
    </div>
  )
}

export function AppHeader() {
  const { user, signOut } = useAuth()
  const [profileOpen, setProfileOpen] = useState(false)

  return (
    <>
      <header
        style={{
          background: 'linear-gradient(135deg, #F59845 0%, #ED3E8F 100%)',
          height: 44,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          paddingLeft: 20,
          paddingRight: 20,
          flexShrink: 0,
        }}
      >
        <Link to="/" style={{ display: 'flex', alignItems: 'center' }}>
          <img
            src="/inquality-logo-white.png"
            alt="InQuality"
            style={{ height: 24, objectFit: 'contain', cursor: 'pointer' }}
          />
        </Link>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <Link
            to="/"
            style={{
              color: 'white',
              fontSize: 13,
              fontWeight: 600,
              letterSpacing: '0.04em',
              opacity: 0.92,
              textDecoration: 'none',
            }}
          >
            InQ ROI
          </Link>
          {user?.platformRole === 'platform_admin' && (
            <Link
              to="/admin"
              title="Panel de administración"
              style={{
                display: 'flex',
                alignItems: 'center',
                color: 'white',
                opacity: 0.85,
              }}
            >
              <Shield style={{ width: 18, height: 18 }} />
            </Link>
          )}
          {user && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <button className="rounded-full focus:outline-none focus:ring-2 focus:ring-white/60" title={user.name}>
                  <UserAvatar name={user.name} avatarUrl={user.avatarUrl} />
                </button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuLabel>
                  <p className="text-sm font-medium leading-tight">{user.name}</p>
                  <p className="text-xs text-muted-foreground leading-tight mt-0.5">{user.email}</p>
                  {user.company && (
                    <p className="text-xs text-muted-foreground leading-tight mt-0.5">{user.company}</p>
                  )}
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => setProfileOpen(true)}>
                  <UserPen className="h-3.5 w-3.5" />
                  Editar perfil
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => signOut()} className="text-destructive focus:text-destructive">
                  <LogOut className="h-3.5 w-3.5" />
                  Cerrar sesión
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>
      </header>

      <ProfileSheet open={profileOpen} onOpenChange={setProfileOpen} />
    </>
  )
}
