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

// 중앙 APK 저장소(ITSM)의 공개 엔드포인트 — 매장/대표 관리자앱(읽기전용). 업로드는 Manager 일원화.
// :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 AdminApp() {
  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('Unable to connect to the central app repository (ITSM).'))
      .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 { /* noop */ }
  }

  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-bold">Admin App Install</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-slate-300 hover:text-brand"><RefreshCw size={15} /> Refresh</button>
      </div>
      <p className="text-sm text-slate-400 mb-6">Mobile app for store and corporate admins. Scan the QR code to open the install page. App uploads and version management are centralized in <span className="text-brand">GUARDiA Manager</span> (read-only).</p>

      {loading && <div className="text-slate-400 text-sm">Loading…</div>}
      {err && <div className="bg-card border border-edge rounded-xl p-6 text-rose-400 text-sm">{err}</div>}

      {!loading && !err && info && !info.has_version && (
        <div className="bg-card border border-edge rounded-xl p-8 text-center text-slate-400">
          <Smartphone size={36} className="mx-auto mb-3 text-slate-600" />
          No app version has been registered yet.<br /><span className="text-xs">Once an APK is uploaded in GUARDiA Manager, the QR code will appear here.</span>
        </div>
      )}

      {!loading && !err && info?.has_version && (
        <div className="bg-card border border-edge rounded-xl 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="Admin App QR" className="w-44 h-44" /> : <Smartphone size={64} className="text-slate-400" />}
          </div>
          <div>
            <div className="flex items-center gap-2 mb-1"><span className="text-lg font-bold">{info.app_name || 'GUARDiA Mall Admin'}</span><span className="px-2 py-0.5 rounded-md bg-brand2 text-white text-xs font-semibold">v{info.version}</span></div>
            <div className="text-xs text-slate-400 mb-4">{info.platform} {info.file_size_mb ? `· ${info.file_size_mb}MB` : ''}{info.download_count != null && ` · ${info.download_count} downloads`}</div>
            {info.release_notes && (
              <div className="mb-4"><div className="text-[11px] font-semibold text-slate-500 uppercase tracking-wider mb-1">Release Notes</div><div className="text-sm text-slate-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-ink text-sm font-semibold"><ExternalLink size={15} /> Install Page</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-slate-300 hover:text-brand"><Download size={15} /> Download 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-slate-300 hover:text-brand">{copied ? <Check size={15} className="text-accent" /> : <Copy size={15} />}{copied ? 'Copied' : 'Copy Link'}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
