import { useQuery } from '@tanstack/react-query'
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts'
import { StatCard, Spinner } from '../components/ui'
import { getDashboard } from '../api/client'

const COLORS = ['#3ddc97', '#ef4444', '#f59e0b', '#00a0c8']
const tt = { background: '#1a2234', border: '1px solid #26304a', color: '#fff' }

export default function Dashboard() {
  const tenant = localStorage.getItem('sgn_tenant')
  const { data: d, isLoading } = useQuery({
    queryKey: ['dashboard', tenant],
    queryFn: () => getDashboard(tenant && tenant !== 'ALL' ? tenant : undefined),
    refetchInterval: 30000,
  })

  if (isLoading) return <Spinner />
  if (!d) return <div className="text-red-400 p-8">데이터를 가져올 수 없습니다.</div>

  const deviceData = [
    { name: '온라인', value: d.onlineDevices || 0 },
    { name: '오프라인', value: d.offlineDevices || 0 },
  ]
  const transferData = [
    { name: '오늘 작업', value: d.totalWorkToday || 0 },
    { name: '완료', value: d.completedWorkToday || 0 },
    { name: 'POS 대기', value: d.pendingPosCvt || 0 },
    { name: 'POS 처리', value: d.processedPosCvtToday || 0 },
  ]

  return (
    <div className="space-y-6">
      <h1 className="text-xl font-semibold text-white">대시보드</h1>

      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
        <StatCard title="전체 매장"   value={d.totalStores || 0}      icon="store"     color="brand" />
        <StatCard title="운영 매장"   value={d.activeStores || 0}     icon="store"     color="green" />
        <StatCard title="온라인 장치" value={d.onlineDevices || 0}    icon="signboard" color="green" />
        <StatCard title="오프라인 장치" value={d.offlineDevices || 0} icon="gateway"   color="orange" />
        <StatCard title="미해결 알람" value={d.unresolvedAlarms || 0} icon="alarm"     color="red" />
        <StatCard title="긴급 알람"   value={d.criticalAlarms || 0}   icon="warn"      color="red" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div className="bg-card border border-edge rounded-lg p-4">
          <h2 className="text-sm font-medium text-gray-300 mb-4">디바이스 상태 현황</h2>
          <ResponsiveContainer width="100%" height={220}>
            <PieChart>
              <Pie data={deviceData} cx="50%" cy="50%" outerRadius={75} dataKey="value"
                label={({ name, value }) => `${name}: ${value}`}>
                {deviceData.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
              </Pie>
              <Tooltip contentStyle={tt} />
            </PieChart>
          </ResponsiveContainer>
        </div>

        <div className="bg-card border border-edge rounded-lg p-4">
          <h2 className="text-sm font-medium text-gray-300 mb-4">전송 · 처리 현황 (오늘)</h2>
          <ResponsiveContainer width="100%" height={220}>
            <BarChart data={transferData}>
              <XAxis dataKey="name" tick={{ fill: '#9ca3af', fontSize: 11 }} />
              <YAxis tick={{ fill: '#9ca3af', fontSize: 11 }} allowDecimals={false} />
              <Tooltip contentStyle={tt} cursor={{ fill: 'rgba(0,160,200,0.08)' }} />
              <Bar dataKey="value" fill="#00a0c8" radius={[3, 3, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {[
          { t: '오늘 작업', v: d.totalWorkToday || 0, s: `완료: ${d.completedWorkToday || 0}`, c: 'text-brand' },
          { t: '전체 알람', v: d.totalAlarms || 0, s: `미해결: ${d.unresolvedAlarms || 0}`, c: 'text-yellow-400' },
          { t: '전체 장치', v: d.totalDevices || 0, s: `오프라인: ${d.offlineDevices || 0}`, c: 'text-accent' },
          { t: 'POS 처리(오늘)', v: d.processedPosCvtToday || 0, s: `대기: ${d.pendingPosCvt || 0}`, c: 'text-green-400' },
        ].map(x => (
          <div key={x.t} className="bg-card border border-edge rounded-lg p-4">
            <p className="text-xs text-gray-400">{x.t}</p>
            <p className={`text-2xl font-bold ${x.c}`}>{x.v}</p>
            <p className="text-xs text-gray-500">{x.s}</p>
          </div>
        ))}
      </div>
    </div>
  )
}
