import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { useBreadcrumb } from '../../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../../config/breadcrumbConfig'
import { BarChart3, TrendingUp, HardDrive, Users, ChevronUp, ChevronDown } from 'lucide-react'
import { api, PaidContentAnalyticsSummary } from '../../lib/api'
import { formatBytes } from '../../lib/utils'
import {
  AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer
} from 'recharts'

const TIME_RANGES = [
  { label: '7d', days: 7 },
  { label: '30d', days: 30 },
  { label: '90d', days: 90 },
  { label: 'All Time', days: 365 },
]

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

const CustomTooltip = ({ active, payload, label, formatter }: any) => {
  if (!active || !payload?.length) return null
  return (
    <div className="bg-popover border border-border rounded-lg p-2 shadow-lg text-sm">
      <p className="text-muted-foreground mb-1">{label}</p>
      {payload.map((entry: any, i: number) => (
        <p key={i} style={{ color: entry.color }}>
          {entry.name}: {formatter ? formatter(entry.value) : entry.value}
        </p>
      ))}
    </div>
  )
}

type SortField = 'total_bytes' | 'file_count' | 'post_count' | 'username' | 'video_count' | 'image_count'

export default function PaidContentAnalytics() {
  useBreadcrumb(breadcrumbConfig['/paid-content/analytics'])
  const [days, setDays] = useState(30)
  const [sortField, setSortField] = useState<SortField>('total_bytes')
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc')

  const { data, isLoading } = useQuery<PaidContentAnalyticsSummary>({
    queryKey: ['paid-content-analytics', days],
    queryFn: () => api.paidContent.getAnalyticsSummary(days),
  })

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDir(d => d === 'asc' ? 'desc' : 'asc')
    } else {
      setSortField(field)
      setSortDir('desc')
    }
  }

  const sortedScorecards = [...(data?.creator_scorecards || [])].sort((a: any, b: any) => {
    const av = a[sortField]
    const bv = b[sortField]
    if (typeof av === 'string') return sortDir === 'asc' ? av.localeCompare(bv) : bv.localeCompare(av)
    return sortDir === 'asc' ? av - bv : bv - av
  })

  const SortIcon = ({ field }: { field: SortField }) => {
    if (sortField !== field) return null
    return sortDir === 'asc' ? <ChevronUp className="w-3 h-3 inline" /> : <ChevronDown className="w-3 h-3 inline" />
  }

  const totalStorage = data?.storage_growth?.length
    ? data.storage_growth[data.storage_growth.length - 1].cumulative_bytes
    : 0
  const totalDownloads = data?.downloads_per_period?.reduce((s, d) => s + d.count, 0) || 0

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-4">
        <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-violet-500" />
            Analytics
          </h1>
          <p className="text-muted-foreground mt-1">Storage, downloads, and content insights</p>
        </div>
        <div className="flex gap-1 bg-secondary rounded-lg p-1">
          {TIME_RANGES.map(r => (
            <button
              key={r.days}
              onClick={() => setDays(r.days)}
              className={`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${
                days === r.days ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'
              }`}
            >
              {r.label}
            </button>
          ))}
        </div>
      </div>

      {isLoading ? (
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent" />
        </div>
      ) : !data ? (
        <div className="text-center py-12 text-muted-foreground">No analytics data available</div>
      ) : (
        <>
          {/* Summary Cards */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="bg-card rounded-xl border border-border p-4">
              <div className="flex items-center gap-2 text-muted-foreground text-sm mb-1">
                <HardDrive className="w-4 h-4" /> Total Storage
              </div>
              <div className="text-2xl font-bold">{formatBytes(totalStorage)}</div>
            </div>
            <div className="bg-card rounded-xl border border-border p-4">
              <div className="flex items-center gap-2 text-muted-foreground text-sm mb-1">
                <TrendingUp className="w-4 h-4" /> Downloads ({days}d)
              </div>
              <div className="text-2xl font-bold">{totalDownloads.toLocaleString()}</div>
            </div>
            <div className="bg-card rounded-xl border border-border p-4">
              <div className="flex items-center gap-2 text-muted-foreground text-sm mb-1">
                <Users className="w-4 h-4" /> Active Creators
              </div>
              <div className="text-2xl font-bold">{data.creator_scorecards?.length || 0}</div>
            </div>
            <div className="bg-card rounded-xl border border-border p-4">
              <div className="flex items-center gap-2 text-muted-foreground text-sm mb-1">
                <BarChart3 className="w-4 h-4" /> Platforms
              </div>
              <div className="text-2xl font-bold">{data.platform_distribution?.length || 0}</div>
            </div>
          </div>

          {/* Storage Growth Chart */}
          {data.storage_growth?.length > 0 && (
            <div className="bg-card rounded-xl border border-border p-4 md:p-6">
              <h2 className="text-lg font-semibold mb-4">Storage Growth</h2>
              <div className="h-64 md:h-80">
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart data={data.storage_growth}>
                    <CartesianGrid strokeDasharray="3 3" className="opacity-30" />
                    <XAxis dataKey="date" tick={{ fontSize: 12 }} tickFormatter={v => v.slice(5)} />
                    <YAxis tick={{ fontSize: 12 }} tickFormatter={v => formatBytes(v)} />
                    <Tooltip content={<CustomTooltip formatter={(v: number) => formatBytes(v)} />} />
                    <Area type="monotone" dataKey="cumulative_bytes" name="Total Storage" stroke="#8b5cf6" fill="#8b5cf6" fillOpacity={0.2} />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            </div>
          )}

          {/* Two-column charts */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Downloads Per Day */}
            {data.downloads_per_period?.length > 0 && (
              <div className="bg-card rounded-xl border border-border p-4 md:p-6">
                <h2 className="text-lg font-semibold mb-4">Downloads Per Day</h2>
                <div className="h-64">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={data.downloads_per_period}>
                      <CartesianGrid strokeDasharray="3 3" className="opacity-30" />
                      <XAxis dataKey="period" tick={{ fontSize: 12 }} tickFormatter={v => v.slice(5)} />
                      <YAxis tick={{ fontSize: 12 }} />
                      <Tooltip content={<CustomTooltip />} />
                      <Bar dataKey="count" name="Downloads" fill="#3b82f6" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </div>
            )}

            {/* Storage By Creator */}
            {data.storage_by_creator?.length > 0 && (
              <div className="bg-card rounded-xl border border-border p-4 md:p-6">
                <h2 className="text-lg font-semibold mb-4">Top Creators by Storage</h2>
                <div className="h-64">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={data.storage_by_creator.slice(0, 10)} layout="vertical">
                      <CartesianGrid strokeDasharray="3 3" className="opacity-30" />
                      <XAxis type="number" tick={{ fontSize: 12 }} tickFormatter={v => formatBytes(v)} />
                      <YAxis type="category" dataKey="username" tick={{ fontSize: 12 }} width={100} />
                      <Tooltip content={<CustomTooltip formatter={(v: number) => formatBytes(v)} />} />
                      <Bar dataKey="total_bytes" name="Storage" fill="#10b981" radius={[0, 4, 4, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </div>
            )}

            {/* Platform Distribution */}
            {data.platform_distribution?.length > 0 && (
              <div className="bg-card rounded-xl border border-border p-4 md:p-6">
                <h2 className="text-lg font-semibold mb-4">Platform Distribution</h2>
                <div className="h-64">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={data.platform_distribution}
                        dataKey="total_bytes"
                        nameKey="platform"
                        cx="50%" cy="50%"
                        innerRadius={50} outerRadius={90}
                        label={({ platform, percent }) => `${platform} (${(percent * 100).toFixed(0)}%)`}
                        labelLine={false}
                      >
                        {data.platform_distribution.map((_, i) => (
                          <Cell key={i} fill={CHART_COLORS[i % CHART_COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip formatter={(v: number) => formatBytes(v)} />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
              </div>
            )}

            {/* Content Type Distribution */}
            {data.content_type_distribution?.length > 0 && (
              <div className="bg-card rounded-xl border border-border p-4 md:p-6">
                <h2 className="text-lg font-semibold mb-4">Content Type Distribution</h2>
                <div className="h-64">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={data.content_type_distribution}
                        dataKey="count"
                        nameKey="content_type"
                        cx="50%" cy="50%"
                        innerRadius={50} outerRadius={90}
                        label={({ content_type, percent }) => `${content_type} (${(percent * 100).toFixed(0)}%)`}
                        labelLine={false}
                      >
                        {data.content_type_distribution.map((_, i) => (
                          <Cell key={i} fill={CHART_COLORS[i % CHART_COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
              </div>
            )}
          </div>

          {/* Creator Scorecards Table */}
          {sortedScorecards.length > 0 && (
            <div className="bg-card rounded-xl border border-border p-4 md:p-6">
              <h2 className="text-lg font-semibold mb-4">Creator Scorecards</h2>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-border text-left">
                      <th className="pb-2 pr-4 cursor-pointer hover:text-foreground" onClick={() => handleSort('username')}>
                        Creator <SortIcon field="username" />
                      </th>
                      <th className="pb-2 pr-4">Platform</th>
                      <th className="pb-2 pr-4 cursor-pointer hover:text-foreground text-right" onClick={() => handleSort('post_count')}>
                        Posts <SortIcon field="post_count" />
                      </th>
                      <th className="pb-2 pr-4 cursor-pointer hover:text-foreground text-right" onClick={() => handleSort('file_count')}>
                        Files <SortIcon field="file_count" />
                      </th>
                      <th className="pb-2 pr-4 cursor-pointer hover:text-foreground text-right" onClick={() => handleSort('image_count')}>
                        Images <SortIcon field="image_count" />
                      </th>
                      <th className="pb-2 pr-4 cursor-pointer hover:text-foreground text-right" onClick={() => handleSort('video_count')}>
                        Videos <SortIcon field="video_count" />
                      </th>
                      <th className="pb-2 cursor-pointer hover:text-foreground text-right" onClick={() => handleSort('total_bytes')}>
                        Storage <SortIcon field="total_bytes" />
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {sortedScorecards.map((c: any) => (
                      <tr key={c.id} className="border-b border-border/50 hover:bg-secondary/50">
                        <td className="py-2 pr-4">
                          <div className="flex items-center gap-2">
                            {c.profile_image_url && (
                              <img
                                src={`/api/paid-content/proxy/image?url=${encodeURIComponent(c.profile_image_url)}`}
                                className="w-6 h-6 rounded-full"
                                alt=""
                              />
                            )}
                            <span className="font-medium">{c.display_name || c.username}</span>
                          </div>
                        </td>
                        <td className="py-2 pr-4 capitalize text-muted-foreground">{c.platform}</td>
                        <td className="py-2 pr-4 text-right">{c.post_count}</td>
                        <td className="py-2 pr-4 text-right">{c.file_count}</td>
                        <td className="py-2 pr-4 text-right">{c.image_count}</td>
                        <td className="py-2 pr-4 text-right">{c.video_count}</td>
                        <td className="py-2 text-right">{formatBytes(c.total_bytes)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  )
}
