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

interface AppVersion {
  id: number; version: string; platform: string
  download_count: number; is_latest: boolean
  qr_url: string; landing_url: string
  file_size_mb: number; release_notes: string; created_at: string
}

export default function AppDistribution() {
  const [versions, setVersions] = useState<AppVersion[]>([])
  const [latest, setLatest] = useState<any>(null)
  const [stats, setStats] = useState<any>(null)
  const [uploading, setUploading] = useState(false)
  const [version, setVersion] = useState('')
  const [notes, setNotes] = useState('')
  const [iosUrl, setIosUrl] = useState('')
  const [externalUrl, setExternalUrl] = useState('')
  const [tab, setTab] = useState<'upload'|'url'>('upload')
  const fileRef = useRef<HTMLInputElement>(null)

  useEffect(() => { load() }, [])

  async function load() {
    const [v, l, s] = await Promise.all([
      guardiaApi.get('/api/app/versions').then((r: any) => r.data).catch(() => []),
      guardiaApi.get('/api/app/latest').then((r: any) => r.data).catch(() => null),
      guardiaApi.get('/api/app/stats').then((r: any) => r.data).catch(() => null),
    ])
    setVersions(v); setLatest(l); setStats(s)
  }

  async function uploadApk() {
    const file = fileRef.current?.files?.[0]
    if (!file || !version) return alert('APK 파일과 버전을 입력하세요')
    setUploading(true)
    try {
      const form = new FormData()
      form.append('file', file)
      form.append('version', version)
      form.append('release_notes', notes)
      form.append('ios_url', iosUrl)
      const r: any = await guardiaApi.post('/api/app/upload', form, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      alert(`✅ 배포 완료! 버전 ${version}\nQR 코드가 생성됐습니다.`)
      setVersion(''); setNotes(''); setIosUrl('')
      if (fileRef.current) fileRef.current.value = ''
      load()
    } catch (e: any) {
      alert(`오류: ${e.response?.data?.detail || e.message}`)
    } finally { setUploading(false) }
  }

  async function setUrl() {
    if (!externalUrl || !version) return alert('URL과 버전을 입력하세요')
    await guardiaApi.post('/api/app/url', {
      android_url: externalUrl, version, release_notes: notes, ios_url: iosUrl || undefined
    })
    alert('QR 코드 생성됨'); setExternalUrl(''); setVersion(''); setNotes('')
    load()
  }

  async function deleteVersion(id: number) {
    if (!confirm('이 버전을 삭제하시겠습니까?')) return
    await guardiaApi.delete(`/api/app/versions/${id}`)
    load()
  }

  const S = { card: { background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: 20, marginBottom: 16 } }

  return (
    <div style={{ padding: '24px 28px' }}>
      <h2 style={{ margin: '0 0 20px', fontSize: 20, fontWeight: 700 }}>📱 모바일 앱 직접 배포</h2>
      <p style={{ color: '#64748b', marginBottom: 20 }}>APK를 업로드하면 QR 코드가 생성됩니다. 사용자는 QR 스캔만으로 앱을 설치할 수 있습니다 (앱스토어 불필요).</p>

      {/* 현재 최신 버전 + QR */}
      {latest?.has_version && (
        <div style={{ ...S.card, display: 'flex', gap: 24, alignItems: 'flex-start', borderLeft: '4px solid #003366' }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, color: '#64748b', marginBottom: 4 }}>현재 최신 버전</div>
            <div style={{ fontSize: 28, fontWeight: 800, color: '#003366' }}>v{latest.version}</div>
            <div style={{ fontSize: 13, color: '#64748b', marginTop: 4 }}>{latest.platform} · 총 {latest.download_count}회 다운로드</div>
            {latest.release_notes && <div style={{ fontSize: 12, color: '#475569', marginTop: 8, lineHeight: 1.6 }}>{latest.release_notes}</div>}
            <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
              <a href={latest.qr_url} target="_blank" rel="noreferrer"
                style={{ padding: '7px 14px', background: '#003366', color: '#fff', borderRadius: 8, fontSize: 12, textDecoration: 'none' }}>
                🖼️ QR 이미지 열기
              </a>
              <a href={latest.landing_url} target="_blank" rel="noreferrer"
                style={{ padding: '7px 14px', border: '1px solid #e2e8f0', borderRadius: 8, fontSize: 12, textDecoration: 'none', color: '#1e293b' }}>
                📄 랜딩 페이지
              </a>
            </div>
          </div>
          {/* QR 이미지 */}
          <div style={{ textAlign: 'center' }}>
            <img src={latest.qr_url} alt="QR" width={120} height={120}
              style={{ border: '2px solid #e2e8f0', borderRadius: 8 }}
              onError={(e: any) => { e.target.style.display = 'none' }} />
            <div style={{ fontSize: 11, color: '#64748b', marginTop: 4 }}>스캔하여 설치</div>
          </div>
        </div>
      )}

      {/* 통계 */}
      {stats && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12, marginBottom: 16 }}>
          {[
            { label: '총 다운로드', val: stats.total_downloads, icon: '📥' },
            { label: 'Android', val: stats.android, icon: '🤖' },
            { label: 'iOS', val: stats.ios, icon: '🍎' },
          ].map(s => (
            <div key={s.label} style={{ ...S.card, textAlign: 'center', padding: 14 }}>
              <div style={{ fontSize: 22 }}>{s.icon}</div>
              <div style={{ fontSize: 24, fontWeight: 700, color: '#003366' }}>{s.val}</div>
              <div style={{ fontSize: 12, color: '#64748b' }}>{s.label}</div>
            </div>
          ))}
        </div>
      )}

      {/* 업로드 폼 */}
      <div style={S.card}>
        <h3 style={{ fontSize: 14, fontWeight: 600, margin: '0 0 16px' }}>새 버전 배포</h3>
        <div style={{ display: 'flex', gap: 4, marginBottom: 16, borderBottom: '1px solid #e2e8f0', paddingBottom: 0 }}>
          {[{id:'upload',label:'APK 파일 업로드'},{id:'url',label:'외부 URL 연결'}].map(t => (
            <button key={t.id} onClick={() => setTab(t.id as any)} style={{
              padding: '8px 16px', border: 'none', background: 'none', cursor: 'pointer',
              fontSize: 13, fontWeight: tab === t.id ? 700 : 400,
              color: tab === t.id ? '#003366' : '#64748b',
              borderBottom: tab === t.id ? '2px solid #003366' : '2px solid transparent',
            }}>{t.label}</button>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 }}>
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>버전 *</label>
            <input value={version} onChange={e => setVersion(e.target.value)} placeholder="예: 1.2.3"
              style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 13, boxSizing: 'border-box' }} />
          </div>
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>iOS URL (선택)</label>
            <input value={iosUrl} onChange={e => setIosUrl(e.target.value)} placeholder="TestFlight URL"
              style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 13, boxSizing: 'border-box' }} />
          </div>
        </div>

        {tab === 'upload' ? (
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>APK 파일 *</label>
            <input type="file" accept=".apk" ref={fileRef}
              style={{ width: '100%', padding: '8px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 13, boxSizing: 'border-box', marginBottom: 8 }} />
          </div>
        ) : (
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>Android 다운로드 URL *</label>
            <input value={externalUrl} onChange={e => setExternalUrl(e.target.value)} placeholder="https://expo.dev/... 또는 직접 APK URL"
              style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 13, boxSizing: 'border-box', marginBottom: 8 }} />
          </div>
        )}

        <div style={{ marginBottom: 12 }}>
          <label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>업데이트 내용</label>
          <textarea value={notes} onChange={e => setNotes(e.target.value)} rows={2} placeholder="이번 버전 변경사항..."
            style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 13, resize: 'vertical', boxSizing: 'border-box' }} />
        </div>

        <button
          onClick={tab === 'upload' ? uploadApk : setUrl}
          disabled={uploading}
          style={{ padding: '9px 20px', background: uploading ? '#94a3b8' : '#003366', color: '#fff', border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 600, cursor: uploading ? 'not-allowed' : 'pointer' }}>
          {uploading ? '업로드 중...' : '🚀 배포 + QR 생성'}
        </button>
      </div>

      {/* 버전 이력 */}
      <div style={S.card}>
        <h3 style={{ fontSize: 14, fontWeight: 600, margin: '0 0 12px' }}>버전 이력</h3>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ borderBottom: '1px solid #e2e8f0' }}>
              {['버전', '플랫폼', '크기', '다운로드', '상태', '배포일', ''].map(h => (
                <th key={h} style={{ textAlign: 'left', padding: '8px 12px', fontSize: 11, fontWeight: 600, color: '#64748b' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {versions.length === 0 ? (
              <tr><td colSpan={7} style={{ textAlign: 'center', padding: 24, color: '#94a3b8' }}>배포 이력 없음</td></tr>
            ) : versions.map(v => (
              <tr key={v.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
                <td style={{ padding: '10px 12px', fontWeight: v.is_latest ? 700 : 400 }}>
                  v{v.version} {v.is_latest && <span style={{ background: '#003366', color: '#fff', fontSize: 10, padding: '1px 6px', borderRadius: 8, marginLeft: 4 }}>최신</span>}
                </td>
                <td style={{ padding: '10px 12px' }}>{v.platform}</td>
                <td style={{ padding: '10px 12px', color: '#64748b' }}>{v.file_size_mb > 0 ? `${v.file_size_mb}MB` : '-'}</td>
                <td style={{ padding: '10px 12px' }}>{v.download_count}회</td>
                <td style={{ padding: '10px 12px' }}>
                  <a href={v.qr_url} target="_blank" rel="noreferrer" style={{ fontSize: 12, color: '#003366' }}>QR ↗</a>
                </td>
                <td style={{ padding: '10px 12px', color: '#64748b', fontSize: 11 }}>
                  {v.created_at ? new Date(v.created_at).toLocaleDateString('ko-KR') : '-'}
                </td>
                <td style={{ padding: '10px 12px' }}>
                  {!v.is_latest && (
                    <button onClick={() => deleteVersion(v.id)}
                      style={{ padding: '3px 8px', border: '1px solid #fca5a5', color: '#dc2626', borderRadius: 4, background: 'none', cursor: 'pointer', fontSize: 11 }}>
                      삭제
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
