'use client'

import React, { useState, useEffect } from 'react'
import { KPICards } from './components/KPICards'
import { SentimentTrendChart } from './components/SentimentTrendChart'
import { ResponseMetrics } from './components/ResponseMetrics'
import { ChannelComparison } from './components/ChannelComparison'
import { TopContent } from './components/TopContent'
import { TopicCloud } from './components/TopicCloud'

type Period = '7d' | '30d' | '90d'

interface Channel {
  id: string
  name: string
}

export const AnalyticsDashboard: React.FC = () => {
  const [period, setPeriod] = useState<Period>('30d')
  const [channel, setChannel] = useState<string>('all')
  const [channels, setChannels] = useState<Channel[]>([])

  // Fetch available channels on mount
  useEffect(() => {
    const fetchChannels = async () => {
      try {
        const response = await fetch(
          '/api/social-accounts?where[isActive][equals]=true&limit=100',
        )
        if (response.ok) {
          const data = await response.json()
          setChannels(
            data.docs.map((acc: { id: number; displayName: string }) => ({
              id: String(acc.id),
              name: acc.displayName,
            })),
          )
        }
      } catch (err) {
        console.error('Failed to fetch channels:', err)
      }
    }
    fetchChannels()
  }, [])

  const periodLabels: Record<Period, string> = {
    '7d': '7 Tage',
    '30d': '30 Tage',
    '90d': '90 Tage',
  }

  return (
    <div className="analytics-dashboard">
      {/* Header */}
      <div className="analytics-dashboard__header">
        <div className="analytics-dashboard__title">
          <div className="analytics-dashboard__nav">
            <a href="/admin/views/community/inbox" className="analytics-dashboard__back-link">
              ← Inbox
            </a>
          </div>
          <h1>Community Analytics</h1>
          <p className="analytics-dashboard__subtitle">Performance-Übersicht aller Kanäle</p>
        </div>

        <div className="analytics-dashboard__filters">
          {/* Period Selector */}
          <div className="analytics-dashboard__filter">
            <label htmlFor="period-select">Zeitraum:</label>
            <select
              id="period-select"
              value={period}
              onChange={(e) => setPeriod(e.target.value as Period)}
              className="analytics-dashboard__select"
            >
              {Object.entries(periodLabels).map(([value, label]) => (
                <option key={value} value={value}>
                  {label}
                </option>
              ))}
            </select>
          </div>

          {/* Channel Filter */}
          <div className="analytics-dashboard__filter">
            <label htmlFor="channel-select">Kanal:</label>
            <select
              id="channel-select"
              value={channel}
              onChange={(e) => setChannel(e.target.value)}
              className="analytics-dashboard__select"
            >
              <option value="all">Alle Kanäle</option>
              {channels.map((ch) => (
                <option key={ch.id} value={ch.id}>
                  {ch.name}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* KPI Cards Row */}
      <div className="analytics-dashboard__kpi-grid">
        <KPICards period={period} channel={channel} />
      </div>

      {/* Charts Grid - Row 1 */}
      <div className="analytics-dashboard__charts-grid">
        <div className="analytics-dashboard__card analytics-dashboard__card--wide">
          <h3>Sentiment-Trend</h3>
          <SentimentTrendChart period={period} channel={channel} />
        </div>

        <div className="analytics-dashboard__card">
          <h3>Response-Metriken</h3>
          <ResponseMetrics period={period} channel={channel} />
        </div>
      </div>

      {/* Charts Grid - Row 2 */}
      <div className="analytics-dashboard__charts-grid">
        <div className="analytics-dashboard__card">
          <h3>Kanal-Vergleich</h3>
          <ChannelComparison period={period} />
        </div>

        <div className="analytics-dashboard__card">
          <h3>Themen-Wolke</h3>
          <TopicCloud period={period} channel={channel} />
        </div>
      </div>

      {/* Top Content */}
      <div className="analytics-dashboard__card">
        <h3>Top Content nach Engagement</h3>
        <TopContent period={period} channel={channel} />
      </div>
    </div>
  )
}
