import { useEffect, useState } from 'react'
import { guardiaApi } from '../api/clients'

interface NetworkDevice {
  id: number; device_name: string; device_type: string
  vendor: string; model?: string; os_type: string
  location?: string; inst_id?: number; is_active: boolean
  last_backup_at?: string | null
}
interface BackupResult {
  success: boolean; device_name: string; backup_id?: number
  config_hash?: string; changed_lines?: number
  backed_up_at?: string; error?: string
}
interface DiffResult {
  success: boolean; changed: boolean
  added_lines?: number; removed_lines?: number
  diff?: string[]; error?: string
  old_backed_up_at?: string; new_backed_up_at?: string
}

const DEVICE_ICON: Record<string, string> = {
  SWITCH: '🔀', ROUTER: '🔗', FIREWALL: '🛡️', LOAD_BALANCER: '⚖️',
}
const VENDOR_COLOR: Record<string, string> = {
  CISCO: '#1ba0d7', HUAWEI: '#cf0a2c', JUNIPER: '#84bd00',
  PIOLINK: '#003087', SECUI: '#0066cc', RADWARE: '#00a3e0',
}

export default function NetworkConsole() {
  const [devices,  setDevices]  = useState<NetworkDevice[]>([])
  const [loading,  setLoading]  = useState(true)
  const [backing,  setBacking]  = useState<number | null>(null)
  const [diffDev,  setDiffDev]  = useState<number | null>(null)
  const [diff,     setDiff]     = useState<DiffResult | null>(null)
  const [msg,      setMsg]      = useState('')
  const [filter,   setFilter]   = useState('')

  useEffect(() => {
    guardiaApi.get('/api/network/devices')
      .then(r => setDevices(r.data))
      .finally(() => setLoading(false))
  }, [])

  const doBackup = async (id: number, name: string) => {
    setBacking(id); setMsg('')
    try {
      const r = await guardiaApi.post(`/api/network/devices/${id}/backup`)
      const res: BackupResult = r.data
      const changed = res.changed_lines ? ` (변경 ${res.changed_lines}줄)` : ''
      setMsg(`✔ ${name} 백업 완료${changed}`)
      setDevices(prev => prev.map(d =>
        d.id === id ? { ...d, last_backup_at: res.backed_up_at ?? new Date().toISOString() } : d
      ))
    } catch (e: any) {
      setMsg(`✘ 백업 실패: ${e.response?.data?.detail ?? e.message}`)
    } finally { setBacking(null) }
  }

  const showDiff = async (id: number) => {
    if (diffDev === id) { setDiffDev(null); setDiff(null); return }
    setDiffDev(id); setDiff(null)
    try {
      const r = await guardiaApi.get(`/api/network/devices/${id}/diff`)
      setDiff(r.data)
    } catch (e: any) {
      setDiff({ success: false, changed: false, error: e.response?.data?.detail ?? e.message })
    }
  }

  const daysSince = (iso?: string | null) => {
    if (!iso) return null
    const diff = (Date.now() - new Date(iso).getTime()) / 86400000
    return Math.floor(diff)
  }

  const filtered = devices.filter(d =>
    !filter || d.device_name.toLowerCase().includes(filter.toLowerCase())
    || d.vendor.toLowerCase().includes(filter.toLowerCase())
    || d.device_type.toLowerCase().includes(filter.toLowerCase())
  )

  const noBackup = devices.filter(d => !d.last_backup_at).length
  const stale    = devices.filter(d => (daysSince(d.last_backup_at) ?? 999) > 7).length

  if (loading) return <div style={{ color: '#94a3b8', padding: 40 }}>로딩 중...</div>

  return (
    <div>
      {/* 요약 */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 24 }}>
        {[
          { label: '전체 장비', value: devices.length, color: '#1e293b' },
          { label: '미백업', value: noBackup, color: '#ef4444' },
          { label: '7일 이상 미백업', value: stale, color: '#f59e0b' },
          { label: '정상', value: devices.length - noBackup - stale, color: '#22c55e' },
        ].map(c => (
          <div key={c.label} style={{ background: '#fff', border: '1px solid #e2e8f0',
            borderRadius: 10, padding: '16px 22px', flex: 1 }}>
            <div style={{ fontSize: 12, color: '#64748b' }}>{c.label}</div>
            <div style={{ fontSize: 26, fontWeight: 700, color: c.color, marginTop: 4 }}>{c.value}</div>
          </div>
        ))}
      </div>

      {msg && (
        <div style={{ padding: '10px 16px', borderRadius: 8, marginBottom: 16,
          background: msg.startsWith('✔') ? '#f0fdf4' : '#fef2f2',
          color: msg.startsWith('✔') ? '#16a34a' : '#dc2626',
          border: `1px solid ${msg.startsWith('✔') ? '#bbf7d0' : '#fecaca'}`,
          fontSize: 13 }}>
          {msg}
        </div>
      )}

      {/* 검색 */}
      <div style={{ marginBottom: 16 }}>
        <input
          value={filter} onChange={e => setFilter(e.target.value)}
          placeholder="장비명 / 벤더 / 타입 검색..."
          style={{ padding: '8px 14px', border: '1px solid #e2e8f0', borderRadius: 8,
            fontSize: 13, width: 300, outline: 'none' }}
        />
      </div>

      {/* 장비 테이블 */}
      <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10,
        overflow: 'hidden', marginBottom: 16 }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#f8fafc' }}>
              {['장비명','타입','벤더/모델','위치','최근 백업','상태','액션'].map(h => (
                <th key={h} style={{ padding: '10px 14px', textAlign: 'left',
                  fontWeight: 600, color: '#475569', fontSize: 12,
                  borderBottom: '1px solid #e2e8f0' }}>
                  {h}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.map(d => {
              const days = daysSince(d.last_backup_at)
              const backupStatus = !d.last_backup_at ? 'none'
                : (days ?? 0) > 7 ? 'stale' : 'ok'
              return (
                <>
                  <tr key={d.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
                    <td style={{ padding: '10px 14px', fontWeight: 600, color: '#1e293b' }}>
                      {DEVICE_ICON[d.device_type] ?? '🔧'} {d.device_name}
                    </td>
                    <td style={{ padding: '10px 14px', color: '#475569' }}>{d.device_type}</td>
                    <td style={{ padding: '10px 14px' }}>
                      <span style={{ fontWeight: 700, color: VENDOR_COLOR[d.vendor] ?? '#475569' }}>
                        {d.vendor}
                      </span>
                      {d.model && <span style={{ color: '#94a3b8', fontSize: 11, marginLeft: 6 }}>
                        {d.model}
                      </span>}
                    </td>
                    <td style={{ padding: '10px 14px', color: '#64748b', fontSize: 12 }}>
                      {d.location ?? '-'}
                    </td>
                    <td style={{ padding: '10px 14px', fontSize: 12 }}>
                      {!d.last_backup_at
                        ? <span style={{ color: '#ef4444', fontWeight: 600 }}>미백업</span>
                        : <span style={{ color: (days ?? 0) > 7 ? '#f59e0b' : '#64748b' }}>
                            {days}일 전
                          </span>}
                    </td>
                    <td style={{ padding: '10px 14px' }}>
                      {backupStatus === 'ok'    && <span style={{ color:'#22c55e', fontWeight:700 }}>✔ 정상</span>}
                      {backupStatus === 'stale' && <span style={{ color:'#f59e0b', fontWeight:700 }}>⚠ 갱신 필요</span>}
                      {backupStatus === 'none'  && <span style={{ color:'#ef4444', fontWeight:700 }}>✘ 미백업</span>}
                    </td>
                    <td style={{ padding: '10px 14px' }}>
                      <div style={{ display: 'flex', gap: 6 }}>
                        <button onClick={() => doBackup(d.id, d.device_name)}
                          disabled={backing === d.id}
                          style={{ padding: '4px 10px', fontSize: 11, borderRadius: 6,
                            background: backing === d.id ? '#e2e8f0' : '#4f6ef7',
                            color: backing === d.id ? '#94a3b8' : '#fff',
                            border: 'none', cursor: backing === d.id ? 'not-allowed' : 'pointer' }}>
                          {backing === d.id ? '백업 중..' : '백업'}
                        </button>
                        <button onClick={() => showDiff(d.id)}
                          style={{ padding: '4px 10px', fontSize: 11, borderRadius: 6,
                            background: diffDev === d.id ? '#1e293b' : '#f1f5f9',
                            color: diffDev === d.id ? '#fff' : '#475569',
                            border: '1px solid #e2e8f0', cursor: 'pointer' }}>
                          Diff
                        </button>
                      </div>
                    </td>
                  </tr>
                  {diffDev === d.id && diff && (
                    <tr key={`diff-${d.id}`}>
                      <td colSpan={7} style={{ padding: '12px 20px', background: '#f8fafc',
                        borderBottom: '1px solid #e2e8f0' }}>
                        {diff.success ? (
                          diff.changed ? (
                            <div>
                              <div style={{ fontSize: 12, color: '#475569', marginBottom: 8 }}>
                                ⚡ 설정 변경 감지 — 추가 {diff.added_lines}줄 / 제거 {diff.removed_lines}줄
                              </div>
                              <pre style={{ fontSize: 11, background: '#1e293b', color: '#e2e8f0',
                                borderRadius: 6, padding: 12, overflow: 'auto', maxHeight: 200,
                                margin: 0 }}>
                                {(diff.diff ?? []).join('\n')}
                              </pre>
                            </div>
                          ) : (
                            <span style={{ fontSize: 12, color: '#22c55e' }}>✔ 변경 없음</span>
                          )
                        ) : (
                          <span style={{ fontSize: 12, color: '#ef4444' }}>{diff.error}</span>
                        )}
                      </td>
                    </tr>
                  )}
                </>
              )
            })}
            {filtered.length === 0 && (
              <tr><td colSpan={7} style={{ padding: 40, textAlign: 'center', color: '#94a3b8' }}>
                {devices.length === 0 ? '등록된 네트워크 장비가 없습니다.' : '검색 결과 없음'}
              </td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
