import { useState } from 'react'
import { guardiaApi } from '../api/clients'
import { Btn } from '../components/common/Btn'

interface ImportResult {
  status: string
  message: string
  total?: number
  imported?: number
  sections?: Record<string, { count: number; status: string; imported?: number }>
  manifest?: { exported_at: string; source: string; exported_by: string }
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: '20px 24px' }}>
      <h3 style={{ fontSize: 14, fontWeight: 700, color: '#1a3a6b', margin: '0 0 16px' }}>{title}</h3>
      {children}
    </div>
  )
}

function Toast({ msg, ok, onClose }: { msg: string; ok: boolean; onClose: () => void }) {
  return (
    <div style={{ position:'fixed', bottom:24, right:24, zIndex:9999,
      background:'#1e293b', color:'#fff', padding:'12px 20px', borderRadius:8,
      fontSize:13, display:'flex', gap:10, alignItems:'center',
      borderLeft:`4px solid ${ok ? '#22c55e' : '#ef4444'}`,
      boxShadow:'0 4px 20px rgba(0,0,0,.2)' }}>
      <span>{ok ? '✅' : '❌'}</span><span>{msg}</span>
      <button onClick={onClose} style={{ background:'none', border:'none', color:'#94a3b8', cursor:'pointer', marginLeft:8 }}>✕</button>
    </div>
  )
}

