/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
*/

import React, { useState } from 'react';
import LoginScreen from './components/LoginScreen';
import AppLayout from './components/AppLayout';
import DoctorRegistration from './components/DoctorRegistration';
import { users as mockUsers } from './data/mockData';
import type { User } from './types';

// In a real app, this would be managed in a global state (Context, Redux, etc.)
let users = [...mockUsers];

const App: React.FC = () => {
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [isCompletingDoctorProfile, setIsCompletingDoctorProfile] = useState(false);

  const handleLoginSuccess = (user: User) => {
    setCurrentUser(user);
    if (user.role === 'doctor') {
      // This is a simplification. In a real app, you'd check if their profile is complete.
      // For the demo, we assume if they log in, their profile is complete.
      setIsCompletingDoctorProfile(false);
    }
  };

  const handleLogout = () => {
    setCurrentUser(null);
    setIsCompletingDoctorProfile(false);
  };

  const handleRegisterSuccess = (newUser: User) => {
    // In a real app, you would add the user to the database.
    // Here, we'll just log them in directly.
    users.push(newUser); // Simulate adding to DB
    setCurrentUser(newUser);
    if (newUser.role === 'doctor') {
      setIsCompletingDoctorProfile(true);
    }
  };

  const handleDoctorRegistrationComplete = () => {
    setIsCompletingDoctorProfile(false);
  };

  if (currentUser && currentUser.role === 'doctor' && isCompletingDoctorProfile) {
    return <DoctorRegistration user={currentUser} onRegistrationComplete={handleDoctorRegistrationComplete} />;
  }

  if (!currentUser) {
    return <LoginScreen onLoginSuccess={handleLoginSuccess} onRegisterSuccess={handleRegisterSuccess} />;
  }

  return <AppLayout currentUser={currentUser} onLogout={handleLogout} />;
};

export default App;