import { useState, useEffect } from 'react'
import { Loader2, Fingerprint, Zap, Music2, CloudSun, Heart, Layers, Globe, Drama, User } from 'lucide-react'
import { getTasteProfile, 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]',
]

export default function TasteProfilePage() {
  const [profile, setProfile] = useState<TasteProfileResponse | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    getTasteProfile()
      .then(setProfile)
      .catch(() => setProfile(null))
      .finally(() => setLoading(false))
  }, [])

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-8 h-8 text-purple animate-spin" />
      </div>
    )
  }

  if (!profile) {
    return (
      <div className="text-center py-20">
        <p className="text-charcoal-muted">Could not load your taste profile.</p>
      </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="space-y-8 max-w-3xl mx-auto">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold text-charcoal flex items-center gap-3">
          <Fingerprint className="w-8 h-8 text-purple" />
          My Taste DNA
        </h1>
        <p className="text-charcoal-muted mt-1">
          Your musical identity, decoded from {profile.track_count} tracks across {profile.playlist_count} playlists
        </p>
      </div>

      {/* Listening Personality */}
      <div className="bg-gradient-to-br from-purple to-purple-dark 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">
              Your Listening Personality
            </p>
            <h2 className="text-2xl font-bold mb-2">{profile.personality.label}</h2>
            <p className="text-purple-100 text-sm leading-relaxed">
              {profile.personality.description}
            </p>
          </div>
        </div>
      </div>

      {/* Genre DNA */}
      <div className="bg-white rounded-2xl border border-purple-100 p-6">
        <h2 className="text-lg font-semibold text-charcoal mb-5">Genre DNA</h2>
        {profile.genre_breakdown.length === 0 ? (
          <p className="text-charcoal-muted text-sm">
            No genre data yet. Import playlists to see your genre breakdown.
          </p>
        ) : (
          <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-charcoal w-28 truncate text-right flex-shrink-0 font-medium">
                  {genre.name}
                </span>
                <div className="flex-1 bg-purple-50 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 Feature Radar */}
      <div className="bg-white rounded-2xl border border-purple-100 p-6">
        <h2 className="text-lg font-semibold text-charcoal mb-5">Audio Features</h2>
        <div className="space-y-4">
          <AudioMeter label="Energy" value={profile.audio_features.energy} />
          <AudioMeter label="Danceability" value={profile.audio_features.danceability} />
          <AudioMeter label="Mood / Valence" value={profile.audio_features.valence} />
          <AudioMeter label="Acousticness" value={profile.audio_features.acousticness} />
          <div className="flex items-center gap-3 pt-2 border-t border-purple-50">
            <span className="text-sm text-charcoal 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-purple">{profile.audio_features.avg_tempo}</span>
              <span className="text-sm text-charcoal-muted">BPM</span>
            </div>
          </div>
        </div>
      </div>

      {/* Top Artists */}
      <div className="bg-white rounded-2xl border border-purple-100 p-6">
        <h2 className="text-lg font-semibold text-charcoal mb-5">Artists That Define You</h2>
        {profile.top_artists.length === 0 ? (
          <p className="text-charcoal-muted text-sm">
            Import playlists to see your defining artists.
          </p>
        ) : (
          <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-cream/60 border border-purple-50"
              >
                <div className="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center flex-shrink-0">
                  <User className="w-5 h-5 text-purple" />
                </div>
                <div className="min-w-0">
                  <p className="text-sm font-semibold text-charcoal truncate">{artist.name}</p>
                  <p className="text-xs text-charcoal-muted">
                    {artist.track_count} track{artist.track_count !== 1 ? 's' : ''}
                    {artist.genre ? ` · ${artist.genre}` : ''}
                  </p>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

function AudioMeter({ label, value }: { label: string; value: number }) {
  return (
    <div className="flex items-center gap-3">
      <span className="text-sm text-charcoal w-28 text-right flex-shrink-0 font-medium">
        {label}
      </span>
      <div className="flex-1 bg-purple-50 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-charcoal-muted w-10">{value}%</span>
      )}
    </div>
  )
}
