import React, { useState } from 'react'
import { BrowserRouter, Routes, Route, Navigate, NavLink } from 'react-router-dom'
import LoginPage from './pages/LoginPage'
import DashboardPage from './pages/DashboardPage'
import EmployeePage from './pages/EmployeePage'
import OrganizationPage from './pages/OrganizationPage'
import PayrollPage from './pages/PayrollPage'
import AttendancePage from './pages/AttendancePage'
import PerformancePage from './pages/PerformancePage'
import RecruitmentPage from './pages/RecruitmentPage'
import TrainingPage from './pages/TrainingPage'
import AiPage from './pages/AiPage'
import WiseAiPage from './pages/WiseAiPage'
import AiPlatformSettings from './pages/AiPlatformSettings'
import AdminPage from './pages/AdminPage'
import MyPage from './pages/MyPage'
import MobileApp from './pages/MobileApp'
// UIWS(UIMS) 이식 — 공통 업무협업 화면(업무일지·일정·쪽지·통계)
import WorklogList from './pages/uiws/WorklogList'
import ScheduleCalendar from './pages/uiws/ScheduleCalendar'
import MessageBox from './pages/uiws/MessageBox'
import StatsPivot from './pages/uiws/StatsPivot'
// UIWS system(권한관리) 이식 — 시스템관리(권한) 화면 셸(탭: 권한/역할-메뉴/공통코드/메뉴/부서/거래처)
import SystemPage from './pages/uiws/system/SystemPage'

// 시스템관리(권한)는 관리자 전용. 백엔드 /api/system/** 조회=SUPERADMIN/MANAGER, 쓰기=SUPERADMIN.
const ADMIN_ROLES = ['SUPERADMIN', 'MANAGER', 'ADMIN']

const MENU = [
  { path: '/dashboard', label: '대시보드', icon: '📊' },
  { path: '/employees', label: '사원관리', icon: '👥' },
  { path: '/organization', label: '조직도', icon: '🏢' },
  { path: '/payroll', label: '급여관리', icon: '💰' },
  { path: '/attendance', label: '근태관리', icon: '⏰' },
  { path: '/performance', label: '성과평가', icon: '🎯' },
  { path: '/recruitment', label: '채용관리', icon: '🔍' },
  { path: '/training', label: '교육관리', icon: '📚' },
  // UIWS 이식 — 업무 협업
  { path: '/worklogs', label: '업무일지', icon: '📝' },
  { path: '/schedules', label: '일정관리', icon: '📅' },
  { path: '/messages', label: '쪽지함', icon: '✉️' },
  { path: '/work-stats', label: '업무통계', icon: '📈' },
  { path: '/ai', label: 'AI 인사분석', icon: '🤖' },
  { path: '/wise-ai', label: 'WISE AI', icon: '✨' },
  { path: '/ai-platform', label: 'AI 플랫폼 설정', icon: '🧠', adminOnly: true },
  { path: '/admin', label: '시스템관리', icon: '⚙️' },
  // UIWS system 이식 — 권한·코드·메뉴·부서·거래처 (관리자 전용)
  { path: '/system', label: '시스템관리(권한)', icon: '🔐', adminOnly: true },
  { path: '/mobile-app', label: '모바일 앱', icon: '📱' },
]

function Layout({ children }: { children: React.ReactNode }) {
  const [collapsed, setCollapsed] = useState(false)
  const user = JSON.parse(localStorage.getItem('hrm_user') || '{"displayName":"관리자","role":"SUPERADMIN"}')
  const isAdmin = ADMIN_ROLES.includes(user.role)
  const visibleMenu = MENU.filter(m => !m.adminOnly || isAdmin)

  return (
    <div className="flex h-screen overflow-hidden">
      {/* 사이드바 */}
      <aside className={`${collapsed ? 'w-16' : 'w-60'} bg-slate-900 flex flex-col transition-all duration-200`}>
        <div className="h-16 flex items-center px-4 border-b border-slate-800">
          {!collapsed && (
            <div>
              <p className="text-white font-bold text-sm">GUARDiA HRM</p>
              <p className="text-slate-400 text-xs">AI 인사관리 플랫폼</p>
            </div>
          )}
          <button onClick={() => setCollapsed(!collapsed)} className="ml-auto text-slate-400 hover:text-white text-lg">
            {collapsed ? '→' : '←'}
          </button>
        </div>
        <nav className="flex-1 overflow-y-auto py-3 px-2 space-y-1">
          {visibleMenu.map(m => (
            <NavLink key={m.path} to={m.path}
              className={({ isActive }) => `sidebar-item ${isActive ? 'active' : ''}`}>
              <span className="text-base">{m.icon}</span>
              {!collapsed && <span>{m.label}</span>}
            </NavLink>
          ))}
        </nav>
        <div className="p-4 border-t border-slate-800">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center text-white text-xs font-bold">
              {user.displayName?.charAt(0) || 'A'}
            </div>
            {!collapsed && (
              <div className="flex-1 min-w-0">
                <p className="text-white text-sm font-medium truncate">{user.displayName}</p>
                <p className="text-slate-400 text-xs">{user.role}</p>
              </div>
            )}
          </div>
          {!collapsed && (
            <div className="mt-3 flex items-center justify-between">
              <NavLink to="/mypage" className="text-xs text-slate-400 hover:text-white">마이페이지</NavLink>
              <button className="text-xs text-slate-400 hover:text-white"
                onClick={() => { localStorage.clear(); window.location.href = '/login'; }}>
                로그아웃
              </button>
            </div>
          )}
        </div>
      </aside>
      {/* 메인 */}
      <main className="flex-1 overflow-auto bg-slate-50">
        <div className="p-6">{children}</div>
      </main>
    </div>
  )
}

