import { useState, useEffect } from 'react'
import { guardiaApi } from '../api/clients'
import { DataTable } from '../components/common/DataTable'
import { Btn } from '../components/common/Btn'
import type { LicenseStatus, LicenseRecord, LicenseActivateResult } from '../api/types'

/* ── 에디션 정보 ── */
const EDITIONS = [
  {
    name: 'TRIAL',
    label: '무료 체험', color: '#94a3b8', bg: '#f8fafc',
    price: '7일 무료',
    features: ['기관 1개', '사용자 10명', '서버 20대', '기본 ITSM', '기술 지원 없음'],
  },
  {
    name: 'COMMUNITY',
    label: 'COMMUNITY', color: '#22c55e', bg: '#f0fdf4',
    price: '무료',
    features: ['기관 1개', '사용자 10명', '서버 50대', '전체 ITSM', '커뮤니티 지원'],
  },
  {
    name: 'STANDARD',
    label: 'STANDARD', color: '#4f6ef7', bg: '#eff2ff',
    price: '협의',
    features: ['기관 50개', '사용자 200명', '서버 500대', 'AI 에이전트', 'LDAP/MFA', 'SLA 관리', '이메일 지원'],
  },
  {
    name: 'ENTERPRISE',
    label: 'ENTERPRISE', color: '#f59e0b', bg: '#fffbeb',
    price: '협의',
    features: ['무제한 기관/사용자/서버', '취약점 스캔', 'FinOps', 'Scouter APM', '멀티테넌트', '전담 지원'],
  },
]

/* ── 에디션 배지 ── */
function EditionBadge({ edition }: { edition?: string }) {
  const e = EDITIONS.find(x => x.name === edition) ?? EDITIONS[0]
  return (
    <span style={{
      padding: '3px 12px', borderRadius: 20, fontSize: 12, fontWeight: 700,
      background: e.bg, color: e.color, border: `1px solid ${e.color}30`,
    }}>{e.label}</span>
  )
}

/* ── 만료일 진행 바 ── */
function ExpiryBar({ days, total = 365 }: { days: number; total?: number }) {
  const pct  = Math.max(0, Math.min(100, (days / total) * 100))
  const color = days <= 7 ? '#ef4444' : days <= 30 ? '#f59e0b' : '#22c55e'
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 5 }}>
        <span style={{ color: '#64748b' }}>남은 기간</span>
        <span style={{ fontWeight: 700, color }}>{days}일</span>
      </div>
      <div style={{ height: 8, background: '#f1f5f9', borderRadius: 4, overflow: 'hidden' }}>
        <div style={{ height: '100%', width: `${pct}%`, background: color,
          borderRadius: 4, transition: 'width .5s ease' }} />
      </div>
    </div>
  )
}

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

