import React, { useState } from 'react';
import {
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonPage,
  IonButtons,
  IonMenuButton,
  IonRow,
  IonCol,
  IonButton,
  IonList,
  IonItem,
  IonInput,
  IonText,
  IonIcon,
  useIonRouter,
  IonToast,
} from '@ionic/react';
import './Login.scss';
import {
  setIsLoggedIn,
  setUsername,
  setData,
  setPartyUserMeta,
} from '../../data/user/user.actions';
import { connect } from '../../data/connect';
import { RouteComponentProps } from 'react-router';
import { chevronBackOutline } from 'ionicons/icons';
import PATHS from '../../PATHS';
import axios from 'axios';
import * as selectors from '../../data/selectors';
import { UserState } from '../../data/user/user.state';
import constants from '../../constants';

interface OwnProps extends RouteComponentProps {}

interface StateProps {
  partyUserState: UserState;
}

interface DispatchProps {
  setIsLoggedIn: typeof setIsLoggedIn;
  setUsername: typeof setUsername;
  setData: typeof setData;
  setPartyUserMeta: typeof setPartyUserMeta;
}

interface LoginProps extends OwnProps, DispatchProps {}

const Login: React.FC<LoginProps> = ({
  setIsLoggedIn,
  history,
  setUsername: setUsernameAction,
  setData,
  setPartyUserMeta,
}) => {
  const [username, setUsername] = useState('demo@minimals.cc');
  const [email, setEmail] = useState('demo@minimals.cc');
  const [password, setPassword] = useState('@2Minimal');
  const [formSubmitted, setFormSubmitted] = useState(false);
  //
  const [usernameError, setUsernameError] = useState(false);
  const [passwordError, setPasswordError] = useState(false);
  const [emailError, setEmailError] = useState(false);

  const login = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormSubmitted(true);

    // if (!username) {
    //   setUsernameError(true);
    // }
    // if (!password) {
    //   setPasswordError(true);
    // }

    const emailAndPassword = { email, password };
    const result = await axios.post(constants.SIGN_IN, emailAndPassword);
    const { data, status } = result;
    const { accessToken, user } = data;

    if (status == 200) {
      // if username and password ok
      setData({ isLoggedin: true, accessToken });
      setPartyUserMeta(user);

      await setIsLoggedIn(true);
      await setUsernameAction(username);

      setShowLoginOkToast(true);

      router.push(PATHS.PROFILE);
    } else {
      // if username or password failed
      console.log({ result });
    }
  };

  const router = useIonRouter();
  function handleBackClick() {
    router.goBack();
  }

  const [showLoginOkToast, setShowLoginOkToast] = useState(false);

  return (
    <IonPage id="login-page">
      <IonHeader className="ion-no-border">
        <IonToolbar>
          <IonButtons slot="start">
            <IonButton onClick={handleBackClick}>
              <IonIcon icon={chevronBackOutline}></IonIcon>
            </IonButton>
          </IonButtons>
          <IonTitle>PartyUser Login Page</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent>
        <div className="login-logo">
          <img src="/assets/img/appicon.svg" alt="Ionic logo" />
        </div>

        <form noValidate onSubmit={login}>
          <IonList>
            <IonItem>
              <IonInput
                label="Email"
                labelPlacement="stacked"
                color="primary"
                name="email"
                type="text"
                value={email}
                spellCheck={false}
                autocapitalize="off"
                onIonInput={(e) => setEmail(e.detail.value as string)}
                required
              >
                {formSubmitted && emailError && (
                  <IonText color="danger" slot="error">
                    <p>Email is required</p>
                  </IonText>
                )}
              </IonInput>
            </IonItem>

            <IonItem>
              <IonInput
                label="Password"
                labelPlacement="stacked"
                color="primary"
                name="password"
                type="password"
                value={password}
                onIonInput={(e) => setPassword(e.detail.value as string)}
              >
                {formSubmitted && passwordError && (
                  <IonText color="danger" slot="error">
                    <p>Password is required</p>
                  </IonText>
                )}
              </IonInput>
            </IonItem>
          </IonList>

          <IonList>
            <IonItem>
              <div>email and password prefilled for demo</div>
            </IonItem>
          </IonList>

          <IonRow>
            <IonCol>
              <IonButton type="submit" expand="block">
                Login
              </IonButton>
            </IonCol>
            <IonCol>
              <IonButton routerLink={PATHS.PARTY_USER_SIGN_UP} color="light" expand="block">
                Signup
              </IonButton>
            </IonCol>
          </IonRow>
        </form>

        <IonToast
          isOpen={showLoginOkToast}
          message="login ok"
          duration={2000}
          onDidDismiss={() => setShowLoginOkToast(false)}
        />
      </IonContent>
    </IonPage>
  );
};

export default connect<OwnProps, StateProps, DispatchProps>({
  mapDispatchToProps: {
    setIsLoggedIn,
    setUsername,
    setData,
    setPartyUserMeta,
  },
  mapStateToProps: (state) => ({
    partyUserState: selectors.getPartyUserState(state),
  }),
  component: Login,
});
