import React, { useState } from 'react';

import {
  IonButton,
  IonContent,
  IonInput,
  IonItem,
  IonLabel,
  IonList,
  IonPage,
  useIonLoading,
  useIonRouter,
  useIonToast,
} from '@ionic/react';

import { supabase } from '../../supabaseClient';

function LoginPage() {
  const [email, setEmail] = useState('user1@example.com');
  const [password, setPassword] = useState('Aa1234567');

  const [showLoading, hideLoading] = useIonLoading();
  const [showToast] = useIonToast();

  const router = useIonRouter();

  const handleLogin = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    await showLoading();

    try {
      //   // OPT
      //   // await supabase.auth.signIn({ email });
      console.log({ email, password });
      const { error } = await supabase.auth.signInWithPassword({
        email,
        password,
      });

      if (error) {
        console.error(error);
        router.push('/login_error', 'forward', 'replace');
        // return redirect('/login?message=Could not authenticate user');
      }
      router.push('/tabs/events', 'forward', 'replace');
      // return redirect('/protected');
    } catch (e: any) {
      await showToast({
        message: e.error_description || e.message,
        duration: 5000,
      });
    } finally {
      await hideLoading();
    }
  };

  return (
    <IonPage>
      <IonContent>
        <IonList inset={true}>
          <form onSubmit={handleLogin}>
            <IonItem>
              <IonLabel position="stacked">{'Email'}</IonLabel>
              <IonInput
                type="email"
                value={email}
                name="email"
                onIonChange={e => setEmail(e.detail.value ?? '')}
              ></IonInput>
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{'Password'}</IonLabel>
              <IonInput
                type="password"
                value={password}
                name="password"
                onIonChange={e => setPassword(e.detail.value ?? '')}
              ></IonInput>
            </IonItem>
            <div className="ion-text-center">
              <IonButton type="submit" fill="clear">
                {'Login'}
              </IonButton>
            </div>
          </form>
        </IonList>
      </IonContent>
    </IonPage>
  );
}
export default React.memo(LoginPage);
