import { useEffect, useState } from 'react'
import {
  LineChart, Line, BarChart, Bar, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
} from 'recharts'
import { StatCard } from '../components/common/StatCard'
import { guardiaApi, managerApi } from '../api/clients'
import type { DashboardStats, SystemResources } from '../api/types'

/* ── 색상 팔레트 ── */
const PIE_COLORS = { running:'#22c55e', stopped:'#94a3b8', error:'#ef4444', unknown:'#cbd5e1' }

/* ── 서브 컴포넌트 ── */
function Card({ title, children, style }: { title: string; children: React.ReactNode; style?: React.CSSProperties }) {
  return (
    <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10,
      padding: '18px 22px', ...style }}>
      <h3 style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', margin: '0 0 14px' }}>{title}</h3>
      {children}
    </div>
  )
}

function Gauge({ label, pct, detail }: { label: string; pct: number; detail?: string }) {
  const color = pct > 90 ? '#ef4444' : pct > 70 ? '#f59e0b' : '#22c55e'
  return (
    <div style={{ flex: 1 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 5 }}>
        <span style={{ fontWeight: 600 }}>{label}</span>
        <span style={{ color, fontWeight: 700 }}>{pct}%</span>
      </div>
      <div style={{ height: 8, background: '#f1f5f9', borderRadius: 4, overflow: 'hidden' }}>
        <div style={{ height: '100%', width: `${pct}%`, background: color,
          borderRadius: 4, transition: 'width .6s ease' }} />
      </div>
      {detail && <div style={{ fontSize: 10, color: '#94a3b8', marginTop: 3 }}>{detail}</div>}
    </div>
  )
}

/* ── Mock 데이터 생성 ── */
function genTrend() {
  const days = ['월','화','수','목','금','토','일']
  return days.map(d => ({
    day: d,
    created:   Math.floor(Math.random() * 15) + 3,
    completed: Math.floor(Math.random() * 12) + 2,
  }))
}

function genPriorityData(stats: DashboardStats) {
  return [
    { name: 'CRITICAL', value: stats.critical_count   || 2,  fill: '#ef4444' },
    { name: 'HIGH',     value: Math.floor((stats.open_tasks || 8) * .3), fill: '#f59e0b' },
    { name: 'MEDIUM',   value: Math.floor((stats.open_tasks || 8) * .5), fill: '#3b82f6' },
    { name: 'LOW',      value: Math.floor((stats.open_tasks || 8) * .2), fill: '#22c55e' },
  ]
}