function PrivateRoute({ children }: { children: React.ReactNode }) {
  const token = localStorage.getItem('hrm_token')
  if (!token) return <Navigate to="/login" replace />
  return <Layout>{children}</Layout>
}

// 관리자 전용 라우트 가드(UI 차단). 실제 인가는 백엔드 /api/system/** RBAC가 강제(403).
function AdminRoute({ children }: { children: React.ReactNode }) {
  const token = localStorage.getItem('hrm_token')
  if (!token) return <Navigate to="/login" replace />
  const user = JSON.parse(localStorage.getItem('hrm_user') || '{"role":"SUPERADMIN"}')
  if (!ADMIN_ROLES.includes(user.role)) return <Navigate to="/dashboard" replace />
  return <Layout>{children}</Layout>
}

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<LoginPage />} />
        <Route path="/" element={<Navigate to="/dashboard" replace />} />
        <Route path="/dashboard" element={<PrivateRoute><DashboardPage /></PrivateRoute>} />
        <Route path="/employees" element={<PrivateRoute><EmployeePage /></PrivateRoute>} />
        <Route path="/organization" element={<PrivateRoute><OrganizationPage /></PrivateRoute>} />
        <Route path="/payroll" element={<PrivateRoute><PayrollPage /></PrivateRoute>} />
        <Route path="/attendance" element={<PrivateRoute><AttendancePage /></PrivateRoute>} />
        <Route path="/performance" element={<PrivateRoute><PerformancePage /></PrivateRoute>} />
        <Route path="/recruitment" element={<PrivateRoute><RecruitmentPage /></PrivateRoute>} />
        <Route path="/training" element={<PrivateRoute><TrainingPage /></PrivateRoute>} />
        {/* UIWS(UIMS) 이식 — 업무 협업 화면 */}
        <Route path="/worklogs" element={<PrivateRoute><WorklogList /></PrivateRoute>} />
        <Route path="/schedules" element={<PrivateRoute><ScheduleCalendar /></PrivateRoute>} />
        <Route path="/messages" element={<PrivateRoute><MessageBox /></PrivateRoute>} />
        <Route path="/work-stats" element={<PrivateRoute><StatsPivot /></PrivateRoute>} />
        <Route path="/ai" element={<PrivateRoute><AiPage /></PrivateRoute>} />
        {/* WISE AI — 중앙 guardia-rag 근거·인용 질의응답(인증 사용자) */}
        <Route path="/wise-ai" element={<PrivateRoute><WiseAiPage /></PrivateRoute>} />
        {/* AI 플랫폼 설정(provider/모델·연결테스트·피드백 학습) — 관리자 전용. 백엔드 /api/hrm/admin/** RBAC 강제 */}
        <Route path="/ai-platform" element={<AdminRoute><AiPlatformSettings /></AdminRoute>} />
        <Route path="/admin" element={<PrivateRoute><AdminPage /></PrivateRoute>} />
        {/* 마이페이지 — OTP 2차 인증 등록/재설정/해제 + 비밀번호 변경 */}
        <Route path="/mypage" element={<PrivateRoute><MyPage /></PrivateRoute>} />
        {/* UIWS system 이식 — 시스템관리(권한). 관리자 전용(SUPERADMIN/MANAGER/ADMIN), 그 외 대시보드로 */}
        <Route path="/system" element={<AdminRoute><SystemPage /></AdminRoute>} />
        {/* 통합 메신저 앱 다운로드 QR (ITSM 중앙 APK 저장소 공개 엔드포인트 재사용·읽기전용) */}
        <Route path="/mobile-app" element={<PrivateRoute><MobileApp /></PrivateRoute>} />
        <Route path="*" element={<Navigate to="/dashboard" replace />} />
      </Routes>
    </BrowserRouter>
  )
}
