'use client'

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

interface TopicCloudProps {
  period: string
  channel: string
}

interface TopicData {
  topic: string
  count: number
  avgSentiment: number
  channels: string[]
}

export const TopicCloud: React.FC<TopicCloudProps> = ({ period, channel }) => {
  const [topics, setTopics] = useState<TopicData[]>([])
  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, limit: '30' })
        const response = await fetch(`/api/community/analytics/topic-cloud?${params}`)

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

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

    fetchData()
  }, [period, channel])

  if (isLoading) {
    return <div className="topic-cloud-loading">Lade Themen...</div>
  }

  if (error) {
    return <div className="topic-cloud-error">Fehler: {error}</div>
  }

  if (topics.length === 0) {
    return <div className="topic-cloud-empty">Keine Themen gefunden</div>
  }

  // Calculate min/max for sizing
  const maxCount = Math.max(...topics.map((t) => t.count))
  const minCount = Math.min(...topics.map((t) => t.count))

  const getSize = (count: number): number => {
    if (maxCount === minCount) return 1
    const normalized = (count - minCount) / (maxCount - minCount)
    return 0.75 + normalized * 1.25 // Scale from 0.75rem to 2rem
  }

  const getColor = (sentiment: number): string => {
    if (sentiment > 0.3) return '#10B981' // Green
    if (sentiment < -0.3) return '#EF4444' // Red
    return '#6B7280' // Gray
  }

  return (
    <div className="topic-cloud">
      <div className="topic-cloud__container">
        {topics.map((topic, index) => (
          <span
            key={index}
            className="topic-cloud__tag"
            style={{
              fontSize: `${getSize(topic.count)}rem`,
              color: getColor(topic.avgSentiment),
              opacity: 0.6 + (getSize(topic.count) / 2) * 0.4,
            }}
            title={`${topic.count} Erwähnungen | Sentiment: ${topic.avgSentiment.toFixed(2)}`}
          >
            {topic.topic}
          </span>
        ))}
      </div>

      <div className="topic-cloud__legend">
        <span className="topic-cloud__legend-item">
          <span style={{ color: '#10B981' }}>●</span> Positiv
        </span>
        <span className="topic-cloud__legend-item">
          <span style={{ color: '#6B7280' }}>●</span> Neutral
        </span>
        <span className="topic-cloud__legend-item">
          <span style={{ color: '#EF4444' }}>●</span> Negativ
        </span>
      </div>
    </div>
  )
}
