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

// 중앙 APK 저장소(ITSM)의 공개 엔드포인트 — 인증 불필요·CORS 허용. 업로드는 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 CustomerApp() {
  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 app store. Please try again in a moment.'))
      .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 className="max-w-3xl mx-auto px-4 py-10">
      <div className="text-center mb-8">
        <div className="flex items-center gap-2 justify-center mb-2"><Smartphone className="text-bloom" size={26} /><h1 className="font-serif text-2xl font-bold text-bloom2">Order with the App</h1></div>
        <p className="text-sm text-gray-500">Scan the QR code to open the <span className="text-bloom font-semibold">GUARDiA Mall</span> customer app install page.<br />Enjoy same-day delivery alerts, easy reordering, and subscription management right in the app.</p>
      </div>

      {loading && <div className="text-center text-gray-400 py-10">Loading…</div>}
      {err && <div className="bg-petal border border-blush-100 rounded-2xl p-6 text-center text-blush-500 text-sm">{err}</div>}

      {!loading && !err && info && !info.has_version && (
        <div className="bg-white border border-blush-100/60 rounded-2xl p-10 text-center text-gray-400">
          <Flower2 size={40} className="mx-auto mb-3 text-bloom/30" />
          No app version has been published yet.<br />
          <span className="text-xs">App uploads and version management are handled in GUARDiA Manager.</span>
        </div>
      )}

      {!loading && !err && info?.has_version && (
        <div className="bg-white border border-blush-100/60 rounded-2xl p-6 grid md:grid-cols-[200px_1fr] gap-6 items-start shadow-sm">
          <div className="bg-petal rounded-2xl p-3 flex items-center justify-center">
            {info.qr_url ? <img src={info.qr_url} alt="App install QR code" className="w-44 h-44" /> : <Smartphone size={64} className="text-bloom/40" />}
          </div>
          <div>
            <div className="flex items-center gap-2 mb-1">
              <span className="text-lg font-bold">{info.app_name || 'GUARDiA Mall'}</span>
              <span className="px-2 py-0.5 rounded-md bg-bloom text-white text-xs font-semibold">v{info.version}</span>
            </div>
            <div className="text-xs text-gray-500 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-gray-400 uppercase tracking-wider mb-1">What's New</div>
                <div className="text-sm text-gray-600 whitespace-pre-line bg-petal 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-4 py-2 rounded-full bg-bloom text-white text-sm font-semibold hover:bg-bloom2"><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-4 py-2 rounded-full border border-blush-100 text-bloom2 text-sm hover:bg-petal"><Download size={15} /> Download APK</a>}
              <button onClick={copyLink} className="flex items-center gap-1.5 px-4 py-2 rounded-full border border-blush-100 text-bloom2 text-sm hover:bg-petal">
                {copied ? <Check size={15} className="text-leaf" /> : <Copy size={15} />}{copied ? 'Copied' : 'Copy Link'}
              </button>
              <button onClick={load} className="flex items-center gap-1.5 px-3 py-2 rounded-full border border-blush-100 text-gray-500 text-sm hover:bg-petal"><RefreshCw size={15} /></button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
