import React, { useState, useEffect, useRef } from 'react';
import { IonPage, IonContent, useIonViewWillEnter } from '@ionic/react';
import { useHistory } from 'react-router-dom';
import { supabase } from '../supabase';
// import { useAuth } from '../contexts/AuthContext';
import { Capacitor } from '@capacitor/core';
import { FirebaseAuthentication } from '@capacitor-firebase/authentication';
import AuthFormFields from '../components/AuthFormFields';
import SocialAuthButton from '../components/SocialAuthButton';
import '../styles/auth.css';

const AuthPage: React.FC = () => {
  const history = useHistory();
  // const location = useLocation();
  // const { user, profile, profileStatus } = useAuth();
  const signInTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  // const navigatedForUserRef = useRef<string | null>(null);

  const [tab, setTab] = useState<'login' | 'register'>('login');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // useEffect(() => {
  //   if (!user) {
  //     navigatedForUserRef.current = null;
  //     return;
  //   }

  //   if (signInTimeoutRef.current) {
  //     clearTimeout(signInTimeoutRef.current);
  //     signInTimeoutRef.current = null;
  //   }

  //   if (location.pathname !== '/auth' || profileStatus === 'loading') return;
  //   if (navigatedForUserRef.current === user.id) return;

  //   navigatedForUserRef.current = user.id;
  //   setLoading(false);

  //   if (
  //     !profile ||
  //     !profile.first_name ||
  //     !profile.last_name ||
  //     !profile.phone ||
  //     !profile.country_of_residence
  //   ) {
  //     history.replace('/setup-profile');
  //   } else {
  //     history.replace('/home');
  //   }
  // }, [user, profile, profileStatus, location.pathname, history]);

  useEffect(() => {
    return () => {
      if (signInTimeoutRef.current) {
        clearTimeout(signInTimeoutRef.current);
      }
    };
  }, []);

  useIonViewWillEnter(() => {
    setTab('login');
    setError(null);
  });

  const showError = (msg: string) => {
    setError(msg);
    setTimeout(() => setError(null), 4000);
  };

  const handleTabChange = (nextTab: 'login' | 'register') => {
    setTab(nextTab);
    setError(null);
    if (nextTab === 'login') {
      setConfirmPassword('');
    }
  };

  const handleSignUp = async (e: React.FormEvent) => {
    e.preventDefault();
    const normalizedEmail = email.trim().toLowerCase();

    if (!normalizedEmail) {
      showError('Please enter your email address.');
      return;
    }

    if (password !== confirmPassword) {
      showError('Passwords do not match');
      return;
    }
    setLoading(true);
    setError(null);

    const { error: signUpError } = await supabase.auth.signUp({
      email: normalizedEmail,
      password,
    });

    if (signUpError) {
      showError(signUpError.message);
      setLoading(false);
      return;
    }

    localStorage.setItem('kumusha_pending_verification_email', normalizedEmail);
    setLoading(false);
    history.replace('/verify-email', { state: { email: normalizedEmail } });
  };

  const handleSignIn = async (e: React.FormEvent) => {
    e.preventDefault();
    const normalizedEmail = email.trim().toLowerCase();

    if (signInTimeoutRef.current) {
      clearTimeout(signInTimeoutRef.current);
    }

    setLoading(true);
    setError(null);

    signInTimeoutRef.current = setTimeout(() => {
      setLoading(false);
      showError(
        'Sign in is taking too long. Please check your connection and try again.'
      );
    }, 12000);

    const { error: signInError } = await supabase.auth.signInWithPassword({
      email: normalizedEmail,
      password,
    });

    if (signInError) {
      if (signInTimeoutRef.current) {
        clearTimeout(signInTimeoutRef.current);
        signInTimeoutRef.current = null;
      }

      if (signInError.message.toLowerCase().includes('email not confirmed')) {
        await supabase.auth.resend({ type: 'signup', email: normalizedEmail });
        localStorage.setItem(
          'kumusha_pending_verification_email',
          normalizedEmail
        );
        history.push('/verify-email', {
          state: { email: normalizedEmail, resent: true },
        });
      } else {
        showError(signInError.message);
      }
      setLoading(false);
      return;
    }
    // Success: keep loading=true, wait for user/profile effect or timeout fallback
  };

  const handleGoogleSignIn = async () => {
    if (!Capacitor.isNativePlatform()) {
      showError(
        'Google Sign-In is only available in the native app. Use email to sign in here.'
      );
      return;
    }
    try {
      setLoading(true);
      const result = await FirebaseAuthentication.signInWithGoogle();
      if (!result.credential?.idToken) throw new Error('Missing ID token');

      const { error } = await supabase.auth.signInWithIdToken({
        provider: 'google',
        token: result.credential.idToken,
      });
      if (error) throw error;
      // keep loading true
    } catch (err: any) {
      showError(err.message || 'Google sign in failed');
      setLoading(false);
    }
  };

  const handleAppleSignIn = async () => {
    if (!Capacitor.isNativePlatform()) {
      showError(
        'Apple Sign-In is only available in the native app. Use email to sign in here.'
      );
      return;
    }
    try {
      setLoading(true);
      const result = await FirebaseAuthentication.signInWithApple({
        skipNativeAuth: true,
      });
      if (!result.credential?.idToken || !result.credential?.nonce)
        throw new Error('Missing token or nonce');

      const displayName = result.user?.displayName ?? null;

      const { data, error } = await supabase.auth.signInWithIdToken({
        provider: 'apple',
        token: result.credential.idToken,
        nonce: result.credential.nonce,
      });
      if (error) throw error;

      if (displayName && data.user) {
        const firstName = displayName.split(' ')[0] || 'Apple';
        const lastName = displayName.split(' ').slice(1).join(' ') || 'User';

        await supabase.from('profiles').upsert(
          {
            id: data.user.id,
            full_name: displayName,
            first_name: firstName,
            last_name: lastName,
            phone: 'Pending',
            country_of_residence: 'Pending',
          },
          { onConflict: 'id' }
        );
      }
    } catch (err: any) {
      showError(err.message || 'Apple sign in failed');
      setLoading(false);
    }
  };

  return (
    <IonPage>
      <IonContent
        className="auth-content"
        fullscreen
        style={{
          '--background':
            'linear-gradient(180deg, #fafafa 0%, #f6f1ff 52%, #f4f0ff 100%)',
          '--padding-start': '0px',
          '--padding-end': '0px',
          '--padding-top': '0px',
          '--padding-bottom': '0px',
        }}
      >
        <div className="auth-shell auth-shell--centered">
          <div className="auth-brand-block">
            <p className="auth-eyebrow">Kumusha</p>
            <h1 className="auth-heading">Take care of home from anywhere</h1>
            <p className="auth-subtitle">
              Support your family with trusted vouchers, airtime, medication,
              and electricity in just a few taps.
            </p>
          </div>

          <div className="auth-card auth-card--elevated">
            <div
              className="auth-mode-toggle"
              role="tablist"
              aria-label="Authentication mode"
            >
              <button
                type="button"
                className={`auth-toggle-pill ${tab === 'login' ? 'active' : 'inactive'}`}
                onClick={() => handleTabChange('login')}
                disabled={loading}
              >
                Sign In
              </button>
              <button
                type="button"
                className={`auth-toggle-pill ${tab === 'register' ? 'active' : 'inactive'}`}
                onClick={() => handleTabChange('register')}
                disabled={loading}
              >
                Sign Up
              </button>
            </div>

            <form
              className="auth-form-stack"
              onSubmit={tab === 'login' ? handleSignIn : handleSignUp}
            >
              <AuthFormFields
                mode={tab}
                email={email}
                password={password}
                confirmPassword={confirmPassword}
                onEmailChange={setEmail}
                onPasswordChange={setPassword}
                onConfirmPasswordChange={setConfirmPassword}
                disabled={loading}
              />

              {error ? (
                <div className="auth-inline-message">{error}</div>
              ) : null}

              {tab === 'login' && (
                <div className="auth-meta-row">
                  <span className="auth-meta-hint">Secure email sign in</span>
                  <button
                    type="button"
                    onClick={() => history.push('/forgot-password')}
                    className="auth-link-button"
                    disabled={loading}
                  >
                    Forgot password?
                  </button>
                </div>
              )}

              <button
                type="submit"
                className="auth-submit-btn"
                disabled={
                  loading ||
                  !email ||
                  !password ||
                  (tab === 'register' && !confirmPassword)
                }
              >
                {loading
                  ? 'Please wait...'
                  : tab === 'login'
                    ? 'Sign In'
                    : 'Create Account'}
              </button>
            </form>

            <div className="auth-divider">
              <span>Or continue with</span>
            </div>

            <div className="auth-social-buttons">
              <SocialAuthButton
                provider="google"
                label="Google"
                onClick={handleGoogleSignIn}
                disabled={loading}
              />
              <SocialAuthButton
                provider="apple"
                label="Apple"
                onClick={handleAppleSignIn}
                disabled={loading}
              />
            </div>
          </div>
        </div>
      </IonContent>
    </IonPage>
  );
};

export default AuthPage;
