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

/**
 * 2.5 메뉴생성(role-menus) — /api/system/role-menus(권한목록), /roles/{id}/menus(읽기/쓰기 매핑 조회·저장).
 * 좌측 권한 선택 → 우측 메뉴별 읽기(readYn)/쓰기(writeYn) 토글 → 저장(PUT 전체 매핑).
 * RBAC 변경 ADMIN/MANAGER(403 + AdminGate). 색상 토큰만.
 */
type Role = { roleId: string; roleNm: string; roleDesc: string; useYn: string }
type RoleMenu = { menuId: string; menuNm: string; readYn: string; writeYn: string }

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

export default function RoleMenuManagement() {
  const [roles, setRoles] = useState<Role[]>([])
  const [active, setActive] = useState<string>('')
  const [menus, setMenus] = useState<RoleMenu[]>([])
  const [loadingRoles, setLoadingRoles] = useState(false)
  const [loadingMenus, setLoadingMenus] = useState(false)
  const [saving, setSaving] = useState(false)
  const [msg, setMsg] = useState('')

  async function loadRoles() {
    setLoadingRoles(true)
    try {
      const res = await roleMenuRoles({ page: 0, size: 100 })
      const list: Role[] = res.data?.data?.content || []
      setRoles(list)
      if (list.length && !active) selectRole(list[0].roleId)
    } catch { setRoles([]) } finally { setLoadingRoles(false) }
  }
  useEffect(() => { loadRoles() }, [])

  async function selectRole(roleId: string) {
    setActive(roleId); setMsg(''); setLoadingMenus(true)
    try {
      const res = await roleMenusGet(roleId)
      setMenus(res.data?.data || [])
    } catch { setMenus([]) } finally { setLoadingMenus(false) }
  }

  function toggle(menuId: string, field: 'readYn' | 'writeYn') {
    setMenus(prev => prev.map(m => {
      if (m.menuId !== menuId) return m
      const next = { ...m, [field]: m[field] === 'Y' ? 'N' : 'Y' }
      // 쓰기 권한이면 읽기는 자동 ON (정합성)
      if (field === 'writeYn' && next.writeYn === 'Y') next.readYn = 'Y'
      if (field === 'readYn' && next.readYn === 'N') next.writeYn = 'N'
      return next
    }))
  }

  async function save() {
    if (!active) return
    setSaving(true); setMsg('')
    try {
      await roleMenusSave(active, menus)
      setMsg('저장되었습니다.')
    } catch (e) { setMsg(friendlyError(e)) } finally { setSaving(false) }
  }

  return (
    <AdminGate>
      <div className="uiws-scope">
        <PageHeader title="메뉴 권한(권한별 메뉴 매핑)" subtitle="역할별 메뉴 읽기/쓰기 권한 부여"
          actions={<Button onClick={save} disabled={!active || saving}>{saving ? '저장 중...' : '저장'}</Button>} />

        <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr', gap: 16 }}>
          <Panel style={{ padding: 12 }}>
            <div style={{ fontSize: 12, color: 'var(--uiws-text-muted)', padding: '4px 6px 10px' }}>역할 선택</div>
            {loadingRoles ? <Spinner /> : roles.length === 0 ? (
              <div style={{ padding: 16, fontSize: 13, color: 'var(--uiws-text-faint)' }}>역할이 없습니다.</div>
            ) : roles.map(r => (
              <button key={r.roleId} onClick={() => selectRole(r.roleId)}
                style={{ display: 'block', width: '100%', textAlign: 'left', padding: '9px 10px', borderRadius: 8,
                  fontSize: 13, marginBottom: 2, border: 'none', cursor: 'pointer',
                  background: active === r.roleId ? 'var(--uiws-row-hover)' : 'transparent',
                  color: active === r.roleId ? 'var(--uiws-primary)' : 'var(--uiws-text)',
                  fontWeight: active === r.roleId ? 600 : 400 }}>
                {r.roleNm} <span style={{ color: 'var(--uiws-text-faint)', fontFamily: 'monospace', fontSize: 11 }}>({r.roleId})</span>
              </button>
            ))}
          </Panel>

          <Panel style={{ padding: 0, overflow: 'hidden' }}>
            {loadingMenus ? <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)', fontSize: 12, fontWeight: 600, borderBottom: '1px solid var(--uiws-border)' }}>메뉴</th>
                    <th style={{ textAlign: 'center', padding: '11px 14px', color: 'var(--uiws-text-muted)', fontSize: 12, fontWeight: 600, borderBottom: '1px solid var(--uiws-border)', width: 90 }}>읽기</th>
                    <th style={{ textAlign: 'center', padding: '11px 14px', color: 'var(--uiws-text-muted)', fontSize: 12, fontWeight: 600, borderBottom: '1px solid var(--uiws-border)', width: 90 }}>쓰기</th>
                  </tr>
                </thead>
                <tbody>
                  {menus.length === 0 ? (
                    <tr><td colSpan={3} style={{ padding: 28, textAlign: 'center', color: 'var(--uiws-text-faint)' }}>매핑할 메뉴가 없습니다.</td></tr>
                  ) : menus.map(m => (
                    <tr key={m.menuId} style={{ borderBottom: '1px solid var(--uiws-border)' }}>
                      <td style={{ padding: '10px 14px' }}>{m.menuNm} <span style={{ color: 'var(--uiws-text-faint)', fontFamily: 'monospace', fontSize: 11 }}>{m.menuId}</span></td>
                      <td style={{ textAlign: 'center' }}><input type="checkbox" checked={m.readYn === 'Y'} onChange={() => toggle(m.menuId, 'readYn')} /></td>
                      <td style={{ textAlign: 'center' }}><input type="checkbox" checked={m.writeYn === 'Y'} onChange={() => toggle(m.menuId, 'writeYn')} /></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </Panel>
        </div>
        {msg && <p style={{ marginTop: 12, fontSize: 13, color: 'var(--uiws-text-muted)' }}>{msg}</p>}
      </div>
    </AdminGate>
  )
}
