import { useEffect, useState, useCallback } from 'react'
import { fetchAPI } from '../api/client'
import ErrorBanner from '../components/ErrorBanner'
import Loading from '../components/Loading'

interface DashboardStats {
  total_media: number
  monitored: number
  unavailable: number
  available: number
  quality_upgrades: number
  queue_pending: number
  queue_downloading: number
  queue_failed: number
  blocklist_count: number
  blocklist_expired: number
  indexers_enabled: number
  recent_downloads: number
  media_by_type: Record<string, number>
  storage_by_type: Record<string, number>
}

export default function Dashboard() {
  const [data, setData] = useState<DashboardStats | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  const fetchDashboard = useCallback(() => {
    setLoading(true)
    setError(null)
    fetchAPI<DashboardStats>('/api/dashboard')
      .then(setData)
      .catch(err => setError(err.message || 'Something went wrong. Please try again.'))
      .finally(() => setLoading(false))
  }, [])

  useEffect(() => {
    fetchDashboard()
  }, [fetchDashboard])

  if (error) {
    return (
      <div>
        <h2 className="text-2xl font-semibold mb-6 text-gray-100">Dashboard</h2>
        <ErrorBanner error={error} onRetry={fetchDashboard} />
      </div>
    )
  }

  const cards = [
    { label: 'Movies', value: data?.media_by_type?.movie ?? 0, color: 'bg-blue-600' },
    { label: 'TV Series', value: data?.media_by_type?.series ?? 0, color: 'bg-green-600' },
    { label: 'Music', value: data?.media_by_type?.music ?? 0, color: 'bg-purple-600' },
    { label: 'Books', value: data?.media_by_type?.book ?? 0, color: 'bg-teal-600' },
    { label: 'Active Downloads', value: data?.queue_downloading ?? 0, color: 'bg-orange-600' },
    { label: 'Missing', value: data?.unavailable ?? 0, color: 'bg-red-600' },
    { label: 'Upgrades Available', value: data?.quality_upgrades ?? 0, color: 'bg-cyan-600' },
    { label: 'Total Storage', value: data ? formatStorage(data.storage_by_type) : '—', color: 'bg-gray-600' },
  ]

  return (
    <div>
      <h2 className="text-2xl font-semibold mb-6 text-gray-100">Dashboard</h2>
      {loading && !data ? (
        <Loading />
      ) : (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {cards.map(card => (
            <div key={card.label} className={`${card.color} rounded-lg p-4`}>
              <p className="text-sm text-gray-200 font-normal">{card.label}</p>
              {loading ? (
                <div className="mt-2 h-8 w-16 bg-white/10 animate-pulse rounded" />
              ) : (
                <p className="text-2xl font-semibold mt-1">{card.value}</p>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

function formatStorage(storageByType: Record<string, number>): string {
  const total = Object.values(storageByType).reduce((sum, v) => sum + v, 0)
  const tb = total / 1e12
  if (tb >= 1) return `${tb.toFixed(1)} TB`
  const gb = total / 1e9
  return `${gb.toFixed(1)} GB`
}
