import { useEffect, useState } from 'react'
import { roleMenuRoles, roleMenuMapping, saveRoleMenuMapping } from '../../../api/uiws'
import { PageHeader, Panel, Button, Spinner } from '../../../components/uiws/ui'

interface Role { roleId: string; roleNm: string; useYn: string }
interface RoleMenuRow { menuId: string; menuNm: string; readYn: string; writeYn: string }

function friendlyError(e: any): string {
  if (e?.response?.status === 403) return '권한이 없습니다 (SUPERADMIN 전용).'
  return e?.response?.data?.message || '요청을 처리하지 못했습니다.'
}

export default function RoleMenuPermission() {
  const [roles, setRoles] = useState<Role[]>([])
  const [activeRole, setActiveRole] = useState<string>('')
  const [rows, setRows] = useState<RoleMenuRow[]>([])
  const [loadingRoles, setLoadingRoles] = useState(false)
  const [loadingMap, setLoadingMap] = useState(false)
  const [saving, setSaving] = useState(false)
  const [msg, setMsg] = useState('')
  const [err, setErr] = useState('')

  useEffect(() => {
    setLoadingRoles(true)
    roleMenuRoles()
      .then(r => {
        // CMS 백엔드 role-menus 목록은 PageResponse → data.content
        const list: Role[] = r.data.data?.content ?? []
        setRoles(list)
        if (list.length > 0) setActiveRole(list[0].roleId)
      })
      .catch(e => setErr(friendlyError(e)))
      .finally(() => setLoadingRoles(false))
  }, [])

  useEffect(() => {
    if (!activeRole) return
    setLoadingMap(true); setMsg(''); setErr('')
    roleMenuMapping(activeRole)
      .then(r => setRows(r.data.data ?? []))
      .catch(e => setErr(friendlyError(e)))
      .finally(() => setLoadingMap(false))
  }, [activeRole])

  // 쓰기를 켜면 읽기도 자동 ON.
  const toggle = (menuId: string, field: 'readYn' | 'writeYn') =>
    setRows(prev => prev.map(r => {
      if (r.menuId !== menuId) return r
      const next = r[field] === 'Y' ? 'N' : 'Y'
      if (field === 'writeYn' && next === 'Y') return { ...r, writeYn: 'Y', readYn: 'Y' }
      if (field === 'readYn' && next === 'N') return { ...r, readYn: 'N', writeYn: 'N' }
      return { ...r, [field]: next }
    }))

  const checkAll = (field: 'readYn' | 'writeYn', on: boolean) =>
    setRows(prev => prev.map(r =>
      on && field === 'writeYn' ? { ...r, writeYn: 'Y', readYn: 'Y' }
        : !on && field === 'readYn' ? { ...r, readYn: 'N', writeYn: 'N' }
          : { ...r, [field]: on ? 'Y' : 'N' }))

  const save = async () => {
    setSaving(true); setMsg(''); setErr('')
    try {
      await saveRoleMenuMapping(activeRole, rows)
      setMsg('메뉴 권한 매핑이 저장되었습니다.')
    } catch (e) { setErr(friendlyError(e)) }
    finally { setSaving(false) }
  }

  return (
    <div className="uiws-scope">
      <PageHeader title="역할-메뉴 권한" subtitle="시스템관리(권한) · 역할별 메뉴 접근(읽기/쓰기) 매핑 — RBAC 핵심"
        actions={<Button onClick={save} disabled={saving || !activeRole}>{saving ? '저장 중...' : '매핑 저장'}</Button>} />

      {err && <div style={{ color: 'var(--uiws-danger)', fontSize: 13, marginBottom: 12 }}>{err}</div>}
      {msg && <div style={{ color: 'var(--uiws-success)', fontSize: 13, marginBottom: 12 }}>{msg}</div>}

      <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', gap: 16, alignItems: 'start' }}>
        <Panel style={{ padding: 0 }}>
          <div style={{ padding: '12px 16px', fontSize: 12, fontWeight: 600, color: 'var(--uiws-text-muted)', borderBottom: '1px solid var(--uiws-border)' }}>
            역할 목록
          </div>
          {loadingRoles ? <Spinner /> : (
            <div>
              {roles.length === 0 && <div style={{ padding: 20, fontSize: 13, color: 'var(--uiws-text-faint)' }}>역할이 없습니다.</div>}
              {roles.map(role => (
                <div key={role.roleId} onClick={() => setActiveRole(role.roleId)}
                  style={{
                    padding: '11px 16px', cursor: 'pointer', fontSize: 13,
                    borderLeft: `3px solid ${activeRole === role.roleId ? 'var(--uiws-primary)' : 'transparent'}`,
                    background: activeRole === role.roleId ? 'var(--uiws-primary-soft)' : 'transparent',
                    color: activeRole === role.roleId ? 'var(--uiws-primary)' : 'var(--uiws-text)',
                  }}>
                  <div style={{ fontWeight: 600 }}>{role.roleNm}</div>
                  <div style={{ fontSize: 11, color: 'var(--uiws-text-muted)' }}>{role.roleId}</div>
                </div>
              ))}
            </div>
          )}
        </Panel>

        <Panel style={{ padding: 0, overflow: 'hidden' }}>
          {loadingMap ? <Spinner /> : (
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, color: 'var(--uiws-text)' }}>
              <thead>
                <tr style={{ background: 'var(--uiws-surface-2)' }}>
                  <th style={{ textAlign: 'left', padding: '11px 14px', color: 'var(--uiws-text-muted)', fontWeight: 600, fontSize: 12, borderBottom: '1px solid var(--uiws-border)' }}>메뉴</th>
                  <th style={{ width: 120, padding: '8px 14px', color: 'var(--uiws-text-muted)', fontSize: 12, borderBottom: '1px solid var(--uiws-border)' }}>
                    읽기<br />
                    <label style={{ fontWeight: 400, fontSize: 11 }}>
                      <input type="checkbox" onChange={e => checkAll('readYn', e.target.checked)} /> 전체
                    </label>
                  </th>
                  <th style={{ width: 120, padding: '8px 14px', color: 'var(--uiws-text-muted)', fontSize: 12, borderBottom: '1px solid var(--uiws-border)' }}>
                    쓰기<br />
                    <label style={{ fontWeight: 400, fontSize: 11 }}>
                      <input type="checkbox" onChange={e => checkAll('writeYn', e.target.checked)} /> 전체
                    </label>
                  </th>
                </tr>
              </thead>
              <tbody>
                {rows.length === 0 ? (
                  <tr><td colSpan={3} style={{ padding: 28, textAlign: 'center', color: 'var(--uiws-text-faint)' }}>매핑 가능한 메뉴가 없습니다.</td></tr>
                ) : rows.map(r => (
                  <tr key={r.menuId} style={{ borderBottom: '1px solid var(--uiws-border)' }}>
                    <td style={{ padding: '11px 14px' }}>
                      {r.menuNm} <span style={{ color: 'var(--uiws-text-muted)', fontSize: 12 }}>({r.menuId})</span>
                    </td>
                    <td style={{ padding: '11px 14px', textAlign: 'center' }}>
                      <input type="checkbox" checked={r.readYn === 'Y'} onChange={() => toggle(r.menuId, 'readYn')} />
                    </td>
                    <td style={{ padding: '11px 14px', textAlign: 'center' }}>
                      <input type="checkbox" checked={r.writeYn === 'Y'} onChange={() => toggle(r.menuId, 'writeYn')} />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </Panel>
      </div>
    </div>
  )
}
