'use client'

import React, { useState, useEffect } from 'react'
import {
  ComposedChart,
  Area,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts'

interface SentimentTrendProps {
  period: string
  channel: string
}

interface TrendDataPoint {
  date: string
  positive: number
  neutral: number
  negative: number
  question: number
  gratitude: number
  frustration: number
  avgScore: number
  total: number
}

const COLORS = {
  positive: '#10B981',
  neutral: '#6B7280',
  negative: '#EF4444',
  question: '#3B82F6',
  gratitude: '#8B5CF6',
  frustration: '#F97316',
  avgScore: '#1F2937',
}

export const SentimentTrendChart: React.FC<SentimentTrendProps> = ({ period, channel }) => {
  const [data, setData] = useState<TrendDataPoint[]>([])
  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 })
        const response = await fetch(`/api/community/analytics/sentiment-trend?${params}`)

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

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

    fetchData()
  }, [period, channel])

  if (isLoading) {
    return <div className="chart-loading">Lade Daten...</div>
  }

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

  if (data.length === 0) {
    return <div className="chart-empty">Keine Daten für den gewählten Zeitraum</div>
  }

  const formatDate = (dateStr: string): string => {
    const date = new Date(dateStr)
    return date.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' })
  }

  return (
    <div className="sentiment-trend-chart">
      <ResponsiveContainer width="100%" height={300}>
        <ComposedChart data={data} margin={{ top: 10, right: 30, left: 0, bottom: 0 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="#E5E7EB" />
          <XAxis dataKey="date" tickFormatter={formatDate} stroke="#9CA3AF" fontSize={12} />
          <YAxis yAxisId="left" stroke="#9CA3AF" fontSize={12} />
          <YAxis
            yAxisId="right"
            orientation="right"
            domain={[-1, 1]}
            stroke={COLORS.avgScore}
            fontSize={12}
          />
          <Tooltip
            contentStyle={{
              backgroundColor: 'var(--theme-elevation-50)',
              border: '1px solid var(--theme-elevation-150)',
              borderRadius: '4px',
            }}
          />
          <Legend />

          <Area
            yAxisId="left"
            type="monotone"
            dataKey="positive"
            name="Positiv"
            stackId="1"
            fill={COLORS.positive}
            stroke={COLORS.positive}
            fillOpacity={0.6}
          />
          <Area
            yAxisId="left"
            type="monotone"
            dataKey="neutral"
            name="Neutral"
            stackId="1"
            fill={COLORS.neutral}
            stroke={COLORS.neutral}
            fillOpacity={0.6}
          />
          <Area
            yAxisId="left"
            type="monotone"
            dataKey="negative"
            name="Negativ"
            stackId="1"
            fill={COLORS.negative}
            stroke={COLORS.negative}
            fillOpacity={0.6}
          />
          <Area
            yAxisId="left"
            type="monotone"
            dataKey="question"
            name="Frage"
            stackId="1"
            fill={COLORS.question}
            stroke={COLORS.question}
            fillOpacity={0.6}
          />

          <Line
            yAxisId="right"
            type="monotone"
            dataKey="avgScore"
            name="Ø Score"
            stroke={COLORS.avgScore}
            strokeWidth={2}
            dot={false}
          />
        </ComposedChart>
      </ResponsiveContainer>
    </div>
  )
}
