import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import {
  FileText, FileCheck2, FileClock, FileSearch, Image, MessageSquareWarning,
  UsersRound, Eye, Target, Sparkles, ArrowRight,
} from 'lucide-react'
import Chart from '../components/Chart'
import { Card } from '../components/ui'
import { getDashboardSummary, getDashboardWorkflow, getTopContent } from '../api/client'

interface Summary {
  totalContent?: number; publishedContent?: number; draftContent?: number; reviewContent?: number
  mediaCount?: number; pendingUgc?: number; memberCount?: number
  totalViews?: number; totalConversions?: number
}

const cards = [
  { key: 'totalContent', label: '전체 콘텐츠', icon: FileText, color: 'text-brand' },
  { key: 'publishedContent', label: '게시됨', icon: FileCheck2, color: 'text-emerald-400' },
  { key: 'draftContent', label: '초안', icon: FileClock, color: 'text-slate-300' },
  { key: 'reviewContent', label: '검토 대기', icon: FileSearch, color: 'text-amber-400' },
  { key: 'mediaCount', label: '미디어', icon: Image, color: 'text-sky-400' },
  { key: 'pendingUgc', label: 'UGC 대기', icon: MessageSquareWarning, color: 'text-rose-400' },
  { key: 'memberCount', label: '회원', icon: UsersRound, color: 'text-violet-400' },
  { key: 'totalViews', label: '총 조회수', icon: Eye, color: 'text-accent' },
] as const

export default function Dashboard() {
  const [sum, setSum] = useState<Summary>({})
  const [workflow, setWorkflow] = useState<any>(null)
  const [top, setTop] = useState<any[]>([])

  useEffect(() => {
    getDashboardSummary().then(d => setSum(d || {})).catch(() => setSum({}))
    getDashboardWorkflow().then(setWorkflow).catch(() => setWorkflow(null))
    getTopContent().then(d => setTop(Array.isArray(d) ? d : (d?.items || []))).catch(() => setTop([]))
  }, [])

  // workflow 응답을 차트 형태로 정규화 (상태별 카운트)
  const workflowChart = (() => {
    if (!workflow) return null
    if (workflow.labels && workflow.series) return workflow
    // {DRAFT:n, REVIEW:n, ...} 형태 폴백
    const entries = Object.entries(workflow).filter(([, v]) => typeof v === 'number')
    if (!entries.length) return null
    return { labels: entries.map(e => e[0]), series: [{ name: '콘텐츠', data: entries.map(e => e[1] as number) }] }
  })()

  const conversionRate = sum.totalViews ? ((sum.totalConversions || 0) / sum.totalViews * 100).toFixed(1) : '0.0'

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold">콘텐츠 개요</h1>
          <p className="text-sm text-slate-400 mt-0.5">게시 현황 · 워크플로우 · 콘텐츠 성과 통합 뷰</p>
        </div>
        <Link to="/ai-tools" className="flex items-center gap-1.5 text-sm text-brand hover:underline">
          <Sparkles size={16} /> AI 도구 열기 <ArrowRight size={14} />
        </Link>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        {cards.map(({ key, label, icon: Icon, color }) => (
          <div key={key} className="bg-card border border-edge rounded-xl p-4">
            <div className="flex items-center gap-1.5 text-xs text-slate-400"><Icon size={13} /> {label}</div>
            <div className={`text-2xl font-bold mt-2 ${color}`}>
              {Number((sum as any)[key] ?? 0).toLocaleString()}
            </div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mb-6">
        <Card title="게시 워크플로우 현황" icon={<FileSearch size={15} />} className="lg:col-span-2">
          <Chart type="BAR" data={workflowChart || undefined} />
        </Card>
        <Card title="전환율" icon={<Target size={15} />}>
          <div className="flex flex-col items-center justify-center h-[240px]">
            <div className="text-5xl font-bold text-accent">{conversionRate}%</div>
            <div className="text-sm text-slate-400 mt-3">
              전환 {Number(sum.totalConversions ?? 0).toLocaleString()} / 조회 {Number(sum.totalViews ?? 0).toLocaleString()}
            </div>
          </div>
        </Card>
      </div>

      <Card title="인기 콘텐츠 TOP" icon={<Eye size={15} />}>
        {top.length === 0 ? (
          <p className="text-slate-500 text-sm py-2">데이터가 없습니다.</p>
        ) : (
          <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.slice(0, 8).map((c: any, i: number) => (
                <tr key={c.id ?? 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>
  )
}
