import React, { useState, useEffect } from 'react'
import { api } from '../services/api'
import { useAuthStore } from '../stores/authStore'

interface AnalyticsOverview {
  workspace_stats: Array<{ type: string; count: number }>
  booking_stats: {
    total_bookings: number
    unique_users: number
    completed_bookings: number
    cancelled_bookings: number
    no_shows: number
  }
  utilization_by_type: Array<{
    type: string
    avg_utilization: number
    avg_hours_booked: number
  }>
  popular_workspaces: Array<{
    id: string
    name: string
    type: string
    floor: string
    booking_count: number
    avg_duration_hours: number
  }>
  peak_hours: Array<{
    hour: number
    booking_count: number
  }>
  date_range: {
    from: string
    to: string
  }
}

export default function WorkspaceAnalytics() {
  const [analytics, setAnalytics] = useState<AnalyticsOverview | null>(null)
  const [fromDate, setFromDate] = useState(
    new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
  )
  const [toDate, setToDate] = useState(new Date().toISOString().split('T')[0])
  const [loading, setLoading] = useState(true)

  const { user } = useAuthStore()

  useEffect(() => {
    if (user && ['admin', 'poweruser'].includes(user.role)) {
      loadAnalytics()
    }
  }, [fromDate, toDate, user])

  const loadAnalytics = async () => {
    try {
      setLoading(true)
      const response = await api.get('/analytics/overview', {
        params: { from_date: fromDate, to_date: toDate }
      })
      setAnalytics(response.data)
    } catch (error) {
      console.error('Failed to load analytics:', error)
    } finally {
      setLoading(false)
    }
  }

  if (!user || !['admin', 'poweruser'].includes(user.role)) {
    return (
      <div className="p-6">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
          <p className="text-red-800 dark:text-red-200">
            Sie haben keine Berechtigung, diese Seite zu sehen.
          </p>
        </div>
      </div>
    )
  }

  const getWorkspaceTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      desk: 'Arbeitsplätze',
      meeting_room: 'Meetingräume',
      phone_booth: 'Telefonboxen',
      parking: 'Parkplätze',
      locker: 'Schließfächer'
    }
    return labels[type] || type
  }

  return (
    <div className="p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
          Workplace Analytics
        </h1>
        <p className="text-gray-600 dark:text-gray-400">
          Detaillierte Auslastungsstatistiken und Nutzungsanalysen
        </p>
      </div>

      {/* Date Range Filter */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Von
            </label>
            <input
              type="date"
              value={fromDate}
              onChange={(e) => setFromDate(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Bis
            </label>
            <input
              type="date"
              value={toDate}
              onChange={(e) => setToDate(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
            />
          </div>
          <div className="flex items-end">
            <button
              onClick={loadAnalytics}
              className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
            >
              Aktualisieren
            </button>
          </div>
        </div>
      </div>

      {loading ? (
        <div className="text-center py-16">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
        </div>
      ) : analytics ? (
        <>
          {/* Key Metrics */}
          <div className="grid grid-cols-1 md:grid-cols-5 gap-4 mb-6">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <p className="text-sm text-gray-600 dark:text-gray-400">Gesamtbuchungen</p>
              <p className="text-3xl font-bold text-gray-900 dark:text-white mt-2">
                {analytics.booking_stats.total_bookings}
              </p>
            </div>
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <p className="text-sm text-gray-600 dark:text-gray-400">Aktive Nutzer</p>
              <p className="text-3xl font-bold text-blue-600 mt-2">
                {analytics.booking_stats.unique_users}
              </p>
            </div>
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <p className="text-sm text-gray-600 dark:text-gray-400">Abgeschlossen</p>
              <p className="text-3xl font-bold text-green-600 mt-2">
                {analytics.booking_stats.completed_bookings}
              </p>
            </div>
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <p className="text-sm text-gray-600 dark:text-gray-400">Storniert</p>
              <p className="text-3xl font-bold text-orange-600 mt-2">
                {analytics.booking_stats.cancelled_bookings}
              </p>
            </div>
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <p className="text-sm text-gray-600 dark:text-gray-400">No-Shows</p>
              <p className="text-3xl font-bold text-red-600 mt-2">
                {analytics.booking_stats.no_shows}
              </p>
            </div>
          </div>

          {/* Workspace Distribution */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                Arbeitsplätze nach Typ
              </h2>
              <div className="space-y-3">
                {analytics.workspace_stats.map(stat => (
                  <div key={stat.type} className="flex justify-between items-center">
                    <span className="text-gray-700 dark:text-gray-300">
                      {getWorkspaceTypeLabel(stat.type)}
                    </span>
                    <span className="font-medium text-gray-900 dark:text-white">
                      {stat.count}
                    </span>
                  </div>
                ))}
              </div>
            </div>

            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                Durchschnittliche Auslastung
              </h2>
              <div className="space-y-3">
                {analytics.utilization_by_type.map(util => (
                  <div key={util.type}>
                    <div className="flex justify-between items-center mb-1">
                      <span className="text-gray-700 dark:text-gray-300">
                        {getWorkspaceTypeLabel(util.type)}
                      </span>
                      <span className="font-medium text-gray-900 dark:text-white">
                        {Math.round(util.avg_utilization * 100)}%
                      </span>
                    </div>
                    <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                      <div
                        className="bg-blue-600 h-2 rounded-full"
                        style={{ width: `${Math.round(util.avg_utilization * 100)}%` }}
                      />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Popular Workspaces */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Beliebteste Arbeitsplätze
            </h2>
            <div className="overflow-x-auto">
              <table className="min-w-full">
                <thead>
                  <tr className="border-b border-gray-200 dark:border-gray-700">
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">
                      Name
                    </th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">
                      Typ
                    </th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">
                      Etage
                    </th>
                    <th className="text-right py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">
                      Buchungen
                    </th>
                    <th className="text-right py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">
                      Ø Dauer
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {analytics.popular_workspaces.map(workspace => (
                    <tr
                      key={workspace.id}
                      className="border-b border-gray-200 dark:border-gray-700"
                    >
                      <td className="py-3 px-4 text-gray-900 dark:text-white">
                        {workspace.name}
                      </td>
                      <td className="py-3 px-4 text-gray-600 dark:text-gray-400">
                        {getWorkspaceTypeLabel(workspace.type)}
                      </td>
                      <td className="py-3 px-4 text-gray-600 dark:text-gray-400">
                        {workspace.floor}
                      </td>
                      <td className="py-3 px-4 text-right text-gray-900 dark:text-white">
                        {workspace.booking_count}
                      </td>
                      <td className="py-3 px-4 text-right text-gray-600 dark:text-gray-400">
                        {workspace.avg_duration_hours.toFixed(1)}h
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Peak Hours */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Stoßzeiten
            </h2>
            <div className="h-64">
              <div className="flex items-end justify-between h-full">
                {Array.from({ length: 24 }, (_, i) => {
                  const hourData = analytics.peak_hours.find(h => h.hour === i)
                  const count = hourData?.booking_count || 0
                  const maxCount = Math.max(...analytics.peak_hours.map(h => h.booking_count))
                  const height = maxCount > 0 ? (count / maxCount) * 100 : 0

                  return (
                    <div
                      key={i}
                      className="flex-1 flex flex-col items-center"
                    >
                      <div
                        className="w-full bg-blue-600 rounded-t"
                        style={{ height: `${height}%` }}
                        title={`${i}:00 - ${count} Buchungen`}
                      />
                      <span className="text-xs text-gray-600 dark:text-gray-400 mt-1">
                        {i}
                      </span>
                    </div>
                  )
                })}
              </div>
            </div>
          </div>
        </>
      ) : (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <p className="text-gray-600 dark:text-gray-400 text-center">
            Keine Daten verfügbar
          </p>
        </div>
      )}
    </div>
  )
}