import { useQuery } from '@tanstack/react-query'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from 'recharts'
import { TrendingUp, TrendingDown, Clock, BarChart3, type LucideIcon } from 'lucide-react'
import { api } from '../lib/api'
import { formatBytes, formatPlatformName } from '../lib/utils'

const COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4', '#84cc16']

function StatCard({
  title,
  value,
  subtitle,
  trend,
  icon: Icon,
  color = 'blue',
}: {
  title: string
  value: string | number
  subtitle?: string
  trend?: { value: number; positive: boolean }
  icon: LucideIcon
  color?: 'blue' | 'green' | 'purple' | 'orange'
}) {
  const colorStyles = {
    blue: {
      card: 'stat-card-blue shadow-blue-glow',
      icon: 'bg-blue-500/20 text-blue-600 dark:text-blue-400',
    },
    green: {
      card: 'stat-card-green shadow-green-glow',
      icon: 'bg-emerald-500/20 text-emerald-600 dark:text-emerald-400',
    },
    purple: {
      card: 'stat-card-purple shadow-purple-glow',
      icon: 'bg-violet-500/20 text-violet-600 dark:text-violet-400',
    },
    orange: {
      card: 'stat-card-orange shadow-orange-glow',
      icon: 'bg-amber-500/20 text-amber-600 dark:text-amber-400',
    },
  }

  const styles = colorStyles[color]

  return (
    <div className={`card-glass-hover rounded-xl p-6 border ${styles.card}`}>
      <div className="flex items-center justify-between mb-4">
        <div className={`p-2 rounded-xl ${styles.icon}`}>
          <Icon className="w-5 h-5" />
        </div>
        {trend && (
          <div className={`flex items-center space-x-1 text-sm font-medium ${trend.positive ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400'}`}>
            {trend.positive ? <TrendingUp className="w-4 h-4" /> : <TrendingDown className="w-4 h-4" />}
            <span>{Math.abs(trend.value).toFixed(1)}%</span>
          </div>
        )}
      </div>
      <h3 className="text-sm font-medium text-muted-foreground">{title}</h3>
      <p className="mt-2 text-2xl font-bold text-foreground animate-count-up">{value}</p>
      {subtitle && <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>}
    </div>
  )
}