/* ── 메인 컴포넌트 ── */
export default function Licenses() {
  const [status, setStatus]       = useState<LicenseStatus | null>(null)
  const [history, setHistory]     = useState<LicenseRecord[]>([])
  const [loading, setLoading]     = useState(true)
  const [action, setAction]       = useState<'activate' | 'trial' | 'verify' | null>(null)
  const [keyInput, setKeyInput]   = useState('')
  const [customer, setCustomer]   = useState('GUARDiA 체험판')
  const [trialDays, setTrialDays] = useState(7)
  const [saving, setSaving]       = useState(false)
  const [verifyResult, setVerifyResult] = useState<{ valid: boolean; message: string; info?: Record<string, unknown> } | null>(null)
  const [toast, setToast]         = useState<{ msg: string; ok: boolean } | null>(null)
  const [newKey, setNewKey]       = useState<{ key: string; copied: boolean } | null>(null)

  const showToast = (msg: string, ok = true) => setToast({ msg, ok })

  const load = async () => {
    setLoading(true)
    try {
      const [st, hi] = await Promise.all([
        guardiaApi.get<LicenseStatus>('/api/license/status'),
        guardiaApi.get<LicenseRecord[]>('/api/license/history').catch(() => ({ data: [] })),
      ])
      setStatus(st.data)
      setHistory(Array.isArray(hi.data) ? hi.data : [])
    } catch {
      showToast('라이선스 정보를 불러올 수 없습니다.', false)
    } finally { setLoading(false) }
  }

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

  /* 라이선스 활성화 */
  const activate = async () => {
    if (!keyInput.trim()) return
    setSaving(true)
    try {
      const r = await guardiaApi.post<LicenseActivateResult>('/api/license/activate', { license_key: keyInput.trim() })
      showToast(r.data.message)
      setAction(null); setKeyInput(''); await load()
    } catch (e: unknown) {
      const msg = (e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? '활성화 실패'
      showToast(msg, false)
    } finally { setSaving(false) }
  }

  /* 체험판 발급 */
  const requestTrial = async () => {
    setSaving(true)
    try {
      const r = await guardiaApi.post<LicenseActivateResult>('/api/license/trial', { customer, days: trialDays })
      if (r.data.license_key) setNewKey({ key: r.data.license_key, copied: false })
      showToast(r.data.message)
      setAction(null); await load()
    } catch (e: unknown) {
      const msg = (e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? '체험 발급 실패'
      showToast(msg, false)
    } finally { setSaving(false) }
  }

  /* 키 검증 (등록 없음) */
  const verify = async () => {
    if (!keyInput.trim()) return
    setSaving(true)
    try {
      const r = await guardiaApi.post('/api/license/verify', { license_key: keyInput.trim() })
      setVerifyResult({ valid: true, message: r.data.message, info: r.data })
    } catch (e: unknown) {
      const msg = (e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? '검증 실패'
      setVerifyResult({ valid: false, message: msg })
    } finally { setSaving(false) }
  }

  /* 비활성화 */
  const deactivate = async () => {
    if (!confirm('라이선스를 비활성화하시겠습니까?\n서비스 이용이 제한될 수 있습니다.')) return
    try {
      const r = await guardiaApi.delete('/api/license')
      showToast(r.data.message)
      await load()
    } catch (e: unknown) {
      showToast((e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? '비활성화 실패', false)
    }
  }

  const currentEdition = EDITIONS.find(e => e.name === status?.edition)

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

      {/* 발급된 체험 키 1회 노출 */}
      {newKey && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)',
          zIndex: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
          <div style={{ background: '#fff', borderRadius: 12, padding: '32px 36px',
            maxWidth: 540, width: '100%', boxShadow: '0 20px 60px rgba(0,0,0,.3)' }}>
            <div style={{ textAlign: 'center', marginBottom: 20 }}>
              <div style={{ fontSize: 40 }}>🎁</div>
              <h3 style={{ color: '#1a3a6b', margin: '10px 0 4px' }}>체험 라이선스가 발급되었습니다</h3>
              <div style={{ fontSize: 12, color: '#94a3b8' }}>이 키는 지금만 확인 가능합니다.</div>
            </div>
            <div style={{ background: '#f8fafc', border: '1px solid #e2e8f0', borderRadius: 8,
              padding: '14px 16px', fontFamily: 'monospace', fontSize: 11,
              wordBreak: 'break-all', marginBottom: 16, color: '#1a3a6b' }}>{newKey.key}</div>
            <div style={{ display: 'flex', gap: 10 }}>
              <Btn variant="primary" style={{ flex: 1 }}
                onClick={() => { navigator.clipboard.writeText(newKey.key); setNewKey(k => k ? { ...k, copied: true } : null) }}>
                {newKey.copied ? '✅ 복사됨' : '📋 클립보드 복사'}
              </Btn>
              <Btn style={{ flex: 1 }} onClick={() => setNewKey(null)}>확인 완료</Btn>
            </div>
          </div>
        </div>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

        {/* ── 업그레이드 배너 ── */}
        {status?.upgrade_banner?.show && (
          <div style={{
            padding: '14px 20px', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 14,
            background: status.upgrade_banner.urgency === 'critical' ? '#fff1f2' : '#fffbeb',
            border: `1px solid ${status.upgrade_banner.urgency === 'critical' ? '#fecaca' : '#fde68a'}`,
          }}>
            <span style={{ fontSize: 24 }}>{status.upgrade_banner.urgency === 'critical' ? '🚨' : '⚠️'}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 14, color: status.upgrade_banner.urgency === 'critical' ? '#dc2626' : '#92400e' }}>
                {status.upgrade_banner.message}
              </div>
              <div style={{ fontSize: 12, color: '#64748b', marginTop: 2 }}>
                정식 라이선스를 활성화하면 이 경고가 사라집니다.
              </div>
            </div>
            <Btn variant="primary" size="sm" onClick={() => setAction('activate')}>라이선스 등록</Btn>
          </div>
        )}

        {/* ── 현재 라이선스 상태 카드 ── */}
        <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 12,
          overflow: 'hidden', boxShadow: '0 2px 8px rgba(0,0,0,.06)' }}>
          {/* 헤더 */}
          <div style={{
            background: status?.valid ? (currentEdition?.bg ?? '#f0fdf4') : '#f8fafc',
            padding: '20px 28px', borderBottom: '1px solid #e2e8f0',
            display: 'flex', alignItems: 'center', gap: 16,
          }}>
            <div style={{ fontSize: 40 }}>
              {status?.valid ? (status.is_trial ? '🎁' : '🏆') : (status?.expired ? '❌' : '🔓')}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                <EditionBadge edition={status?.edition} />
                {status?.is_trial && (
                  <span style={{ fontSize: 11, background: '#fef9c3', color: '#854d0e',
                    padding: '2px 8px', borderRadius: 10, fontWeight: 600 }}>체험판</span>
                )}
                {status?.expired && (
                  <span style={{ fontSize: 11, background: '#fee2e2', color: '#dc2626',
                    padding: '2px 8px', borderRadius: 10, fontWeight: 600 }}>만료됨</span>
                )}
              </div>
              <div style={{ fontWeight: 700, fontSize: 18, color: '#1e293b', marginBottom: 2 }}>
                {status?.customer || (loading ? '로딩 중...' : '라이선스 없음')}
              </div>
              <div style={{ fontSize: 12, color: '#64748b' }}>{status?.message}</div>
            </div>
            {/* 액션 버튼 */}
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
              <Btn variant="primary" size="sm" onClick={() => { setAction('activate'); setKeyInput(''); setVerifyResult(null) }}>
                🔑 라이선스 등록
              </Btn>
              {!status?.activated && (
                <Btn size="sm" onClick={() => { setAction('trial'); setVerifyResult(null) }}>
                  🎁 무료 체험
                </Btn>
              )}
              <Btn size="sm" onClick={() => { setAction('verify'); setKeyInput(''); setVerifyResult(null) }}>
                🔍 키 검증
              </Btn>
              {status?.activated && (
                <Btn variant="danger" size="sm" onClick={deactivate}>비활성화</Btn>
              )}
              <Btn size="sm" onClick={load}>↺</Btn>
            </div>
          </div>

          {/* 상세 정보 */}
          {status?.valid && (
            <div style={{ padding: '20px 28px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 20 }}>
              {/* 만료 진행 바 */}
              <div>
                <ExpiryBar days={status.days_remaining ?? 0}
                  total={status.is_trial ? (trialDays || 7) : 365} />
                <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 4 }}>
                  만료일: {status.expires_at?.slice(0, 10)}
                </div>
              </div>
              {/* 라이선스 ID */}
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, color: '#64748b', marginBottom: 4,
                  textTransform: 'uppercase', letterSpacing: '.04em' }}>라이선스 ID</div>
                <div style={{ fontFamily: 'monospace', fontSize: 12, color: '#1e293b',
                  wordBreak: 'break-all' }}>{status.license_id ?? '-'}</div>
              </div>
              {/* 제한 정보 */}
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, color: '#64748b', marginBottom: 6,
                  textTransform: 'uppercase', letterSpacing: '.04em' }}>허용 한도</div>
                {status.limits && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 3, fontSize: 12 }}>
                    {[
                      ['기관', status.limits.max_institutions ?? '무제한'],
                      ['사용자', status.limits.max_users ?? '무제한'],
                      ['서버', status.limits.max_servers ?? '무제한'],
                    ].map(([k, v]) => (
                      <div key={String(k)} style={{ display: 'flex', gap: 8 }}>
                        <span style={{ color: '#94a3b8', width: 48 }}>{k}</span>
                        <span style={{ fontWeight: 600 }}>{String(v)}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>

        {/* ── 액션 패널 ── */}
        {action && (
          <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10,
            padding: '20px 24px', animation: 'fadeIn .2s ease' }}>
            {/* 라이선스 등록 */}
            {action === 'activate' && (
              <>
                <h3 style={{ margin: '0 0 16px', fontSize: 14, fontWeight: 700, color: '#1a3a6b' }}>
                  🔑 라이선스 키 등록
                </h3>
                <div style={{ display: 'flex', gap: 10 }}>
                  <textarea value={keyInput} onChange={e => setKeyInput(e.target.value)}
                    placeholder="발급받은 라이선스 키를 입력하세요 (grd_lic_... 또는 grd_trial_...)"
                    style={{ flex: 1, padding: '10px 14px', border: '1px solid #e2e8f0',
                      borderRadius: 8, fontSize: 12, fontFamily: 'monospace', resize: 'vertical',
                      minHeight: 80, outline: 'none' }}
                    onFocus={e => { e.target.style.borderColor = '#4f6ef7' }}
                    onBlur={e => { e.target.style.borderColor = '#e2e8f0' }} />
                </div>
                <div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
                  <Btn variant="primary" loading={saving} onClick={activate} disabled={!keyInput.trim()}>
                    활성화
                  </Btn>
                  <Btn onClick={() => { setAction(null); setKeyInput('') }}>취소</Btn>
                </div>
              </>
            )}

            {/* 체험판 발급 */}
            {action === 'trial' && (
              <>
                <h3 style={{ margin: '0 0 4px', fontSize: 14, fontWeight: 700, color: '#1a3a6b' }}>
                  🎁 무료 체험 라이선스
                </h3>
                <div style={{ fontSize: 12, color: '#64748b', marginBottom: 16 }}>
                  설치당 1회만 발급 가능합니다. 발급 즉시 적용됩니다.
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, marginBottom: 12 }}>
                  <div>
                    <label style={{ fontSize: 11, fontWeight: 600, color: '#64748b', display: 'block', marginBottom: 5 }}>
                      고객/기관명
                    </label>
                    <input value={customer} onChange={e => setCustomer(e.target.value)}
                      style={{ width: '100%', padding: '9px 12px', border: '1px solid #e2e8f0',
                        borderRadius: 7, fontSize: 13, outline: 'none', boxSizing: 'border-box' }} />
                  </div>
                  <div>
                    <label style={{ fontSize: 11, fontWeight: 600, color: '#64748b', display: 'block', marginBottom: 5 }}>
                      기간 (일)
                    </label>
                    <select value={trialDays} onChange={e => setTrialDays(Number(e.target.value))}
                      style={{ padding: '9px 12px', border: '1px solid #e2e8f0', borderRadius: 7,
                        fontSize: 13, outline: 'none', background: '#fff' }}>
                      {[7, 14, 30].map(d => <option key={d} value={d}>{d}일</option>)}
                    </select>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 10 }}>
                  <Btn variant="primary" loading={saving} onClick={requestTrial} disabled={!customer.trim()}>
                    🎁 체험 시작
                  </Btn>
                  <Btn onClick={() => setAction(null)}>취소</Btn>
                </div>
              </>
            )}

            {/* 키 검증 */}
            {action === 'verify' && (
              <>
                <h3 style={{ margin: '0 0 16px', fontSize: 14, fontWeight: 700, color: '#1a3a6b' }}>
                  🔍 라이선스 키 검증
                </h3>
                <div style={{ display: 'flex', gap: 10, marginBottom: 12 }}>
                  <textarea value={keyInput} onChange={e => { setKeyInput(e.target.value); setVerifyResult(null) }}
                    placeholder="검증할 라이선스 키를 입력하세요"
                    style={{ flex: 1, padding: '10px 14px', border: '1px solid #e2e8f0',
                      borderRadius: 8, fontSize: 12, fontFamily: 'monospace', resize: 'vertical',
                      minHeight: 80, outline: 'none' }}
                    onFocus={e => { e.target.style.borderColor = '#4f6ef7' }}
                    onBlur={e => { e.target.style.borderColor = '#e2e8f0' }} />
                </div>
                {verifyResult && (
                  <div style={{ padding: '12px 16px', borderRadius: 8, marginBottom: 12, fontSize: 13,
                    background: verifyResult.valid ? '#f0fdf4' : '#fff1f2',
                    border: `1px solid ${verifyResult.valid ? '#bbf7d0' : '#fecaca'}`,
                    color: verifyResult.valid ? '#166534' : '#dc2626' }}>
                    {verifyResult.valid ? '✅' : '❌'} {verifyResult.message}
                    {verifyResult.valid && verifyResult.info && (
                      <div style={{ marginTop: 8, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6,
                        fontSize: 12, color: '#475569' }}>
                        {([['에디션', String(verifyResult.info['edition'] ?? '-')], ['고객', String(verifyResult.info['customer'] ?? '-')],
                          ['발급일', String(verifyResult.info['issued_at'] ?? '').slice(0,10)],
                          ['만료일', String(verifyResult.info['expires_at'] ?? '').slice(0,10)]] as [string,string][]).map(([k, v]) => (
                          <div key={k}><span style={{ color: '#94a3b8' }}>{k}: </span><strong>{v}</strong></div>
                        ))}
                      </div>
                    )}
                  </div>
                )}
                <div style={{ display: 'flex', gap: 10 }}>
                  <Btn variant="primary" loading={saving} onClick={verify} disabled={!keyInput.trim()}>검증</Btn>
                  {verifyResult?.valid && (
                    <Btn variant="outline" onClick={() => { setAction('activate') }}>
                      이 키로 활성화
                    </Btn>
                  )}
                  <Btn onClick={() => { setAction(null); setVerifyResult(null); setKeyInput('') }}>닫기</Btn>
                </div>
              </>
            )}
          </div>
        )}

        {/* ── 에디션 비교 테이블 ── */}
        <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: '20px 24px' }}>
          <h3 style={{ fontSize: 14, fontWeight: 700, margin: '0 0 16px', color: '#1e293b' }}>
            📊 에디션 비교
          </h3>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
            {EDITIONS.map(ed => (
              <div key={ed.name} style={{
                border: `2px solid ${status?.edition === ed.name ? ed.color : '#e2e8f0'}`,
                borderRadius: 10, padding: '16px 14px',
                background: status?.edition === ed.name ? ed.bg : '#fff',
                transition: 'all .2s',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
                  <span style={{ fontWeight: 700, fontSize: 13, color: ed.color }}>{ed.label}</span>
                  {status?.edition === ed.name && (
                    <span style={{ fontSize: 10, background: ed.color, color: '#fff',
                      padding: '1px 6px', borderRadius: 8 }}>현재</span>
                  )}
                </div>
                <div style={{ fontSize: 16, fontWeight: 800, color: '#1e293b', marginBottom: 10 }}>
                  {ed.price}
                </div>
                <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex',
                  flexDirection: 'column', gap: 4 }}>
                  {ed.features.map(f => (
                    <li key={f} style={{ fontSize: 11, color: '#475569', display: 'flex', gap: 5 }}>
                      <span style={{ color: ed.color }}>✓</span> {f}
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>

        {/* ── 라이선스 이력 ── */}
        <DataTable<LicenseRecord & { id: number }>
          cols={[
            { key: 'id',           header: 'ID',   width: 50 },
            { key: 'license_id',   header: '라이선스 ID', render: r =>
              <span style={{ fontFamily: 'monospace', fontSize: 11 }}>{r.license_id?.slice(0,20)}...</span> },
            { key: 'edition',      header: '에디션', render: r => <EditionBadge edition={r.edition} /> },
            { key: 'customer',     header: '고객명' },
            { key: 'is_trial',     header: '체험판', render: r =>
              r.is_trial ? <span style={{ color: '#f59e0b', fontSize: 12 }}>🎁 체험판</span>
                         : <span style={{ color: '#64748b', fontSize: 12 }}>정식</span> },
            { key: 'expires_at',   header: '만료일', render: r => r.expires_at?.slice(0,10) },
            { key: 'is_active',    header: '상태', render: r =>
              <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 10,
                background: r.is_active ? '#dcfce7' : '#f5f5f5',
                color: r.is_active ? '#16a34a' : '#9e9e9e' }}>
                {r.is_active ? '활성' : '비활성'}
              </span> },
            { key: 'activated_by', header: '등록자' },
            { key: 'activated_at', header: '등록일', render: r => r.activated_at?.slice(0,16) },
          ]}
          rows={(history as (LicenseRecord & { id: number })[])}
          loading={loading}
          empty="라이선스 이력이 없습니다."
          toolbar={<span style={{ fontSize: 12, color: '#64748b' }}>총 {history.length}건</span>}
        />
      </div>
    </>
  )
}
