import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { IonContent, IonPage, IonSpinner } from '@ionic/react';
import { useAuth } from '../contexts/AuthContext';

interface Props {
  component: React.ComponentType<any>;
  path: string | string[];
  exact?: boolean;
}

const BYPASS_AUTH = true;

const ProtectedRouteLoader: React.FC = () => (
  <IonPage>
    <IonContent
      style={{
        '--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
      }}
    >
      <div
        style={{
          minHeight: '100%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          flexDirection: 'column',
          gap: '12px',
          color: '#6b7280',
          fontSize: '14px',
          fontWeight: 600,
        }}
      >
        <IonSpinner name="crescent" color="primary" />
        <span>Loading your profile...</span>
      </div>
    </IonContent>
  </IonPage>
);

const ProtectedRoute: React.FC<Props> = ({ component: Component, ...rest }) => {
  const { user, profileStatus } = useAuth();

  return (
    <Route
      {...rest}
      render={(props) => {
        if (BYPASS_AUTH) {
          return <Component {...props} />;
        }
        if (!user) {
          return <Redirect to="/auth" />;
        }
        if (profileStatus === 'loading') {
          return <ProtectedRouteLoader />;
        }
        if (profileStatus === 'missing') {
          return <Redirect to="/setup-profile" />;
        }
        return <Component {...props} />;
      }}
    />
  );
};

export default ProtectedRoute;
