import { useEffect, useState } from 'react'
import { roleMenuRoleList, roleMenus, saveRoleMenus } from '../../../api/uiws'
import { PageHeader, Panel, Button, Spinner } from '../../../components/uiws/ui'

/*
 * 역할-메뉴 권한(role-menus) — HRM 백엔드(com.zioinfo.hrm.uiws.system RoleMenuController) 계약 정합.
 * 좌측: 권한목록(/api/system/role-menus, PageResponse<RoleDto>).
 * 우측: 권한별 메뉴매핑(/api/system/roles/{roleId}/menus, RoleMenuDto[] = {menuId,menuNm,readYn,writeYn}).
 * 저장: PUT 동일 경로 {menus:[...]}.  (PMS엔 이 엔드포인트가 없어 HRM 신규 화면)
 */

interface Role { roleId: string; roleNm: string; roleDesc: string; useYn: string }
interface 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 [activeRole, setActiveRole] = useState<string>('')
  const [menus, setMenus] = useState<RoleMenu[]>([])
  const [loadingRoles, setLoadingRoles] = useState(false)
  const [loadingMenus, setLoadingMenus] = useState(false)
  const [saving, setSaving] = useState(false)
  const [err, setErr] = useState('')
  const [msg, setMsg] = useState('')

  const loadRoles = async () => {
    setLoadingRoles(true); setErr('')
    try {
      const res = await roleMenuRoleList()
      const list: Role[] = res.data.data?.content ?? []
      setRoles(list)
      if (!activeRole && list.length > 0) setActiveRole(list[0].roleId)
    } catch (e) { setErr(friendlyError(e)) }
    finally { setLoadingRoles(false) }
  }
  useEffect(() => { loadRoles() }, [])

  const loadMenus = async (roleId = activeRole) => {
    if (!roleId) { setMenus([]); return }
    setLoadingMenus(true); setErr(''); setMsg('')
    try {
      const res = await roleMenus(roleId)
      setMenus(res.data.data ?? [])
    } catch (e) { setErr(friendlyError(e)) }
    finally { setLoadingMenus(false) }
  }
  useEffect(() => { loadMenus() }, [activeRole])

  const 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' }
      // 쓰기 권한을 켜면 읽기 권한도 함께 보장(일반적 RBAC 규칙).
      if (field === 'writeYn' && next.writeYn === 'Y') next.readYn = 'Y'
      if (field === 'readYn' && next.readYn === 'N') next.writeYn = 'N'
      return next
    }))
  }

  const save = async () => {
    if (!activeRole) return
    setSaving(true); setErr(''); setMsg('')
    try {
      await saveRoleMenus(activeRole, menus)
      setMsg('저장되었습니다.')
    } catch (e) { setErr(friendlyError(e)) }
    finally { setSaving(false) }
  }

  return (
    <div className="uiws-scope">
      <PageHeader title="역할-메뉴 권한" subtitle="시스템관리(권한) · 권한별 메뉴 읽기/쓰기 매핑"
        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: '300px 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(r => (
                <div key={r.roleId} onClick={() => setActiveRole(r.roleId)}
                  style={{
                    padding: '11px 16px', cursor: 'pointer', fontSize: 13,
                    borderLeft: `3px solid ${activeRole === r.roleId ? 'var(--uiws-primary)' : 'transparent'}`,
                    background: activeRole === r.roleId ? 'var(--uiws-primary-soft)' : 'transparent',
                  }}>
                  <div style={{ fontWeight: 600, color: activeRole === r.roleId ? 'var(--uiws-primary)' : 'var(--uiws-text)' }}>{r.roleNm}</div>
                  <div style={{ fontSize: 11, color: 'var(--uiws-text-muted)' }}>{r.roleId}</div>
                </div>
              ))}
            </div>
          )}
        </Panel>

        <Panel style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '12px 16px', fontSize: 14, fontWeight: 600, color: 'var(--uiws-text)', borderBottom: '1px solid var(--uiws-border)' }}>
            메뉴 권한 {activeRole && <span style={{ color: 'var(--uiws-text-muted)', fontWeight: 400, fontSize: 13 }}>({activeRole})</span>}
          </div>
          {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)', fontWeight: 600, fontSize: 12, borderBottom: '1px solid var(--uiws-border)' }}>메뉴</th>
                  <th style={{ textAlign: 'center', padding: '11px 14px', width: 90, color: 'var(--uiws-text-muted)', fontWeight: 600, fontSize: 12, borderBottom: '1px solid var(--uiws-border)' }}>읽기</th>
                  <th style={{ textAlign: 'center', padding: '11px 14px', width: 90, color: 'var(--uiws-text-muted)', fontWeight: 600, fontSize: 12, borderBottom: '1px solid var(--uiws-border)' }}>쓰기</th>
                </tr>
              </thead>
              <tbody>
                {menus.length === 0 ? (
                  <tr><td colSpan={3} style={{ padding: 28, textAlign: 'center', color: 'var(--uiws-text-faint)' }}>
                    {activeRole ? '매핑 가능한 메뉴가 없습니다.' : '권한을 선택하세요.'}
                  </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-muted)', fontSize: 12 }}>({m.menuId})</span>
                    </td>
                    <td style={{ padding: '10px 14px', textAlign: 'center' }}>
                      <input type="checkbox" checked={m.readYn === 'Y'} onChange={() => toggle(m.menuId, 'readYn')} />
                    </td>
                    <td style={{ padding: '10px 14px', textAlign: 'center' }}>
                      <input type="checkbox" checked={m.writeYn === 'Y'} onChange={() => toggle(m.menuId, 'writeYn')} />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </Panel>
      </div>
    </div>
  )
}
