import React, { useEffect, useState } from 'react';
import {
  IonButton,
  IonContent,
  IonHeader,
  IonItem,
  IonLabel,
  IonPage,
  IonTitle,
  IonToolbar,
} from '@ionic/react';
import { Redirect, useHistory } from 'react-router-dom';
import { supabase } from '../supabase';
import {
  Style,
  setStatusBarBackground,
  setStatusBarStyle,
} from '../utils/statusBar';
import { useIonViewWillEnter } from '@ionic/react';

const Account: React.FC = () => {
  const history = useHistory();
  const [sessionChecked, setSessionChecked] = useState(false);
  const [email, setEmail] = useState<string | null>(null);

  useIonViewWillEnter(() => {
    setStatusBarStyle(Style.Dark);
    setStatusBarBackground('#ffffff');
  });

  useEffect(() => {
    supabase.auth.getSession().then(({ data }) => {
      setEmail(data.session?.user.email ?? null);
      setSessionChecked(true);
    });
  }, []);

  const handleSignOut = async () => {
    await supabase.auth.signOut();
    history.replace('/auth');
  };

  if (sessionChecked && !email) {
    return <Redirect to="/auth" />;
  }

  return (
    <IonPage>
      <IonHeader className="ion-no-border">
        <IonToolbar>
          <IonTitle>Account</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent fullscreen>
        <div className="dashboard-shell ion-padding">
          <section className="hero-card compact">
            <span className="eyebrow">Signed in as</span>
            <h1>{email ?? 'Loading...'}</h1>
            <p>
              Your habits sync to your account so your streak history stays
              safe.
            </p>
          </section>

          <div className="stats-card">
            <IonItem lines="none">
              <IonLabel>
                <h2>Email</h2>
                <p>{email ?? '—'}</p>
              </IonLabel>
            </IonItem>
            <IonButton expand="block" routerLink="/home">
              Back to Habits
            </IonButton>
            <IonButton
              expand="block"
              fill="outline"
              color="danger"
              onClick={handleSignOut}
            >
              Sign Out
            </IonButton>
          </div>
        </div>
      </IonContent>
    </IonPage>
  );
};

export default Account;
