import React, { useState } from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import CircularProgress from '@mui/material/CircularProgress';
import ProjectSelectorBar from './ProjectSelectorBar';
import MetricCards from './MetricCards';
import QuickActionCards from './QuickActionCards';
import AdminSection from './AdminSection';
import useDashboardData from './useDashboardData';

export default function DashboardPage({
  user,
  projects,
  navigateToPage,
  loadProjects,
  inactiveProjects,
  setInactiveProjects,
  // legacy props (kept for App.jsx compat)
  showCreateProject,
  setShowCreateProject,
  ...rest
}) {
  const [selectedProject, setSelectedProject] = useState(null);
  const { loading, getMetrics } = useDashboardData(user, projects, selectedProject);

  const roleLabelMap = {
    admin: '시스템 관리자',
    manager: '프로젝트 매니저',
    designer: '설계 담당자',
    purchaser: '구매 담당자',
  };
  const roleLabel = roleLabelMap[user?.role] || '사용자';

  return (
    <Box sx={{ maxWidth: 1100, mx: 'auto', p: { xs: 2, sm: 4 } }}>
      {/* Header */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h4" sx={{ color: '#111827', mb: 0.5 }}>Dashboard</Typography>
        <Typography variant="body1" color="text.secondary">
          {user?.name || user?.username}님 환영합니다 — {roleLabel}
        </Typography>
      </Box>

      {/* Project selector */}
      <Box sx={{ mb: 3 }}>
        <ProjectSelectorBar
          projects={projects}
          selectedProject={selectedProject}
          onSelectProject={setSelectedProject}
          inactiveProjects={inactiveProjects}
        />
      </Box>

      {/* Metric cards */}
      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
          <CircularProgress size={28} />
        </Box>
      ) : (
        <Box sx={{ mb: 3 }}>
          <MetricCards metrics={getMetrics()} />
        </Box>
      )}

      {/* Quick action cards */}
      <Box sx={{ mb: 3 }}>
        <QuickActionCards selectedProject={selectedProject} navigateToPage={navigateToPage} />
      </Box>

      {/* Admin section */}
      <AdminSection user={user} navigateToPage={navigateToPage} />
    </Box>
  );
}
