import { useEffect, useState } from 'react'
import { Smartphone, Download, Copy, Check, ExternalLink, RefreshCw } from 'lucide-react'

// 중앙 APK 저장소(ITSM)의 공개 엔드포인트 — 인증 불필요·CORS 허용·읽기전용.
// 앱 업로드/버전 관리는 GUARDiA Manager에서 일원화. 외부 API는 ITSM 공개 도메인 1곳만 사용.
// :8443은 외부 비공개 → itsm 서브도메인(nginx 443) 사용. 응답 내 URL의 :8443도 동일 치환.
const ITSM_APP_BASE = 'https://itsm.zioinfo.co.kr'
const fixUrl = (u?: string) => u?.replace(/https?:\/\/zioinfo\.co\.kr:8443/g, ITSM_APP_BASE)

interface AppInfo {
  has_version: boolean
  app_name?: string
  version?: string
  platform?: string
  file_size_mb?: number
  release_notes?: string
  download_count?: number
  qr_url?: string
  landing_url?: string
  download_url?: string
  updated_at?: string
}

export default function MobileApp() {
  const [info, setInfo] = useState<AppInfo | null>(null)
  const [loading, setLoading] = useState(true)
  const [err, setErr] = useState('')
  const [copied, setCopied] = useState(false)

  const load = () => {
    setLoading(true); setErr('')
    fetch(`${ITSM_APP_BASE}/api/app/public-latest`)
      .then(r => r.json())
      .then((d: AppInfo) => setInfo({ ...d, qr_url: fixUrl(d.qr_url), landing_url: fixUrl(d.landing_url), download_url: fixUrl(d.download_url) }))
      .catch(() => setErr('버전 정보를 불러올 수 없습니다. (중앙 앱 저장소 연결 실패)'))
      .finally(() => setLoading(false))
  }
  useEffect(() => { load() }, [])

  const copyLink = async () => {
    if (!info?.landing_url) return
    try {
      await navigator.clipboard.writeText(info.landing_url)
      setCopied(true); setTimeout(() => setCopied(false), 2000)
    } catch { /* clipboard 권한 없을 때 무시 */ }
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2">
          <Smartphone className="text-brand" size={22} />
          <h1 className="text-xl font-semibold text-white">GUARDiA 통합 메신저 앱 설치</h1>
        </div>
        <button onClick={load} className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-card border border-edge text-sm text-gray-300 hover:text-brand">
          <RefreshCw size={15} /> 새로고침
        </button>
      </div>

      <p className="text-sm text-gray-400 mb-6">
        QR 코드를 스캔하면 <span className="text-brand font-semibold">GUARDiA Messenger</span> 앱 설치 페이지로 이동합니다.
        앱스토어 없이 바로 설치할 수 있으며, 앱 업로드·버전 관리는 GUARDiA Manager에서 일원화되어 있습니다.
      </p>

      {loading && <div className="text-gray-400 text-sm">불러오는 중…</div>}
      {err && <div className="bg-card border border-edge rounded-lg p-6 text-red-400 text-sm">{err}</div>}

      {!loading && !err && info && !info.has_version && (
        <div className="bg-card border border-edge rounded-lg p-8 text-center text-gray-400">
          <Smartphone size={36} className="mx-auto mb-3 text-gray-600" />
          아직 등록된 앱 버전이 없습니다.<br />
          <span className="text-xs">GUARDiA Manager에서 APK를 업로드하면 여기에 QR이 표시됩니다.</span>
        </div>
      )}

      {!loading && !err && info?.has_version && (
        <div className="bg-card border border-edge rounded-lg p-6 grid md:grid-cols-[200px_1fr] gap-6 items-start">
          <div className="bg-white rounded-xl p-3 flex items-center justify-center">
            {info.qr_url ? <img src={info.qr_url} alt="앱 설치 QR" className="w-44 h-44" /> : <Smartphone size={64} className="text-gray-400" />}
          </div>
          <div>
            <div className="flex items-center gap-2 mb-1">
              <span className="text-lg font-bold text-white">{info.app_name || 'GUARDiA Messenger'}</span>
              <span className="px-2 py-0.5 rounded-md bg-brand text-white text-xs font-semibold">v{info.version}</span>
            </div>
            <div className="text-xs text-gray-400 mb-4">
              {info.platform}{info.file_size_mb ? ` · ${info.file_size_mb}MB` : ''}
              {info.download_count != null && ` · 다운로드 ${info.download_count}회`}
            </div>

            {info.release_notes && (
              <div className="mb-4">
                <div className="text-[11px] font-semibold text-gray-500 uppercase tracking-wider mb-1">릴리즈 노트</div>
                <div className="text-sm text-gray-300 whitespace-pre-line bg-ink border border-edge rounded-lg p-3 max-h-32 overflow-auto">
                  {info.release_notes}
                </div>
              </div>
            )}

            <div className="flex flex-wrap gap-2">
              {info.landing_url && (
                <a href={info.landing_url} target="_blank" rel="noreferrer"
                   className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-brand text-white text-sm font-semibold">
                  <ExternalLink size={15} /> 설치 페이지 열기
                </a>
              )}
              {info.download_url && (
                <a href={info.download_url} target="_blank" rel="noreferrer"
                   className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-card border border-edge text-sm text-gray-300 hover:text-brand">
                  <Download size={15} /> APK 직접 다운로드
                </a>
              )}
              <button onClick={copyLink}
                 className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-card border border-edge text-sm text-gray-300 hover:text-brand">
                {copied ? <Check size={15} className="text-green-400" /> : <Copy size={15} />}
                {copied ? '복사됨' : '다운로드 링크 복사'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
