'use client';

import type { BaseUser } from 'src/contexts/types/user';

import { useState, useEffect } from 'react';

import { paths } from 'src/routes/paths';

import { DashboardContent } from 'src/shared/layouts/dashboard';

import { CustomBreadcrumbs } from 'src/shared/components/custom-breadcrumbs';

import { apiService } from '../../api.service';
import { UserConsulterForm } from '../user-consulter-form';

type Props = {
  id: string;
  userType: string;
};

export function UserConsulterView({ id, userType }: Props) {
  const [currentUser, setCurrentUser] = useState<BaseUser | null>(null);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        let user: BaseUser | null = null;
        switch (userType) {
          case 'PARENT':
            user = await apiService.user.getParent(id);
            break;
          case 'ADMIN':
            user = await apiService.user.getAdmin(id);
            break;
          case 'CHILD':
            user = await apiService.user.getChild(id);
            break;
          default:
            console.error('Type utilisateur inconnu:', userType);
        }
        setCurrentUser(user);
      } catch (error) {
        console.error('Erreur lors de la récupération de l’utilisateur:', error);
      }
    };

    fetchUser();
  }, [id, userType]);

  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading="Visualiser utilisateur"
        links={[
          { name: 'Tableau de bord', href: paths.dashboard.root },
          { name: 'Utilisateurs', href: paths.dashboard.users.accounts },
          {
            name: currentUser ? `${currentUser.firstName} ${currentUser.lastName}` : 'Utilisateur',
          },
        ]}
        sx={{ mb: { xs: 3, md: 5 } }}
      />
      <UserConsulterForm currentUser={currentUser ?? undefined} />
    </DashboardContent>
  );
}
