import { useEffect, useState } from 'react'
import { guardiaApi } from '../api/clients'

interface Condition { field: string; op: string; value: string }
interface Rule {
  id: number; name: string; enabled: boolean
  conditions: Condition[]; channels: string[]
  silence_start?: string; silence_end?: string
  digest_mode: boolean; priority_filter: string
  created_at: string
}

const FIELDS = ['sr_category','sr_priority','server_cpu','server_memory','server_disk','sr_status','tenant_id']
const OPS = ['==','!=','>','>=','<','<=','contains']
const CHANNELS = ['messenger','email','sms']
const PRIORITIES = ['','CRITICAL','HIGH','MEDIUM','LOW']

export default function NotificationRules() {
  const [rules, setRules] = useState<Rule[]>([])
  const [editing, setEditing] = useState<Partial<Rule> | null>(null)
  const [testResult, setTestResult] = useState<Record<number,string>>({})

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

  async function load() {
    const r: any = await guardiaApi.get('/api/notify/rules').catch(() => ({ data: [] }))
    setRules(r.data)
  }

  function newRule() {
    setEditing({
      name: '', enabled: true, conditions: [{ field: 'sr_priority', op: '==', value: 'CRITICAL' }],
      channels: ['messenger'], digest_mode: false, priority_filter: 'CRITICAL',
    })
  }

  async function save() {
    if (!editing) return
    if (!editing.name) return alert('규칙 이름을 입력하세요')
    if (editing.id) {
      await guardiaApi.put(`/api/notify/rules/${editing.id}`, editing)
    } else {
      await guardiaApi.post('/api/notify/rules', editing)
    }
    setEditing(null); load()
  }

  async function toggle(id: number, enabled: boolean) {
    await guardiaApi.patch(`/api/notify/rules/${id}/toggle`, { enabled: !enabled })
    load()
  }

  async function del(id: number) {
    if (!confirm('삭제하시겠습니까?')) return
    await guardiaApi.delete(`/api/notify/rules/${id}`)
    load()
  }

  async function test(id: number) {
    const r: any = await guardiaApi.post(`/api/notify/rules/${id}/test`).catch((e: any) => ({ data: { ok: false, message: e.message } }))
    setTestResult(prev => ({ ...prev, [id]: r.data.ok ? '✅ 테스트 발송 성공' : `❌ ${r.data.message}` }))
    setTimeout(() => setTestResult(prev => { const n = {...prev}; delete n[id]; return n }), 4000)
  }

  function addCond() {
    setEditing(e => e ? { ...e, conditions: [...(e.conditions||[]), { field: 'sr_priority', op: '==', value: '' }] } : e)
  }

  function removeCond(i: number) {
    setEditing(e => e ? { ...e, conditions: (e.conditions||[]).filter((_,idx) => idx !== i) } : e)
  }

  function updateCond(i: number, key: keyof Condition, val: string) {
    setEditing(e => e ? { ...e, conditions: (e.conditions||[]).map((c, idx) => idx === i ? { ...c, [key]: val } : c) } : e)
  }

  function toggleChannel(ch: string) {
    setEditing(e => {
      if (!e) return e
      const chs = e.channels || []
      return { ...e, channels: chs.includes(ch) ? chs.filter(c => c !== ch) : [...chs, ch] }
    })
  }

  const S = {
    card: { background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, padding: 16, marginBottom: 12 },
    tag: (active: boolean) => ({ padding: '4px 10px', borderRadius: 12, fontSize: 12, fontWeight: 600, cursor: 'pointer', border: 'none',
      background: active ? '#003366' : '#f1f5f9', color: active ? '#fff' : '#64748b' }),
  }

  return (
    <div style={{ padding: '24px 28px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>🔔 스마트 알림 규칙</h2>
        <button onClick={newRule}
          style={{ padding: '9px 18px', background: '#003366', color: '#fff', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
          + 규칙 추가
        </button>
      </div>
      <p style={{ color: '#64748b', marginBottom: 20, fontSize: 13 }}>조건 기반 스마트 알림 규칙을 설정합니다. AND 조건으로 모두 충족 시 알림이 발송됩니다.</p>

      {/* 규칙 목록 */}
      {rules.length === 0 && !editing && (
        <div style={{ textAlign: 'center', padding: 40, color: '#94a3b8', border: '2px dashed #e2e8f0', borderRadius: 10 }}>
          등록된 알림 규칙이 없습니다.<br />
          <button onClick={newRule} style={{ marginTop: 12, padding: '8px 16px', background: '#003366', color: '#fff', border: 'none', borderRadius: 8, cursor: 'pointer' }}>첫 규칙 만들기</button>
        </div>
      )}

      {rules.map(r => (
        <div key={r.id} style={{ ...S.card, opacity: r.enabled ? 1 : 0.6 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <span style={{ fontSize: 15, fontWeight: 700 }}>{r.name}</span>
                <span style={{ padding: '2px 8px', borderRadius: 8, fontSize: 11, fontWeight: 600,
                  background: r.enabled ? '#dcfce7' : '#f1f5f9', color: r.enabled ? '#166534' : '#64748b' }}>
                  {r.enabled ? '활성' : '비활성'}
                </span>
                {r.digest_mode && <span style={{ padding: '2px 8px', borderRadius: 8, fontSize: 11, background: '#fef3c7', color: '#92400e' }}>다이제스트</span>}
              </div>
              <div style={{ fontSize: 12, color: '#64748b', marginBottom: 6 }}>
                조건: {(r.conditions||[]).map(c => `${c.field} ${c.op} "${c.value}"`).join(' AND ') || '없음'}
              </div>
              <div style={{ display: 'flex', gap: 4 }}>
                {(r.channels||[]).map(ch => (
                  <span key={ch} style={{ padding: '2px 8px', background: '#eff6ff', color: '#1d4ed8', borderRadius: 8, fontSize: 11 }}>{ch}</span>
                ))}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6, marginLeft: 12 }}>
              {testResult[r.id] && <span style={{ fontSize: 12, alignSelf: 'center' }}>{testResult[r.id]}</span>}
              <button onClick={() => test(r.id)} style={{ padding: '5px 10px', border: '1px solid #e2e8f0', borderRadius: 6, background: 'none', cursor: 'pointer', fontSize: 12 }}>테스트</button>
              <button onClick={() => setEditing(r)} style={{ padding: '5px 10px', border: '1px solid #e2e8f0', borderRadius: 6, background: 'none', cursor: 'pointer', fontSize: 12 }}>편집</button>
              <button onClick={() => toggle(r.id, r.enabled)} style={{ padding: '5px 10px', border: '1px solid #e2e8f0', borderRadius: 6, background: 'none', cursor: 'pointer', fontSize: 12 }}>
                {r.enabled ? '비활성화' : '활성화'}
              </button>
              <button onClick={() => del(r.id)} style={{ padding: '5px 10px', border: '1px solid #fca5a5', color: '#dc2626', borderRadius: 6, background: 'none', cursor: 'pointer', fontSize: 12 }}>삭제</button>
            </div>
          </div>
        </div>
      ))}

      {/* 편집 폼 */}
      {editing && (
        <div style={{ ...S.card, border: '2px solid #003366', marginTop: 8 }}>
          <h3 style={{ fontSize: 15, fontWeight: 700, margin: '0 0 16px', color: '#003366' }}>
            {editing.id ? '규칙 편집' : '새 규칙 만들기'}
          </h3>

          <div style={{ marginBottom: 12 }}>
            <label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>규칙 이름</label>
            <input value={editing.name||''} onChange={e => setEditing(v => ({ ...v!, name: e.target.value }))}
              placeholder="예: CRITICAL SR 즉시 알림"
              style={{ width: '100%', padding: '8px 12px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 13, boxSizing: 'border-box' }} />
          </div>

          {/* 조건 */}
          <div style={{ marginBottom: 12 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <label style={{ fontSize: 12, fontWeight: 600 }}>조건 (AND)</label>
              <button onClick={addCond} style={{ fontSize: 11, color: '#003366', border: 'none', background: 'none', cursor: 'pointer' }}>+ 조건 추가</button>
            </div>
            {(editing.conditions||[]).map((c, i) => (
              <div key={i} style={{ display: 'flex', gap: 6, marginBottom: 6 }}>
                <select value={c.field} onChange={e => updateCond(i, 'field', e.target.value)}
                  style={{ flex: 2, padding: '6px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 12 }}>
                  {FIELDS.map(f => <option key={f} value={f}>{f}</option>)}
                </select>
                <select value={c.op} onChange={e => updateCond(i, 'op', e.target.value)}
                  style={{ flex: 1, padding: '6px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 12 }}>
                  {OPS.map(o => <option key={o} value={o}>{o}</option>)}
                </select>
                <input value={c.value} onChange={e => updateCond(i, 'value', e.target.value)} placeholder="값"
                  style={{ flex: 2, padding: '6px 10px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 12 }} />
                <button onClick={() => removeCond(i)} style={{ padding: '4px 8px', border: 'none', background: '#fef2f2', color: '#dc2626', borderRadius: 6, cursor: 'pointer', fontSize: 12 }}>×</button>
              </div>
            ))}
          </div>

          {/* 채널 */}
          <div style={{ marginBottom: 12 }}>
            <label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 6 }}>알림 채널</label>
            <div style={{ display: 'flex', gap: 6 }}>
              {CHANNELS.map(ch => (
                <button key={ch} onClick={() => toggleChannel(ch)}
                  style={S.tag((editing.channels||[]).includes(ch))}>
                  {ch === 'messenger' ? '📱 메신저' : ch === 'email' ? '📧 이메일' : '💬 SMS'}
                </button>
              ))}
            </div>
          </div>

          {/* 무음 시간 + 다이제스트 */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginBottom: 12 }}>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>무음 시작</label>
              <input type="time" value={editing.silence_start||''} onChange={e => setEditing(v => ({ ...v!, silence_start: e.target.value }))}
                style={{ width: '100%', padding: '7px 10px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 13, boxSizing: 'border-box' }} />
            </div>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>무음 종료</label>
              <input type="time" value={editing.silence_end||''} onChange={e => setEditing(v => ({ ...v!, silence_end: e.target.value }))}
                style={{ width: '100%', padding: '7px 10px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 13, boxSizing: 'border-box' }} />
            </div>
            <div>
              <label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>우선순위 필터</label>
              <select value={editing.priority_filter||''} onChange={e => setEditing(v => ({ ...v!, priority_filter: e.target.value }))}
                style={{ width: '100%', padding: '7px 10px', border: '1px solid #e2e8f0', borderRadius: 6, fontSize: 13, boxSizing: 'border-box' }}>
                {PRIORITIES.map(p => <option key={p} value={p}>{p || '전체'}</option>)}
              </select>
            </div>
          </div>

          <div style={{ marginBottom: 16 }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>
              <input type="checkbox" checked={editing.digest_mode||false}
                onChange={e => setEditing(v => ({ ...v!, digest_mode: e.target.checked }))} />
              <span style={{ fontSize: 13 }}>다이제스트 모드 (묶어서 발송)</span>
            </label>
          </div>

          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={save}
              style={{ padding: '9px 20px', background: '#003366', color: '#fff', border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>
              저장
            </button>
            <button onClick={() => setEditing(null)}
              style={{ padding: '9px 20px', border: '1px solid #e2e8f0', borderRadius: 8, fontSize: 14, cursor: 'pointer', background: 'none' }}>
              취소
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
