'use client'

import React, { useState, useEffect } from 'react'

interface TopContentProps {
  period: string
  channel: string
}

type SortBy = 'comments' | 'sentiment' | 'medical'

interface ContentData {
  contentId: number
  videoId: string
  title: string
  channelName: string
  thumbnailUrl: string
  commentCount: number
  avgSentiment: number
  medicalQuestions: number
  topTopics: string[]
  publishedAt: string
}

export const TopContent: React.FC<TopContentProps> = ({ period, channel }) => {
  const [content, setContent] = useState<ContentData[]>([])
  const [sortBy, setSortBy] = useState<SortBy>('comments')
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true)
      setError(null)

      try {
        const params = new URLSearchParams({ period, channel, sortBy, limit: '10' })
        const response = await fetch(`/api/community/analytics/top-content?${params}`)

        if (!response.ok) throw new Error('Failed to fetch top content')

        const result = await response.json()
        setContent(result.content)
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error')
      } finally {
        setIsLoading(false)
      }
    }

    fetchData()
  }, [period, channel, sortBy])

  const getSentimentEmoji = (score: number): string => {
    if (score > 0.3) return '😊'
    if (score < -0.3) return '😟'
    return '😐'
  }

  const sortOptions: { value: SortBy; label: string }[] = [
    { value: 'comments', label: 'Interaktionen' },
    { value: 'sentiment', label: 'Sentiment' },
    { value: 'medical', label: 'Med. Anfragen' },
  ]

  return (
    <div className="top-content">
      <div className="top-content__header">
        <div className="top-content__sort">
          <label>Sortieren nach:</label>
          <select value={sortBy} onChange={(e) => setSortBy(e.target.value as SortBy)}>
            {sortOptions.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      {isLoading && <div className="top-content__loading">Lade Content...</div>}

      {error && <div className="top-content__error">Fehler: {error}</div>}

      {!isLoading && !error && content.length === 0 && (
        <div className="top-content__empty">Kein Content mit Interaktionen gefunden</div>
      )}

      {!isLoading && !error && content.length > 0 && (
        <div className="top-content__list">
          {content.map((item, index) => (
            <div key={item.contentId} className="top-content__item">
              <span className="top-content__rank">{index + 1}</span>

              <div className="top-content__thumbnail">
                {item.thumbnailUrl ? (
                  <img src={item.thumbnailUrl} alt={item.title} />
                ) : (
                  <div className="top-content__thumbnail-placeholder">🎬</div>
                )}
              </div>

              <div className="top-content__info">
                <h4 className="top-content__title">{item.title}</h4>
                <span className="top-content__channel">{item.channelName}</span>
                <div className="top-content__topics">
                  {item.topTopics.slice(0, 3).map((topic, i) => (
                    <span key={i} className="top-content__topic">
                      {topic}
                    </span>
                  ))}
                </div>
              </div>

              <div className="top-content__stats">
                <div className="top-content__stat">
                  <span className="top-content__stat-value">{item.commentCount}</span>
                  <span className="top-content__stat-label">Interaktionen</span>
                </div>
                <div className="top-content__stat">
                  <span className="top-content__stat-value">
                    {getSentimentEmoji(item.avgSentiment)} {item.avgSentiment.toFixed(2)}
                  </span>
                  <span className="top-content__stat-label">Sentiment</span>
                </div>
                {item.medicalQuestions > 0 && (
                  <div className="top-content__stat top-content__stat--medical">
                    <span className="top-content__stat-value">⚕️ {item.medicalQuestions}</span>
                    <span className="top-content__stat-label">Med. Fragen</span>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