export default function Analytics() {
  useBreadcrumb(breadcrumbConfig['/analytics'])
  const { data: analytics } = useQuery({
    queryKey: ['analytics'],
    queryFn: () => api.getAnalytics(),
    refetchInterval: 30000, // Refresh every 30 seconds
  })

  if (!analytics) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-slate-500 dark:text-slate-400">Loading analytics...</div>
      </div>
    )
  }

  // Prepare data for charts
  const downloadsChartData = analytics.downloads_per_day.reverse()

  const fileTypeChartData = analytics.file_types.map(ft => ({
    name: ft.type.charAt(0).toUpperCase() + ft.type.slice(1),
    value: ft.count,
    size: ft.size,
  }))

  const platformStorageData = analytics.storage_by_platform.map(p => ({
    platform: formatPlatformName(p.platform),
    count: p.count,
    size: p.total_size,
    avgSize: p.avg_size,
  }))

  const hourlyData = Array.from({ length: 24 }, (_, i) => {
    const hourData = analytics.hourly_distribution.find(h => h.hour === i)
    return {
      hour: `${i.toString().padStart(2, '0')}:00`,
      count: hourData?.count || 0,
    }
  })

  const totalFileTypeCount = fileTypeChartData.reduce((sum, item) => sum + item.value, 0)

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
          <BarChart3 className="w-8 h-8 text-teal-500" />
          Analytics
        </h1>
        <p className="text-slate-600 dark:text-slate-400 mt-1">
          Advanced statistics and insights for your downloads
        </p>
      </div>

      {/* Weekly Comparison Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <StatCard
          title="This Week"
          value={analytics.weekly_comparison.this_week.toLocaleString()}
          subtitle="Downloads this week"
          icon={TrendingUp}
          color="blue"
        />
        <StatCard
          title="Last Week"
          value={analytics.weekly_comparison.last_week.toLocaleString()}
          subtitle="Downloads last week"
          icon={Clock}
          color="purple"
        />
        <StatCard
          title="Growth Rate"
          value={`${analytics.weekly_comparison.growth_rate >= 0 ? '+' : ''}${analytics.weekly_comparison.growth_rate.toFixed(1)}%`}
          subtitle="Week over week"
          trend={{
            value: analytics.weekly_comparison.growth_rate,
            positive: analytics.weekly_comparison.growth_rate >= 0,
          }}
          icon={TrendingUp}
          color="green"
        />
      </div>

      {/* Downloads Over Time */}
      <div className="card-glass-hover rounded-xl p-6">
        <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
          Downloads Over Time (Last 30 Days)
        </h3>
        <div className="h-80">
          <ResponsiveContainer width="100%" height="100%">
            <LineChart data={downloadsChartData}>
              <CartesianGrid strokeDasharray="3 3" className="stroke-slate-200 dark:stroke-slate-700" />
              <XAxis
                dataKey="date"
                className="text-xs"
                tick={{ fill: 'currentColor' }}
                tickFormatter={(value) => new Date(value).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
              />
              <YAxis className="text-xs" tick={{ fill: 'currentColor' }} />
              <Tooltip
                contentStyle={{
                  backgroundColor: 'var(--background)',
                  border: '1px solid var(--border)',
                  borderRadius: '0.5rem',
                }}
                labelFormatter={(value) => new Date(value).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })}
              />
              <Line type="monotone" dataKey="count" stroke="#3b82f6" strokeWidth={2} dot={{ r: 4 }} />
            </LineChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* File Types and Hourly Distribution */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* File Type Distribution */}
        <div className="card-glass-hover rounded-xl p-6">
          <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
            File Type Distribution
          </h3>
          <div className="h-80 flex items-center justify-center">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={fileTypeChartData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  outerRadius={100}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {fileTypeChartData.map((_, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip
                  contentStyle={{
                    backgroundColor: 'var(--background)',
                    border: '1px solid var(--border)',
                    borderRadius: '0.5rem',
                  }}
                  formatter={(value: number) => [value.toLocaleString(), 'Downloads']}
                />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <div className="mt-4 space-y-2">
            {fileTypeChartData.map((item, index) => (
              <div key={item.name} className="flex items-center justify-between text-sm">
                <div className="flex items-center space-x-2">
                  <div
                    className="w-3 h-3 rounded-full"
                    style={{ backgroundColor: COLORS[index % COLORS.length] }}
                  />
                  <span className="text-slate-700 dark:text-slate-300">{item.name}</span>
                </div>
                <div className="text-slate-500 dark:text-slate-400">
                  {item.value} ({((item.value / totalFileTypeCount) * 100).toFixed(1)}%) - {formatBytes(item.size)}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Hourly Distribution */}
        <div className="card-glass-hover rounded-xl p-6">
          <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
            Hourly Activity (Last 7 Days)
          </h3>
          <div className="h-80">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={hourlyData}>
                <CartesianGrid strokeDasharray="3 3" className="stroke-slate-200 dark:stroke-slate-700" />
                <XAxis
                  dataKey="hour"
                  className="text-xs"
                  tick={{ fill: 'currentColor' }}
                  interval={2}
                />
                <YAxis className="text-xs" tick={{ fill: 'currentColor' }} />
                <Tooltip
                  contentStyle={{
                    backgroundColor: 'var(--background)',
                    border: '1px solid var(--border)',
                    borderRadius: '0.5rem',
                  }}
                />
                <Bar dataKey="count" fill="#10b981" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      {/* Platform Storage Analysis */}
      <div className="card-glass-hover rounded-xl p-6">
        <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
          Storage by Platform
        </h3>
        <div className="h-80">
          <ResponsiveContainer width="100%" height="100%">
            <BarChart data={platformStorageData} layout="vertical">
              <CartesianGrid strokeDasharray="3 3" className="stroke-slate-200 dark:stroke-slate-700" />
              <XAxis type="number" className="text-xs" tick={{ fill: 'currentColor' }} tickFormatter={formatBytes} />
              <YAxis dataKey="platform" type="category" className="text-xs" tick={{ fill: 'currentColor' }} width={100} />
              <Tooltip
                contentStyle={{
                  backgroundColor: 'var(--background)',
                  border: '1px solid var(--border)',
                  borderRadius: '0.5rem',
                }}
                formatter={(value: number) => formatBytes(value)}
              />
              <Bar dataKey="size" fill="#8b5cf6" radius={[0, 4, 4, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* Top Sources */}
      <div className="card-glass-hover rounded-xl p-6">
        <h3 className="text-lg font-semibold text-foreground mb-4">
          Top 10 Sources
        </h3>
        <div className="space-y-3">
          {analytics.top_sources.map((source, index) => (
            <div key={`${source.platform}-${source.source}`} className="flex items-center justify-between p-3 bg-secondary/50 rounded-xl transition-all duration-200 hover:bg-secondary">
              <div className="flex items-center space-x-3">
                <div className="flex items-center justify-center w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-500/20 text-blue-600 dark:text-blue-400 font-semibold text-sm">
                  {index + 1}
                </div>
                <div>
                  <p className="text-sm font-medium text-slate-900 dark:text-slate-100">{source.source}</p>
                  <p className="text-xs text-slate-500 dark:text-slate-400">{formatPlatformName(source.platform)}</p>
                </div>
              </div>
              <div className="text-sm font-semibold text-slate-900 dark:text-slate-100">
                {source.count.toLocaleString()}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
