'use client';

import { useState, useEffect } from 'react';

import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import CircularProgress from '@mui/material/CircularProgress';

import { useAuthContext } from 'src/auth/hooks';

import { OverviewCourseView } from 'src/sections/overview/course/view';
import { OverviewClientView } from 'src/sections/overview/client/view';

// ----------------------------------------------------------------------

export default function DashboardPage() {
  const { user, loading } = useAuthContext();

  // Для родителя: выбранный ребёнок из localStorage
  const [selectedChild, setSelectedChild] = useState(null);

  useEffect(() => {
    if (user?.role === 'parent') {
      try {
        const saved = localStorage.getItem('selected_child');
        if (saved) setSelectedChild(JSON.parse(saved));
      } catch {
        // ignore
      }
    }
  }, [user]);

  if (loading) {
    return (
      <Box sx={{ display: 'flex', height: '80vh', alignItems: 'center', justifyContent: 'center' }}>
        <CircularProgress />
      </Box>
    );
  }

  if (!user) return null;

  if (user.role === 'mentor') {
    return <OverviewCourseView />;
  }

  if (user.role === 'client') {
    return <OverviewClientView />;
  }

  if (user.role === 'parent') {
    return (
      <OverviewClientView
        childId={selectedChild?.id || null}
        childName={selectedChild?.name || null}
      />
    );
  }

  return (
    <Box sx={{ p: 3, textAlign: 'center' }}>
      <Typography color="text.secondary">Неизвестная роль: {user.role}</Typography>
    </Box>
  );
}