export default function Dashboard() {
  const [stats, setStats]       = useState<DashboardStats | null>(null)
  const [res, setRes]           = useState<SystemResources | null>(null)
  const [svcs, setSvcs]         = useState<Record<string, string>>({})
  const [deployLog, setDeployLog] = useState<string[]>([])
  const [trend] = useState(genTrend)

  useEffect(() => {
    guardiaApi.get('/api/dashboard').then(r => setStats(r.data)).catch(() => {})
    managerApi.get('/api/system/resources').then(r => setRes(r.data)).catch(() => {})
    managerApi.get('/api/system/services').then(r => setSvcs(r.data)).catch(() => {})
    managerApi.get('/api/deploy/history').then(r => setDeployLog(r.data?.lines ?? [])).catch(() => {})

    const timer = setInterval(() => {
      managerApi.get('/api/system/resources').then(r => setRes(r.data)).catch(() => {})
    }, 30000)
    return () => clearInterval(timer)
  }, [])

  const svcList = Object.entries(svcs)
  const runningCount = svcList.filter(([, s]) => s === 'active').length
  const recentLogs = deployLog.slice(-6).reverse()

  const priorityData = stats ? genPriorityData(stats) : genPriorityData({
    total_tasks: 24, open_tasks: 8, in_progress_tasks: 5,
    completed_today: 3, critical_count: 2, pending_approvals: 1,
  })

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

      {/* ── 핵심 지표 카드 4개 ── */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <StatCard title="전체 SR" value={stats?.total_tasks ?? '-'}
          sub={`진행중 ${stats?.in_progress_tasks ?? 0}건`} icon="📋" color="#e8ecff" />
        <StatCard title="긴급 인시던트" value={stats?.critical_count ?? '-'}
          sub="CRITICAL 등급" icon="🚨" color="#fff1f2" />
        <StatCard title="서비스 가용"
          value={svcList.length ? `${runningCount}/${svcList.length}` : '-'}
          sub="실행중 서비스" icon="🖥️" color="#f0fdf4" />
        <StatCard title="승인 대기" value={stats?.pending_approvals ?? '-'}
          sub="검토 필요" icon="⏳" color="#fff7ed" />
      </div>

      {/* ── 차트 행 1: SR 추이 + 우선순위 파이 ── */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16 }}>
        <Card title="📈 SR 생성 / 완료 추이 (7일)">
          <ResponsiveContainer width="100%" height={200}>
            <LineChart data={trend} margin={{ top: 5, right: 10, left: -20, bottom: 5 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f2f5" />
              <XAxis dataKey="day" tick={{ fontSize: 11, fill: '#94a3b8' }} />
              <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} />
              <Tooltip contentStyle={{ borderRadius: 8, border: '1px solid #e2e8f0', fontSize: 12 }} />
              <Legend wrapperStyle={{ fontSize: 12 }} />
              <Line type="monotone" dataKey="created"   name="신규 SR"
                stroke="#4f6ef7" strokeWidth={2} dot={{ r: 3 }} activeDot={{ r: 5 }} />
              <Line type="monotone" dataKey="completed" name="완료 SR"
                stroke="#22c55e" strokeWidth={2} dot={{ r: 3 }} activeDot={{ r: 5 }} />
            </LineChart>
          </ResponsiveContainer>
        </Card>

        <Card title="🎯 SR 우선순위 분포">
          <ResponsiveContainer width="100%" height={200}>
            <PieChart>
              <Pie data={priorityData} cx="50%" cy="50%"
                innerRadius={45} outerRadius={75} paddingAngle={2} dataKey="value">
                {priorityData.map((e, i) => <Cell key={i} fill={e.fill} />)}
              </Pie>
              <Tooltip formatter={(v, n) => [`${v}건`, n]} />
              <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11 }} />
            </PieChart>
          </ResponsiveContainer>
        </Card>
      </div>

      {/* ── 서버 리소스 게이지 ── */}
      {res ? (
        <Card title="💻 서버 리소스 모니터링">
          <div style={{ display: 'flex', gap: 32 }}>
            <Gauge label="CPU"
              pct={Math.round(res.cpu_percent)}
              detail={`${res.cpu_percent.toFixed(1)}% 사용 중`} />
            <Gauge label="메모리"
              pct={Math.round(res.memory.percent)}
              detail={`${res.memory.used_gb}GB / ${res.memory.total_gb}GB`} />
            <Gauge label="디스크"
              pct={Math.round(res.disk.percent)}
              detail={`${res.disk.used_gb}GB / ${res.disk.total_gb}GB`} />
          </div>
        </Card>
      ) : (
        <Card title="💻 서버 리소스 모니터링">
          <div style={{ color: '#94a3b8', fontSize: 13, padding: '8px 0' }}>
            Manager Backend에 연결 중... <a href="/config/env" style={{ color: '#4f6ef7' }}>설정 확인</a>
          </div>
        </Card>
      )}

      {/* ── 서비스 상태 + 배포 이력 ── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <Card title="🔧 서비스 상태">
          {svcList.length > 0 ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
              {svcList.map(([name, status]) => (
                <div key={name} style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  padding: '8px 10px', background: '#f8fafc', borderRadius: 7,
                  border: '1px solid #f1f5f9',
                }}>
                  <span style={{ fontSize: 12, fontWeight: 500 }}>{name}</span>
                  <span style={{
                    fontSize: 10, fontWeight: 600, padding: '2px 7px', borderRadius: 10,
                    background: status === 'active' ? '#dcfce7' : '#fee2e2',
                    color: status === 'active' ? '#16a34a' : '#dc2626',
                  }}>
                    {status === 'active' ? '실행중' : status}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <div style={{ color: '#94a3b8', fontSize: 13 }}>서비스 정보를 불러오는 중...</div>
          )}
        </Card>

        <Card title="🚀 최근 배포 이력">
          {recentLogs.length > 0 ? (
            <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
              {recentLogs.map((line, i) => {
                const ok = line.includes('완료') || line.includes('DONE') || line.includes('success')
                const isErr = line.includes('실패') || line.includes('ERROR') || line.includes('error')
                const ts = line.match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/)?.[0] ?? ''
                const msg = line.replace(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3} \w+ /, '').trim().slice(0, 55)
                return (
                  <li key={i} style={{
                    display: 'flex', gap: 8, padding: '8px 0', fontSize: 12,
                    borderBottom: i < recentLogs.length - 1 ? '1px solid #f1f5f9' : 'none',
                  }}>
                    <span>{ok ? '✅' : isErr ? '❌' : '🔄'}</span>
                    <span style={{ flex: 1, color: '#1e293b', overflow: 'hidden',
                      textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{msg}</span>
                    <span style={{ color: '#94a3b8', whiteSpace: 'nowrap' }}>{ts.slice(11)}</span>
                  </li>
                )
              })}
            </ul>
          ) : (
            <div style={{ color: '#94a3b8', fontSize: 13 }}>배포 이력이 없습니다.</div>
          )}
        </Card>
      </div>

      {/* ── SR 상태별 막대 차트 ── */}
      <Card title="📊 SR 처리 현황 (상태별)">
        <ResponsiveContainer width="100%" height={160}>
          <BarChart layout="vertical" margin={{ left: 20, right: 20, top: 5, bottom: 5 }}
            data={[
              { name: '신규 접수',  count: stats?.open_tasks ?? 8,           fill: '#4f6ef7' },
              { name: '진행 중',    count: stats?.in_progress_tasks ?? 5,    fill: '#f59e0b' },
              { name: '오늘 완료',  count: stats?.completed_today ?? 3,      fill: '#22c55e' },
              { name: '승인 대기',  count: stats?.pending_approvals ?? 1,    fill: '#94a3b8' },
            ]}>
            <CartesianGrid strokeDasharray="3 3" stroke="#f0f2f5" horizontal={false} />
            <XAxis type="number" tick={{ fontSize: 11, fill: '#94a3b8' }} />
            <YAxis type="category" dataKey="name" tick={{ fontSize: 12, fill: '#475569' }} width={70} />
            <Tooltip />
            <Bar dataKey="count" name="건수" radius={[0,4,4,0]}>
              {[{ fill:'#4f6ef7' },{ fill:'#f59e0b' },{ fill:'#22c55e' },{ fill:'#94a3b8' }].map((e, i) => (
                <Cell key={i} fill={e.fill} />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </Card>

    </div>
  )
}
