'use client'

import { createClient } from '@/lib/supabase/client'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { useState } from 'react'

interface UserNavProps {
  email: string
  planName?: string
}

export function UserNav({ email, planName }: UserNavProps) {
  const [loading, setLoading] = useState(false)
  const router = useRouter()
  const supabase = createClient()

  async function handleSignOut() {
    setLoading(true)
    await supabase.auth.signOut()
    router.push('/login')
    router.refresh()
  }

  // Get initials from email
  const initials = email
    .split('@')[0]
    .split(/[._-]/)
    .slice(0, 2)
    .map(part => part.charAt(0).toUpperCase())
    .join('')

  return (
    <div className="flex items-center gap-4">
      {/* Avatar */}
      <div className="w-9 h-9 bg-ink flex items-center justify-center">
        <span className="text-cream text-sm font-medium">{initials}</span>
      </div>

      {/* Info */}
      <div className="hidden sm:block text-sm text-right">
        <p className="font-medium text-ink">{email}</p>
        {planName && (
          <p className="text-ink-muted text-xs">Piano {planName}</p>
        )}
      </div>

      {/* Logout button */}
      <Button
        variant="ghost"
        size="sm"
        onClick={handleSignOut}
        disabled={loading}
        className="text-ink-light hover:text-ink"
      >
        {loading ? 'Uscita...' : 'Esci'}
      </Button>
    </div>
  )
}
