import React, { useReducer } from 'react';

interface UserData {
  username: string;
  email: string;
  avatarUrl?: string;
  bio?: string;
}

// Define possible form states
enum SetupState {
  EMAIL_VERIFICATION = 'EMAIL_VERIFICATION',
  USERNAME_VALIDATION = 'USERNAME_VALIDATION',
  AVATAR_UPLOAD = 'AVATAR_UPLOAD',
  BIO_ENTRY = 'BIO_ENTRY',
  COMPLETE = 'COMPLETE',
}

// Define state shape
interface SetupFormState {
  currentState: SetupState;
  data: {
    email: string;
    username: string;
    avatarUrl?: string;
    bio?: string;
  };
}

// Define possible actions
type SetupAction =
  | { type: 'SET_EMAIL'; payload: string }
  | { type: 'EMAIL_VERIFIED' }
  | { type: 'SET_USERNAME'; payload: string }
  | { type: 'USERNAME_VERIFIED' }
  | { type: 'AVATAR_UPLOADED'; payload: string }
  | { type: 'SET_BIO'; payload: string }
  | { type: 'BIO_COMPLETED' };

// Initial state
const initialState: SetupFormState = {
  currentState: SetupState.EMAIL_VERIFICATION,
  data: {
    email: '',
    username: '',
  },
};

// Reducer function
function setupReducer(state: SetupFormState, action: SetupAction): SetupFormState {
  switch (action.type) {
    case 'SET_EMAIL':
      return {
        ...state,
        data: { ...state.data, email: action.payload },
      };
    case 'EMAIL_VERIFIED':
      return {
        ...state,
        currentState: SetupState.USERNAME_VALIDATION,
      };
    case 'SET_USERNAME':
      return {
        ...state,
        data: { ...state.data, username: action.payload },
      };
    case 'USERNAME_VERIFIED':
      return {
        ...state,
        currentState: SetupState.AVATAR_UPLOAD,
      };
    case 'AVATAR_UPLOADED':
      return {
        ...state,
        currentState: SetupState.BIO_ENTRY,
        data: { ...state.data, avatarUrl: action.payload },
      };
    case 'SET_BIO':
      return {
        ...state,
        data: { ...state.data, bio: action.payload },
      };
    case 'BIO_COMPLETED':
      return {
        ...state,
        currentState: SetupState.COMPLETE,
      };
    default:
      return state;
  }
}

export const ProfileSetup: React.FC = () => {
  const [state, dispatch] = useReducer(setupReducer, initialState);

  const handleEmailSubmit = async () => {
    const isValid = await validateEmail(state.data.email);
    if (isValid) {
      dispatch({ type: 'EMAIL_VERIFIED' });
    }
  };

  const handleUsernameSubmit = async () => {
    const isValid = await checkUsername(state.data.username);
    if (isValid) {
      dispatch({ type: 'USERNAME_VERIFIED' });
    }
  };

  const handleAvatarUpload = (url: string) => {
    dispatch({ type: 'AVATAR_UPLOADED', payload: url });
  };

  const handleBioSubmit = () => {
    dispatch({ type: 'BIO_COMPLETED' });
  };

  const handleSubmitAll = () => {
    if (state.currentState === SetupState.COMPLETE) {
      submitToServer(state.data);
    }
  };

  // Render current step based on state
  const renderCurrentStep = () => {
    switch (state.currentState) {
      case SetupState.EMAIL_VERIFICATION:
        return (
          <EmailForm
            email={state.data.email}
            onEmailChange={(email) => dispatch({ type: 'SET_EMAIL', payload: email })}
            onSubmit={handleEmailSubmit}
          />
        );
      case SetupState.USERNAME_VALIDATION:
        return (
          <UsernameForm
            username={state.data.username}
            onUsernameChange={(username) => 
              dispatch({ type: 'SET_USERNAME', payload: username })
            }
            onSubmit={handleUsernameSubmit}
          />
        );
      case SetupState.AVATAR_UPLOAD:
        return <AvatarUpload onUpload={handleAvatarUpload} />;
      case SetupState.BIO_ENTRY:
        return (
          <BioForm
            bio={state.data.bio || ''}
            onBioChange={(bio) => dispatch({ type: 'SET_BIO', payload: bio })}
            onSubmit={handleBioSubmit}
          />
        );
      case SetupState.COMPLETE:
        return <button onClick={handleSubmitAll}>Complete Setup</button>;
    }
  };

  return <div className="profile-setup">{renderCurrentStep()}</div>;
};

// Mock functions
const validateEmail = async (email: string): Promise<boolean> => true;
const checkUsername = async (username: string): Promise<boolean> => true;
const submitToServer = (userData: UserData): void => {};