'use client'

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

interface KPICardsProps {
  period: string
  channel: string
}

interface OverviewData {
  totalInteractions: number
  newInteractions: number
  responseRate: number
  avgResponseTimeHours: number
  avgSentimentScore: number
  medicalQuestions: number
  escalations: number
  sentimentDistribution: {
    positive: number
    neutral: number
    negative: number
    question: number
    gratitude: number
    frustration: number
  }
  comparison: {
    totalInteractions: number
    responseRate: number
    avgSentimentScore: number
  }
}

export const KPICards: React.FC<KPICardsProps> = ({ period, channel }) => {
  const [data, setData] = useState<OverviewData | null>(null)
  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/overview?${params}`)

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

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

    fetchData()
  }, [period, channel])

  if (isLoading) {
    return (
      <>
        {[...Array(5)].map((_, i) => (
          <div key={i} className="kpi-card kpi-card--loading">
            <div className="kpi-card__skeleton" />
          </div>
        ))}
      </>
    )
  }

  if (error || !data) {
    return <div className="kpi-card kpi-card--error">Fehler beim Laden der Daten</div>
  }

  const getTrendClass = (value: number): string => {
    if (value > 0) return 'kpi-card__trend--up'
    if (value < 0) return 'kpi-card__trend--down'
    return 'kpi-card__trend--neutral'
  }

  const getTrendIcon = (value: number): string => {
    if (value > 0) return '↑'
    if (value < 0) return '↓'
    return '→'
  }

  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)} Min`
    return `${hours.toFixed(1)}h`
  }

  return (
    <>
      {/* Neue Interaktionen */}
      <div className="kpi-card">
        <div className="kpi-card__icon kpi-card__icon--blue">💬</div>
        <div className="kpi-card__value">{data.newInteractions}</div>
        <div className="kpi-card__label">Neue Interaktionen</div>
        <div className={`kpi-card__trend ${getTrendClass(data.comparison.totalInteractions)}`}>
          {getTrendIcon(data.comparison.totalInteractions)}{' '}
          {Math.abs(data.comparison.totalInteractions)}% vs. Vorperiode
        </div>
      </div>

      {/* Response Rate */}
      <div className="kpi-card">
        <div className="kpi-card__icon kpi-card__icon--green">✅</div>
        <div className="kpi-card__value">{data.responseRate.toFixed(0)}%</div>
        <div className="kpi-card__label">Response Rate</div>
        <div className={`kpi-card__trend ${getTrendClass(data.comparison.responseRate)}`}>
          {getTrendIcon(data.comparison.responseRate)}{' '}
          {Math.abs(data.comparison.responseRate).toFixed(1)}%
        </div>
      </div>

      {/* Ø Antwortzeit */}
      <div className="kpi-card">
        <div className="kpi-card__icon kpi-card__icon--purple">⏱️</div>
        <div className="kpi-card__value">{formatTime(data.avgResponseTimeHours)}</div>
        <div className="kpi-card__label">Ø Antwortzeit</div>
        <div className="kpi-card__trend kpi-card__trend--neutral">Median</div>
      </div>

      {/* Sentiment Score */}
      <div className="kpi-card">
        <div className="kpi-card__icon kpi-card__icon--yellow">
          {getSentimentEmoji(data.avgSentimentScore)}
        </div>
        <div className="kpi-card__value">
          {data.avgSentimentScore > 0 ? '+' : ''}
          {data.avgSentimentScore.toFixed(2)}
        </div>
        <div className="kpi-card__label">Sentiment Score</div>
        <div className={`kpi-card__trend ${getTrendClass(data.comparison.avgSentimentScore)}`}>
          {getTrendIcon(data.comparison.avgSentimentScore)}{' '}
          {Math.abs(data.comparison.avgSentimentScore).toFixed(2)}
        </div>
      </div>

      {/* Medical Flags */}
      <div className="kpi-card">
        <div
          className={`kpi-card__icon ${data.medicalQuestions > 0 ? 'kpi-card__icon--red' : 'kpi-card__icon--gray'}`}
        >
          ⚕️
        </div>
        <div className="kpi-card__value">{data.medicalQuestions}</div>
        <div className="kpi-card__label">Med. Anfragen</div>
        {data.escalations > 0 && (
          <div className="kpi-card__trend kpi-card__trend--down">
            ⚠️ {data.escalations} Eskalationen
          </div>
        )}
      </div>
    </>
  )
}
