'use client'

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

interface ResponseMetricsProps {
  period: string
  channel: string
}

interface MetricsData {
  firstResponseTime: {
    median: number
    p90: number
    trend: number
  }
  resolutionRate: number
  escalationRate: number
  templateUsageRate: number
  byPriority: {
    urgent: { count: number; avgResponseTime: number }
    high: { count: number; avgResponseTime: number }
    normal: { count: number; avgResponseTime: number }
    low: { count: number; avgResponseTime: number }
  }
  byStatus: {
    new: number
    in_review: number
    waiting: number
    replied: number
    resolved: number
    archived: number
    spam: number
  }
}

export const ResponseMetrics: React.FC<ResponseMetricsProps> = ({ period, channel }) => {
  const [data, setData] = useState<MetricsData | 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/response-metrics?${params}`)

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

        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 <div className="metrics-loading">Lade Metriken...</div>
  }

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

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

  const getProgressColor = (value: number, target: number, inverse: boolean = false): string => {
    const ratio = value / target
    if (inverse) {
      if (ratio <= 1) return '#10B981'
      if (ratio <= 1.5) return '#F59E0B'
      return '#EF4444'
    }
    if (ratio >= 1) return '#10B981'
    if (ratio >= 0.7) return '#F59E0B'
    return '#EF4444'
  }

  return (
    <div className="response-metrics">
      {/* Response Time */}
      <div className="response-metrics__item">
        <div className="response-metrics__label">Erste Antwort (Median)</div>
        <div className="response-metrics__value">{formatTime(data.firstResponseTime.median)}</div>
        <div className="response-metrics__bar">
          <div
            className="response-metrics__bar-fill"
            style={{
              width: `${Math.min((4 / Math.max(data.firstResponseTime.median, 0.1)) * 100, 100)}%`,
              backgroundColor: getProgressColor(data.firstResponseTime.median, 4, true),
            }}
          />
        </div>
        <div className="response-metrics__target">Ziel: &lt; 4h</div>
      </div>

      {/* Resolution Rate */}
      <div className="response-metrics__item">
        <div className="response-metrics__label">Resolution Rate</div>
        <div className="response-metrics__value">{data.resolutionRate.toFixed(0)}%</div>
        <div className="response-metrics__bar">
          <div
            className="response-metrics__bar-fill"
            style={{
              width: `${data.resolutionRate}%`,
              backgroundColor: getProgressColor(data.resolutionRate, 90),
            }}
          />
        </div>
        <div className="response-metrics__target">Ziel: &gt; 90%</div>
      </div>

      {/* Escalation Rate */}
      <div className="response-metrics__item">
        <div className="response-metrics__label">Eskalationsrate</div>
        <div className="response-metrics__value">{data.escalationRate.toFixed(1)}%</div>
        <div className="response-metrics__bar">
          <div
            className="response-metrics__bar-fill"
            style={{
              width: `${Math.min(data.escalationRate * 10, 100)}%`,
              backgroundColor: getProgressColor(data.escalationRate, 5, true),
            }}
          />
        </div>
        <div className="response-metrics__target">Ziel: &lt; 5%</div>
      </div>

      {/* Template Usage */}
      <div className="response-metrics__item">
        <div className="response-metrics__label">Template-Nutzung</div>
        <div className="response-metrics__value">{data.templateUsageRate.toFixed(0)}%</div>
        <div className="response-metrics__bar">
          <div
            className="response-metrics__bar-fill"
            style={{
              width: `${data.templateUsageRate}%`,
              backgroundColor: getProgressColor(data.templateUsageRate, 60),
            }}
          />
        </div>
        <div className="response-metrics__target">Ziel: &gt; 60%</div>
      </div>

      {/* Priority Breakdown */}
      <div className="response-metrics__priority-section">
        <h4>Nach Priorität</h4>
        <div className="response-metrics__priority-grid">
          {Object.entries(data.byPriority).map(([priority, stats]) => (
            <div
              key={priority}
              className={`response-metrics__priority response-metrics__priority--${priority}`}
            >
              <span className="response-metrics__priority-label">
                {priority.charAt(0).toUpperCase() + priority.slice(1)}
              </span>
              <span className="response-metrics__priority-count">{stats.count}</span>
              <span className="response-metrics__priority-time">
                {formatTime(stats.avgResponseTime)}
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
