import { useState, useEffect } from 'react'
import { useParams, Link } from 'react-router-dom'
import { Loader2, Fingerprint, Zap, Music2, CloudSun, Heart, Layers, Globe, Drama, User } from 'lucide-react'
import { getPublicProfile, type TasteProfileResponse } from '../lib/api'

const personalityIcons: Record<string, typeof Zap> = {
  zap: Zap,
  cloud: CloudSun,
  heart: Heart,
  layers: Layers,
  globe: Globe,
  drama: Drama,
  music: Music2,
}

const genreBarColors = [
  'bg-[#7C3AED]',
  'bg-[#8B5CF6]',
  'bg-[#9F6FFB]',
  'bg-[#A78BFA]',
  'bg-[#B49BFC]',
  'bg-[#C4ABFD]',
  'bg-[#D3BCFE]',
  'bg-[#DDD6FE]',
  'bg-[#E8DFFE]',
  'bg-[#F0EAFF]',
]

type PublicProfileData = TasteProfileResponse & { name: string }

function possessive(name: string): string {
  return name.endsWith('s') ? `${name}'` : `${name}'s`
}

export default function PublicProfile() {
  const { userId, token } = useParams<{ userId: string; token: string }>()
  const [profile, setProfile] = useState<PublicProfileData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!userId || !token) return
    setLoading(true)
    getPublicProfile(userId, token)
      .then(setProfile)
      .catch(() => setError('This profile link is invalid or has expired.'))
      .finally(() => setLoading(false))
  }, [userId, token])

  if (loading) {
    return (
      <div className="min-h-screen bg-[#FFF7ED] flex items-center justify-center">
        <div className="w-12 h-12 border-4 border-[#7C3AED] border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  if (error || !profile) {
    return (
      <div className="min-h-screen bg-[#FFF7ED] flex items-center justify-center p-6">
        <div className="text-center max-w-md">
          <h1 className="text-2xl font-bold text-[#1C1917] mb-2">Profile Not Found</h1>
          <p className="text-[#1C1917]/60 mb-6">{error || 'This taste profile could not be found.'}</p>
          <Link
            to="/register"
            className="inline-block px-6 py-3 bg-[#7C3AED] text-white rounded-xl font-semibold hover:bg-[#6D28D9] transition-colors no-underline"
          >
            Discover Your Taste on Vynl
          </Link>
        </div>
      </div>
    )
  }

  const PersonalityIcon = personalityIcons[profile.personality.icon] || Music2
  const maxGenrePercent = profile.genre_breakdown.length > 0
    ? Math.max(...profile.genre_breakdown.map((g) => g.percentage))
    : 100

  return (
    <div className="min-h-screen bg-[#FFF7ED] flex flex-col">
      {/* Header */}
      <header className="py-6 px-6 text-center">
        <Link to="/" className="inline-block no-underline">
          <h1 className="text-2xl font-bold text-[#7C3AED] tracking-tight">vynl</h1>
        </Link>
      </header>

      {/* Content */}
      <main className="flex-1 px-4 pb-12 max-w-3xl mx-auto w-full space-y-6">
        {/* Title */}
        <div className="text-center">
          <h2 className="text-3xl font-bold text-[#1C1917] flex items-center justify-center gap-3">
            <Fingerprint className="w-8 h-8 text-[#7C3AED]" />
            {possessive(profile.name)} Music DNA
          </h2>
          <p className="text-[#1C1917]/50 mt-1 text-sm">
            Built from {profile.track_count} tracks across {profile.playlist_count} playlists
          </p>
        </div>

        {/* Listening Personality */}
        <div className="bg-gradient-to-br from-[#7C3AED] to-[#5B21B6] rounded-2xl p-8 text-white">
          <div className="flex items-start gap-4">
            <div className="w-14 h-14 rounded-2xl bg-white/15 flex items-center justify-center flex-shrink-0">
              <PersonalityIcon className="w-7 h-7 text-white" />
            </div>
            <div>
              <p className="text-purple-200 text-xs font-semibold uppercase tracking-wider mb-1">
                Listening Personality
              </p>
              <h3 className="text-2xl font-bold mb-2">{profile.personality.label}</h3>
              <p className="text-purple-100 text-sm leading-relaxed">
                {profile.personality.description}
              </p>
            </div>
          </div>
        </div>

        {/* Genre DNA */}
        {profile.genre_breakdown.length > 0 && (
          <div className="bg-white rounded-2xl border border-[#7C3AED]/10 p-6">
            <h3 className="text-lg font-semibold text-[#1C1917] mb-5">Genre DNA</h3>
            <div className="space-y-3">
              {profile.genre_breakdown.map((genre, i) => (
                <div key={genre.name} className="flex items-center gap-3">
                  <span className="text-sm text-[#1C1917] w-28 truncate text-right flex-shrink-0 font-medium">
                    {genre.name}
                  </span>
                  <div className="flex-1 bg-[#F5F3FF] rounded-full h-6 overflow-hidden">
                    <div
                      className={`h-full rounded-full ${genreBarColors[i] || genreBarColors[genreBarColors.length - 1]} transition-all duration-700 ease-out flex items-center justify-end pr-2`}
                      style={{ width: `${(genre.percentage / maxGenrePercent) * 100}%`, minWidth: '2rem' }}
                    >
                      <span className="text-xs font-semibold text-white drop-shadow-sm">
                        {genre.percentage}%
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Audio Features */}
        <div className="bg-white rounded-2xl border border-[#7C3AED]/10 p-6">
          <h3 className="text-lg font-semibold text-[#1C1917] mb-5">Audio Features</h3>
          <div className="space-y-4">
            <PublicAudioMeter label="Energy" value={profile.audio_features.energy} />
            <PublicAudioMeter label="Danceability" value={profile.audio_features.danceability} />
            <PublicAudioMeter label="Mood / Valence" value={profile.audio_features.valence} />
            <PublicAudioMeter label="Acousticness" value={profile.audio_features.acousticness} />
            <div className="flex items-center gap-3 pt-2 border-t border-[#7C3AED]/10">
              <span className="text-sm text-[#1C1917] w-28 text-right flex-shrink-0 font-medium">
                Avg Tempo
              </span>
              <div className="flex-1 flex items-center gap-2">
                <span className="text-2xl font-bold text-[#7C3AED]">{profile.audio_features.avg_tempo}</span>
                <span className="text-sm text-[#1C1917]/50">BPM</span>
              </div>
            </div>
          </div>
        </div>

        {/* Top Artists */}
        {profile.top_artists.length > 0 && (
          <div className="bg-white rounded-2xl border border-[#7C3AED]/10 p-6">
            <h3 className="text-lg font-semibold text-[#1C1917] mb-5">Artists That Define Them</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {profile.top_artists.map((artist) => (
                <div
                  key={artist.name}
                  className="flex items-center gap-3 p-3 rounded-xl bg-[#FFF7ED]/60 border border-[#7C3AED]/5"
                >
                  <div className="w-10 h-10 rounded-full bg-[#F5F3FF] flex items-center justify-center flex-shrink-0">
                    <User className="w-5 h-5 text-[#7C3AED]" />
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-semibold text-[#1C1917] truncate">{artist.name}</p>
                    <p className="text-xs text-[#1C1917]/50">
                      {artist.track_count} track{artist.track_count !== 1 ? 's' : ''}
                      {artist.genre ? ` · ${artist.genre}` : ''}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* CTA */}
        <div className="bg-white rounded-2xl border border-[#7C3AED]/10 p-8 text-center">
          <p className="text-[#1C1917]/60 text-sm mb-4">
            Want to discover your own music DNA?
          </p>
          <Link
            to="/register"
            className="inline-block px-8 py-3.5 bg-[#7C3AED] text-white rounded-xl font-semibold hover:bg-[#6D28D9] transition-colors no-underline text-base"
          >
            Discover Your Taste on Vynl
          </Link>
        </div>
      </main>
    </div>
  )
}

function PublicAudioMeter({ label, value }: { label: string; value: number }) {
  return (
    <div className="flex items-center gap-3">
      <span className="text-sm text-[#1C1917] w-28 text-right flex-shrink-0 font-medium">
        {label}
      </span>
      <div className="flex-1 bg-[#F5F3FF] rounded-full h-5 overflow-hidden">
        <div
          className="h-full rounded-full bg-gradient-to-r from-[#7C3AED] to-[#A78BFA] transition-all duration-700 ease-out flex items-center justify-end pr-2"
          style={{ width: `${value}%`, minWidth: value > 0 ? '1.5rem' : '0' }}
        >
          {value > 10 && (
            <span className="text-xs font-semibold text-white drop-shadow-sm">
              {value}%
            </span>
          )}
        </div>
      </div>
      {value <= 10 && (
        <span className="text-xs font-medium text-[#1C1917]/50 w-10">{value}%</span>
      )}
    </div>
  )
}
