import { useEffect, useState } from 'react'
import { BarChart3, Eye, Target, Percent } from 'lucide-react'
import Chart from '../components/Chart'
import { Card, Empty } from '../components/ui'
import { getAnalyticsSummary, getAnalyticsTop } from '../api/client'

export default function Analytics() {
  const [summary, setSummary] = useState<any>({})
  const [top, setTop] = useState<any[]>([])

  useEffect(() => {
    getAnalyticsSummary().then(d => setSummary(d || {})).catch(() => setSummary({}))
    getAnalyticsTop(10).then(d => setTop(Array.isArray(d) ? d : (d?.items || []))).catch(() => setTop([]))
  }, [])

  const rate = summary.conversionRate != null
    ? Number(summary.conversionRate)
    : (summary.totalViews ? (summary.totalConversions || 0) / summary.totalViews * 100 : 0)

  const topChart = {
    labels: top.slice(0, 8).map((c: any) => (c.title || c.contentTitle || `#${c.contentId ?? c.id}`)?.slice(0, 14)),
    series: [{ name: '조회수', data: top.slice(0, 8).map((c: any) => Number(c.views ?? c.totalViews ?? 0)) }],
  }
  const convChart = {
    labels: top.slice(0, 8).map((c: any) => (c.title || c.contentTitle || `#${c.contentId ?? c.id}`)?.slice(0, 14)),
    series: [{ name: '전환', data: top.slice(0, 8).map((c: any) => Number(c.conversions ?? c.totalConversions ?? 0)) }],
  }

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-xl font-bold">콘텐츠 분석</h1>
        <p className="text-sm text-slate-400 mt-0.5">조회 · 체류 · 전환 · 인기 콘텐츠 성과 (Recharts)</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <Card>
          <div className="flex items-center gap-1.5 text-xs text-slate-400"><Eye size={13} /> 총 조회수</div>
          <div className="text-3xl font-bold mt-2 text-brand">{Number(summary.totalViews ?? 0).toLocaleString()}</div>
        </Card>
        <Card>
          <div className="flex items-center gap-1.5 text-xs text-slate-400"><Target size={13} /> 총 전환</div>
          <div className="text-3xl font-bold mt-2 text-accent">{Number(summary.totalConversions ?? 0).toLocaleString()}</div>
        </Card>
        <Card>
          <div className="flex items-center gap-1.5 text-xs text-slate-400"><Percent size={13} /> 전환율</div>
          <div className="text-3xl font-bold mt-2 text-amber-400">{rate.toFixed(1)}%</div>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <Card title="인기 콘텐츠 조회수" icon={<BarChart3 size={15} />}>
          {top.length ? <Chart type="BAR" data={topChart} /> : <Empty msg="데이터가 없습니다." />}
        </Card>
        <Card title="콘텐츠별 전환" icon={<Target size={15} />}>
          {top.length ? <Chart type="BAR" data={convChart} /> : <Empty msg="데이터가 없습니다." />}
        </Card>
      </div>

      <Card title="인기 콘텐츠 상세" icon={<Eye size={15} />} className="mt-4">
        {top.length === 0 ? <Empty msg="데이터가 없습니다." /> : (
          <table className="w-full text-sm">
            <thead className="text-slate-500 text-xs">
              <tr><th className="text-left py-2">제목</th><th className="text-left">유형</th><th className="text-right">조회</th><th className="text-right">전환</th></tr>
            </thead>
            <tbody>
              {top.map((c: any, i: number) => (
                <tr key={c.id ?? c.contentId ?? i} className="border-t border-edge/50">
                  <td className="py-2 font-medium">{c.title || c.contentTitle || `#${c.contentId ?? c.id}`}</td>
                  <td className="text-slate-400">{c.contentType || '-'}</td>
                  <td className="text-right text-slate-300">{Number(c.views ?? c.totalViews ?? 0).toLocaleString()}</td>
                  <td className="text-right text-slate-300">{Number(c.conversions ?? c.totalConversions ?? 0).toLocaleString()}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Card>
    </div>
  )
}
