import { useState } from 'react'
import { useApi } from '../hooks/useApi'
import { guardiaApi } from '../api/clients'
import { DataTable } from '../components/common/DataTable'
import { StatusBadge } from '../components/common/StatusBadge'
import { SlidePanel } from '../components/common/SlidePanel'
import { Btn } from '../components/common/Btn'
import type { APIKey } from '../api/types'

const SCOPES = ['read', 'write', 'webhook', 'admin']

export default function ApiKeys() {
  const { data, loading, refetch } = useApi<APIKey[]>(guardiaApi, '/api/external/keys')
  const [creating, setCreating] = useState(false)
  const [newKey, setNewKey]     = useState<string | null>(null)
  const [copied, setCopied]     = useState(false)
  const [form, setForm]         = useState({ name: '', scopes: 'read', allowed_ips: '', expires_days: 365 })
  const [saving, setSaving]     = useState(false)

  const create = async () => {
    setSaving(true)
    try {
      const r = await guardiaApi.post('/api/external/keys', form)
      setNewKey(r.data.api_key)
      setCreating(false)
      setForm({ name: '', scopes: 'read', allowed_ips: '', expires_days: 365 })
      refetch()
    } catch (e: unknown) {
      alert((e as { response?: { data?: { detail?: string } } }).response?.data?.detail ?? '발급 실패')
    } finally { setSaving(false) }
  }

  const revoke = async (id: number, name: string) => {
    if (!confirm(`"${name}" API Key를 비활성화하시겠습니까?`)) return
    await guardiaApi.delete(`/api/external/keys/${id}`)
    refetch()
  }

  const copy = (text: string) => {
    navigator.clipboard.writeText(text)
    setCopied(true); setTimeout(() => setCopied(false), 2000)
  }

  return (
    <>
      {/* 1회 노출 모달 */}
      {newKey && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)',
          zIndex: 300, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ background: '#fff', borderRadius: 12, padding: '32px 36px',
            maxWidth: 520, width: '100%', margin: 16, boxShadow: '0 20px 60px rgba(0,0,0,.3)' }}>
            <div style={{ fontSize: 32, textAlign: 'center', marginBottom: 16 }}>🔑</div>
            <h3 style={{ textAlign: 'center', color: '#1a3a6b', marginBottom: 8 }}>API Key가 발급되었습니다</h3>
            <div style={{ background: '#fff8e1', border: '1px solid #f59e0b', borderRadius: 7,
              padding: '10px 14px', fontSize: 12, color: '#92400e', marginBottom: 16 }}>
              ⚠️ 이 키는 지금만 확인 가능합니다. 안전한 곳에 복사해 보관하세요.
            </div>
            <div style={{ background: '#f8fafc', border: '1px solid #e2e8f0', borderRadius: 8,
              padding: '14px 16px', fontFamily: 'monospace', fontSize: 13,
              wordBreak: 'break-all', marginBottom: 16 }}>{newKey}</div>
            <div style={{ display: 'flex', gap: 10 }}>
              <Btn variant="primary" style={{ flex: 1 }} onClick={() => copy(newKey)}>
                {copied ? '✅ 복사됨' : '📋 복사'}
              </Btn>
              <Btn style={{ flex: 1 }} onClick={() => setNewKey(null)}>확인 완료</Btn>
            </div>
          </div>
        </div>
      )}

      <DataTable<APIKey>
        cols={[
          { key: 'name',        header: '키 이름' },
          { key: 'scopes',      header: '권한', render: r => (
            <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
              {r.scopes.split(',').map(s => (
                <span key={s} style={{ fontSize: 10, background: '#e8ecff', color: '#4f6ef7',
                  padding: '1px 7px', borderRadius: 10 }}>{s}</span>
              ))}
            </div>
          )},
          { key: 'use_count',   header: '사용', width: 70 },
          { key: 'last_used_at', header: '마지막 사용', render: r =>
            r.last_used_at ? r.last_used_at.slice(0, 16) : '-' },
          { key: 'expires_at',  header: '만료일', render: r =>
            r.expires_at ? r.expires_at.slice(0, 10) : '무기한' },
          { key: 'is_active',   header: '상태', render: r =>
            <StatusBadge status={r.is_active ? 'active' : 'inactive'} /> },
          { key: 'id', header: '관리', render: r => r.is_active ? (
            <Btn variant="danger" size="sm" onClick={e => { e.stopPropagation(); revoke(r.id, r.name) }}>
              비활성화
            </Btn>
          ) : <span style={{ color: '#94a3b8', fontSize: 11 }}>비활성</span> },
        ]}
        rows={data ?? []}
        loading={loading}
        empty="발급된 API Key가 없습니다."
        toolbar={<Btn variant="primary" size="sm" onClick={() => setCreating(true)}>+ API Key 발급</Btn>}
      />

      <SlidePanel open={creating} onClose={() => setCreating(false)} title="API Key 발급"
        footer={
          <>
            <Btn onClick={() => setCreating(false)}>취소</Btn>
            <Btn variant="primary" loading={saving} onClick={create} disabled={!form.name}>발급</Btn>
          </>
        }>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {[
            { label: '키 이름 *', key: 'name', ph: '예: 카카오워크 봇' },
            { label: 'IP 허용 (빈칸=전체)', key: 'allowed_ips', ph: '예: 1.2.3.4 (쉼표 구분)' },
          ].map(f => (
            <div key={f.key}>
              <label style={{ fontSize: 11, fontWeight: 600, color: '#64748b', display: 'block', marginBottom: 5 }}>
                {f.label}
              </label>
              <input value={(form as Record<string, unknown>)[f.key] as string}
                onChange={e => setForm(p => ({ ...p, [f.key]: e.target.value }))}
                placeholder={f.ph}
                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>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {SCOPES.map(s => (
                <label key={s} style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 13, cursor: 'pointer' }}>
                  <input type="checkbox"
                    checked={form.scopes.split(',').includes(s)}
                    onChange={e => {
                      const cur = form.scopes.split(',').filter(Boolean)
                      const next = e.target.checked ? [...cur, s] : cur.filter(x => x !== s)
                      setForm(p => ({ ...p, scopes: next.join(',') || 'read' }))
                    }} />
                  {s}
                </label>
              ))}
            </div>
          </div>
          <div>
            <label style={{ fontSize: 11, fontWeight: 600, color: '#64748b', display: 'block', marginBottom: 5 }}>만료 기간 (일)</label>
            <input type="number" min={1} max={3650} value={form.expires_days}
              onChange={e => setForm(p => ({ ...p, expires_days: parseInt(e.target.value) }))}
              style={{ width: '100%', padding: '9px 12px', border: '1px solid #e2e8f0',
                borderRadius: 7, fontSize: 13, outline: 'none', boxSizing: 'border-box' }} />
          </div>
        </div>
      </SlidePanel>
    </>
  )
}
