import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import dayjs from 'dayjs'
import { Event } from 'nostr-tools'
import AudioPlayer from '@/components/AudioPlayer'

interface MusicTrackNoteProps {
  event: Event
  className?: string
}

export default function MusicTrackNote({ event, className }: MusicTrackNoteProps) {
  const { t } = useTranslation()

  const metadata = useMemo(() => {
    const getTagValue = (tagName: string) => {
      const tag = event.tags.find(tag => tag[0] === tagName)
      return tag?.[1] || null
    }

    const getTagValues = (tagName: string) => {
      return event.tags
      .filter(tag => tag[0] === tagName)
      .map(tag => tag[1])
      .filter(Boolean)
    }


    let lyrics = null
    let credits = null

    if (event.content) {
      const creditsMatch = event.content.match(/Credits:\s*\n([\s\S]*)/i)
      if (creditsMatch) {
        credits = creditsMatch[1].trim()

        const lyricsMatch = event.content.match(/^([\s\S]*?)Credits:/i)
        lyrics = lyricsMatch ? lyricsMatch[1].trim() : null
      } else {

        lyrics = event.content
      }
    }

    return {
      title: getTagValue('title') || t('music.untitled'),
                           url: getTagValue('url'),
                           image: getTagValue('image'),
                           license: getTagValue('license'),
                           alt: getTagValue('alt'),
                           releaseDate: getTagValue('released'),
                           artist: getTagValue('artist'),
                           album: getTagValue('album'),
                           trackNumber: getTagValue('track_number'),
                           duration: getTagValue('duration'),
                           genres: getTagValues('t').filter(tag =>
                           !['music'].includes(tag)
                           ),
                           lyrics,
                           credits
    }
  }, [event, t])

  if (!metadata.url) {
    return (
      <div className={`p-4 text-red-500 ${className || ''}`}>
      {t('music.noAudioUrl')}
      </div>
    )
  }

  return (
    <div className={`space-y-4 p-4 ${className || ''}`}>
      {/* Main track container */}
      <div className="flex gap-4 flex-col sm:flex-row">
        {/* Cover Art */}
        {metadata.image && (
          <div className="flex-shrink-0">
          <img
          src={metadata.image}
          alt={metadata.alt || metadata.title}
          className="w-48 h-48 object-cover rounded-lg shadow-md"
          loading="lazy"
          />
          </div>
        )}

        {/* Track Info */}
        <div className="flex-1 space-y-2">
          <h3 className="text-xl font-bold">{metadata.title}</h3>

          {metadata.artist && (
            <p className="text-muted-foreground">
            {t('music.by')} {metadata.artist}
            </p>
          )}

          {metadata.album && (
            <p className="text-sm">
            {t('music.album')}: {metadata.album}
            {metadata.trackNumber && ` • ${t('music.track')} ${metadata.trackNumber}`}
            </p>
          )}

          {metadata.releaseDate && (
            <p className="text-sm text-muted-foreground">
            {t('music.released')}: {dayjs(metadata.releaseDate).format('MMMM D, YYYY')}
            </p>
          )}

          {/* Audio Player */}
          <div className="mt-4">
          <AudioPlayer
          src={metadata.url}
          />
          </div>

          {/* Show lyrics if they exist */}
          {metadata.lyrics && (
            <div className="pt-2">
            <p className="text-sm whitespace-pre-wrap text-muted-foreground">
            {metadata.lyrics}
            </p>
            </div>
          )}

          {/* Show credits if they exist */}
          {metadata.credits && (
            <div className="pt-2">
            <p className="text-sm italic text-muted-foreground whitespace-pre-wrap">
            <span className="font-semibold not-italic">{t('music.credits')}:</span><br />
            {metadata.credits}
            </p>
            </div>
          )}

        </div>
      </div>


    {/* License and Metadata Footer */}
    <div className="pt-4 border-t space-y-1">
    {metadata.license && (
      <p className="text-xs text-muted-foreground">
      {t('music.license')}: {metadata.license}
      </p>
    )}

    {metadata.genres.length > 0 && (
      <div className="flex flex-wrap gap-2 mt-2">
      {metadata.genres.map((genre, index) => (
        <span
        key={index}
        className="px-2 py-1 text-xs rounded-full bg-secondary"
        >
        {genre}
        </span>
      ))}
      </div>
    )}
    </div>
    </div>
  )
}