export default function ExportImport() {
  const [exporting, setExporting] = useState<string | null>(null)
  const [uploading, setUploading] = useState(false)
  const [importFile, setImportFile] = useState<File | null>(null)
  const [dryRun, setDryRun] = useState(true)
  const [result, setResult] = useState<ImportResult | null>(null)
  const [toast, setToast] = useState<{ msg: string; ok: boolean } | null>(null)

  const showToast = (msg: string, ok = true) => {
    setToast({ msg, ok }); setTimeout(() => setToast(null), 4000)
  }

  const doExport = async (type: 'bundle' | 'sr' | 'cmdb' | 'institutions' | 'audit') => {
    setExporting(type)
    try {
      const isBundle = type === 'bundle'
      const url = `/api/export-import/export/${type}`
      const r = await guardiaApi.get(url, { responseType: isBundle ? 'blob' : 'json' })

      if (isBundle) {
        const blob = new Blob([r.data], { type: 'application/zip' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = `guardia_bundle_${new Date().toISOString().slice(0,10)}.zip`
        link.click(); URL.revokeObjectURL(link.href)
        showToast('번들 다운로드 완료')
      } else {
        const json = JSON.stringify(r.data, null, 2)
        const blob = new Blob([json], { type: 'application/json' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = `guardia_${type}_${new Date().toISOString().slice(0,10)}.json`
        link.click(); URL.revokeObjectURL(link.href)
        showToast(`${type} Export 완료 (${r.data.count}건)`)
      }
    } catch (e: unknown) {
      showToast((e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? 'Export 실패', false)
    } finally { setExporting(null) }
  }

  const doImport = async () => {
    if (!importFile) return
    setUploading(true); setResult(null)
    try {
      const form = new FormData()
      form.append('file', importFile)
      const endpoint = importFile.name.endsWith('.zip')
        ? `/api/export-import/import/bundle?dry_run=${dryRun}`
        : `/api/export-import/import/sr?dry_run=${dryRun}`
      const r = await guardiaApi.post<ImportResult>(endpoint, form, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      setResult(r.data)
      showToast(r.data.message)
    } catch (e: unknown) {
      showToast((e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? 'Import 실패', false)
    } finally { setUploading(false) }
  }

  const EXPORTS = [
    { type: 'bundle' as const, icon: '📦', label: '전체 번들 (ZIP)', desc: 'SR + CMDB + 기관 + 감사로그 패키징', primary: true },
    { type: 'sr' as const,     icon: '📋', label: 'SR 목록',    desc: '서비스 요청 전체 JSON' },
    { type: 'cmdb' as const,   icon: '🖥️', label: 'CMDB 자산',  desc: '서버 자산 목록 JSON' },
    { type: 'institutions' as const, icon: '🏛️', label: '기관 목록', desc: '등록된 기관 정보 JSON' },
    { type: 'audit' as const,  icon: '📜', label: '감사 로그',  desc: '최근 1000건 감사 로그 JSON' },
  ]

  return (
    <>
      {toast && <Toast msg={toast.msg} ok={toast.ok} onClose={() => setToast(null)} />}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        {/* 안내 배너 */}
        <div style={{ background: '#eff2ff', border: '1px solid #c7d2fe', borderRadius: 10,
          padding: '14px 20px', display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <span style={{ fontSize: 24, flexShrink: 0 }}>🔄</span>
          <div>
            <div style={{ fontWeight: 700, color: '#1a3a6b', marginBottom: 4 }}>폐쇄망 ↔ 개방망 데이터 연동</div>
            <div style={{ fontSize: 12, color: '#475569', lineHeight: 1.6 }}>
              폐쇄망 GUARDiA 시스템의 데이터(SR, CMDB, 기관, 감사로그)를 Export하여 이 관리 시스템으로 가져올 수 있습니다.<br/>
              번들 ZIP에는 HMAC-SHA256 서명이 포함되어 위변조를 방지합니다. 민감 정보(IP, 비밀번호)는 자동으로 마스킹됩니다.
            </div>
          </div>
        </div>

        {/* Export 섹션 */}
        <Section title="📤 Export — 데이터 내보내기">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
            {EXPORTS.map(e => (
              <div key={e.type} style={{
                border: `1px solid ${e.primary ? '#4f6ef7' : '#e2e8f0'}`,
                borderRadius: 8, padding: '14px 16px',
                background: e.primary ? '#eff2ff' : '#f8fafc',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                  <span style={{ fontSize: 20 }}>{e.icon}</span>
                  <span style={{ fontWeight: 700, fontSize: 13 }}>{e.label}</span>
                  {e.primary && <span style={{ fontSize: 10, background: '#4f6ef7', color: '#fff',
                    padding: '1px 6px', borderRadius: 8 }}>권장</span>}
                </div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 10 }}>{e.desc}</div>
                <Btn variant={e.primary ? 'primary' : 'outline'} size="sm"
                  loading={exporting === e.type}
                  onClick={() => doExport(e.type)}>
                  ⬇ 다운로드
                </Btn>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 12, fontSize: 11, color: '#94a3b8' }}>
            📌 폐쇄망 GUARDiA 서버에서: <code>GET http://localhost:8001/api/export-import/export/bundle</code> (Bearer 토큰 필요)
          </div>
        </Section>

        {/* Import 섹션 */}
        <Section title="📥 Import — 데이터 가져오기">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 16, alignItems: 'start' }}>
            <div>
              {/* 파일 업로드 */}
              <div style={{ border: '2px dashed #e2e8f0', borderRadius: 8, padding: '28px 20px',
                textAlign: 'center', marginBottom: 14, cursor: 'pointer',
                background: importFile ? '#f0fdf4' : '#f8fafc',
                borderColor: importFile ? '#22c55e' : '#e2e8f0',
                transition: 'all .2s' }}
                onClick={() => document.getElementById('import-file')?.click()}
                onDragOver={e => e.preventDefault()}
                onDrop={e => { e.preventDefault(); const f = e.dataTransfer.files[0]; if (f) setImportFile(f) }}>
                <div style={{ fontSize: 32, marginBottom: 8 }}>{importFile ? '✅' : '📁'}</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: importFile ? '#16a34a' : '#475569' }}>
                  {importFile ? importFile.name : '파일을 드래그하거나 클릭하여 선택'}
                </div>
                <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 4 }}>
                  .zip (전체 번들) 또는 .json (SR 목록) 지원
                </div>
                <input id="import-file" type="file" accept=".zip,.json" style={{ display: 'none' }}
                  onChange={e => setImportFile(e.target.files?.[0] ?? null)} />
              </div>

              {/* 옵션 */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 14 }}>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer' }}>
                  <input type="checkbox" checked={dryRun}
                    onChange={e => setDryRun(e.target.checked)}
                    style={{ width: 16, height: 16, accentColor: '#4f6ef7' }} />
                  <span>
                    <strong>Dry Run</strong>
                    <span style={{ color: '#64748b' }}> — 검증만 (실제 저장 안 함)</span>
                  </span>
                </label>
                {!dryRun && (
                  <span style={{ fontSize: 11, background: '#fff3cd', color: '#856404',
                    padding: '3px 10px', borderRadius: 6, border: '1px solid #ffc107' }}>
                    ⚠️ 실제 DB에 저장됩니다
                  </span>
                )}
              </div>

              <div style={{ display: 'flex', gap: 10 }}>
                <Btn variant="primary" loading={uploading} disabled={!importFile} onClick={doImport}>
                  {dryRun ? '🔍 검증 실행' : '📥 Import 실행'}
                </Btn>
                {importFile && (
                  <Btn onClick={() => { setImportFile(null); setResult(null) }}>파일 제거</Btn>
                )}
              </div>
            </div>

            {/* 결과 패널 */}
            {result && (
              <div style={{ minWidth: 320, background: result.status === 'error' ? '#fff1f2' : '#f0fdf4',
                border: `1px solid ${result.status === 'error' ? '#fecaca' : '#bbf7d0'}`,
                borderRadius: 8, padding: '16px 18px' }}>
                <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 10,
                  color: result.status === 'error' ? '#dc2626' : '#16a34a' }}>
                  {result.status === 'dry_run' ? '🔍 검증 결과' :
                   result.status === 'imported' ? '✅ Import 완료' : '❌ 오류'}
                </div>
                {result.manifest && (
                  <div style={{ fontSize: 12, color: '#475569', marginBottom: 10 }}>
                    <div>출처: {result.manifest.source}</div>
                    <div>Export 일시: {result.manifest.exported_at?.slice(0, 16)}</div>
                    <div>Export 담당자: {result.manifest.exported_by}</div>
                  </div>
                )}
                {result.sections && (
                  <div>
                    {Object.entries(result.sections).map(([name, s]) => (
                      <div key={name} style={{ display: 'flex', justifyContent: 'space-between',
                        fontSize: 12, padding: '4px 0', borderBottom: '1px solid rgba(0,0,0,.05)' }}>
                        <span style={{ color: '#475569' }}>{name}</span>
                        <span style={{ fontWeight: 600 }}>{s.count}건{s.imported !== undefined ? ` (${s.imported}건 저장)` : ''}</span>
                      </div>
                    ))}
                  </div>
                )}
                {(result.total !== undefined) && (
                  <div style={{ marginTop: 8, fontSize: 12, color: '#475569' }}>
                    전체 {result.total}건 중 {result.imported ?? 0}건 저장
                  </div>
                )}
              </div>
            )}
          </div>
        </Section>

        {/* 연동 흐름 안내 */}
        <Section title="🔄 연동 흐름 가이드">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 0,
            alignItems: 'center', textAlign: 'center' }}>
            {[
              { icon: '🖥️', label: '폐쇄망\nGUARDiA', sub: 'localhost:8001' },
              { icon: '→', label: '', sub: '' },
              { icon: '📦', label: 'Export\nBundle ZIP', sub: 'HMAC 서명' },
              { icon: '→', label: '', sub: '' },
              { icon: '☁️', label: 'zio 서버\nManager', sub: 'import/bundle' },
            ].map((item, i) => (
              item.icon === '→' ? (
                <div key={i} style={{ fontSize: 24, color: '#94a3b8' }}>→</div>
              ) : (
                <div key={i} style={{ background: '#f8fafc', border: '1px solid #e2e8f0',
                  borderRadius: 8, padding: '14px 8px' }}>
                  <div style={{ fontSize: 28 }}>{item.icon}</div>
                  <div style={{ fontSize: 12, fontWeight: 600, color: '#1e293b',
                    whiteSpace: 'pre-line', marginTop: 6 }}>{item.label}</div>
                  <div style={{ fontSize: 10, color: '#94a3b8', marginTop: 2 }}>{item.sub}</div>
                </div>
              )
            ))}
          </div>
          <div style={{ marginTop: 14, fontSize: 11, color: '#94a3b8', lineHeight: 1.7 }}>
            1. 폐쇄망 서버에서 <code>GET /api/export-import/export/bundle</code> 호출 → ZIP 다운로드<br/>
            2. USB/보안매체로 이 화면에 접속<br/>
            3. ZIP 파일 업로드 → [🔍 검증 실행]으로 내용 확인<br/>
            4. Dry Run 해제 → [📥 Import 실행]으로 실제 반영<br/>
            5. 중복 SR(sr_id 기준)은 자동 SKIP
          </div>
        </Section>
      </div>
    </>
  )
}
