'use client'

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

interface ChannelComparisonProps {
  period: string
}

interface ChannelData {
  id: number
  name: string
  platform: string
  metrics: {
    totalInteractions: number
    avgSentiment: number
    responseRate: number
    avgResponseTimeHours: number
    topTopics: string[]
  }
}

export const ChannelComparison: React.FC<ChannelComparisonProps> = ({ period }) => {
  const [channels, setChannels] = useState<ChannelData[]>([])
  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 })
        const response = await fetch(`/api/community/analytics/channel-comparison?${params}`)

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

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

    fetchData()
  }, [period])

  if (isLoading) {
    return <div className="channel-comparison-loading">Lade Vergleich...</div>
  }

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

  if (channels.length === 0) {
    return <div className="channel-comparison-empty">Keine Kanäle gefunden</div>
  }

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

  const formatTime = (hours: number): string => {
    if (hours < 1) return `${Math.round(hours * 60)}m`
    return `${hours.toFixed(1)}h`
  }

  return (
    <div className="channel-comparison">
      <table className="channel-comparison__table">
        <thead>
          <tr>
            <th>Kanal</th>
            <th>Interaktionen</th>
            <th>Sentiment</th>
            <th>Response</th>
            <th>Ø Zeit</th>
            <th>Top Themen</th>
          </tr>
        </thead>
        <tbody>
          {channels.map((channel) => (
            <tr key={channel.id}>
              <td>
                <div className="channel-comparison__channel">
                  <span className="channel-comparison__platform">{channel.platform}</span>
                  <strong>{channel.name}</strong>
                </div>
              </td>
              <td>{channel.metrics.totalInteractions}</td>
              <td>
                <span className="channel-comparison__sentiment">
                  {getSentimentEmoji(channel.metrics.avgSentiment)}
                  {channel.metrics.avgSentiment > 0 ? '+' : ''}
                  {channel.metrics.avgSentiment.toFixed(2)}
                </span>
              </td>
              <td>
                <span
                  className={`channel-comparison__rate ${channel.metrics.responseRate >= 90 ? 'channel-comparison__rate--good' : ''}`}
                >
                  {channel.metrics.responseRate.toFixed(0)}%
                </span>
              </td>
              <td>{formatTime(channel.metrics.avgResponseTimeHours)}</td>
              <td>
                <div className="channel-comparison__topics">
                  {channel.metrics.topTopics.slice(0, 3).map((topic, i) => (
                    <span key={i} className="channel-comparison__topic-tag">
                      {topic}
                    </span>
                  ))}
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
