import { useQuery } from '@tanstack/react-query'
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts'
import { Store, Bell, Cpu, ClipboardList, RefreshCw, AlertTriangle } from 'lucide-react'
import StatCard from '../components/StatCard'
import { getDashboard } from '../api/client'

const COLORS = ['#00a0c8','#3ddc97','#f59e0b','#ef4444']

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

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

  const deviceData = [
    { name: 'ONLINE',  value: d.onlineDevices  || 0 },
    { name: 'OFFLINE', value: d.offlineDevices || 0 },
  ]

  const workData = [
    { 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.unresolvedAlarms || 0} icon={Bell}         color="red" />
        <StatCard title="긴급 알람"      value={d.criticalAlarms || 0} icon={AlertTriangle} color="red" />
        <StatCard title="온라인 장치"    value={d.onlineDevices || 0}  icon={Cpu}           color="green" />
        <StatCard title="POS 대기"       value={d.pendingPosCvt || 0}  icon={RefreshCw}     color="yellow" />
      </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={200}>
            <PieChart>
              <Pie data={deviceData} cx="50%" cy="50%" outerRadius={70}
                   dataKey="value" label={({ name, value }) => `${name}: ${value}`}>
                {deviceData.map((_, i) => (
                  <Cell key={i} fill={COLORS[i % COLORS.length]} />
                ))}
              </Pie>
              <Tooltip contentStyle={{ background: '#1a2234', border: '1px solid #26304a', color: '#fff' }} />
            </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">오늘의 작업/POS 현황</h2>
          <ResponsiveContainer width="100%" height={200}>
            <BarChart data={workData}>
              <XAxis dataKey="name" tick={{ fill: '#9ca3af', fontSize: 11 }} />
              <YAxis tick={{ fill: '#9ca3af', fontSize: 11 }} />
              <Tooltip contentStyle={{ background: '#1a2234', border: '1px solid #26304a', color: '#fff' }} />
              <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">
        <div className="bg-card border border-edge rounded-lg p-4">
          <p className="text-xs text-gray-400">오늘 작업</p>
          <p className="text-2xl font-bold text-brand">{d.totalWorkToday || 0}</p>
          <p className="text-xs text-gray-500">완료: {d.completedWorkToday || 0}</p>
        </div>
        <div className="bg-card border border-edge rounded-lg p-4">
          <p className="text-xs text-gray-400">전체 알람</p>
          <p className="text-2xl font-bold text-yellow-400">{d.totalAlarms || 0}</p>
          <p className="text-xs text-gray-500">미해결: {d.unresolvedAlarms || 0}</p>
        </div>
        <div className="bg-card border border-edge rounded-lg p-4">
          <p className="text-xs text-gray-400">전체 장치</p>
          <p className="text-2xl font-bold text-accent">{d.totalDevices || 0}</p>
          <p className="text-xs text-gray-500">오프라인: {d.offlineDevices || 0}</p>
        </div>
        <div className="bg-card border border-edge rounded-lg p-4">
          <p className="text-xs text-gray-400">POS 처리(오늘)</p>
          <p className="text-2xl font-bold text-green-400">{d.processedPosCvtToday || 0}</p>
          <p className="text-xs text-gray-500">대기: {d.pendingPosCvt || 0}</p>
        </div>
      </div>
    </div>
  )
}
