import React, { useState } from 'react';
import {
  IonButton,
  IonButtons,
  IonContent,
  IonHeader,
  IonIcon,
  IonInput,
  IonPage,
  IonTitle,
  IonToolbar,
} from '@ionic/react';
import { chevronBackOutline, keyOutline } from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import { supabase } from '../supabase';
import '../styles/auth.css';

const ForgotPasswordPage: React.FC = () => {
  const history = useHistory();
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [status, setStatus] = useState<string | null>(null);

  const showMessage = (message: string, kind: 'error' | 'status') => {
    if (kind === 'error') {
      setError(message);
      setStatus(null);
      setTimeout(() => setError(null), 4000);
    } else {
      setStatus(message);
      setError(null);
      setTimeout(() => setStatus(null), 4000);
    }
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();

    const normalizedEmail = email.trim().toLowerCase();
    if (!normalizedEmail) {
      showMessage('Enter your email address to continue', 'error');
      return;
    }

    setLoading(true);
    setError(null);
    setStatus(null);

    const { error: resetError } =
      await supabase.auth.resetPasswordForEmail(normalizedEmail);

    if (resetError) {
      showMessage(resetError.message, 'error');
      setLoading(false);
      return;
    }

    showMessage('Reset code sent', 'status');
    setLoading(false);
    history.push('/verify-reset', { state: { email: normalizedEmail } });
  };

  return (
    <IonPage style={{ backgroundColor: '#fafafa' }}>
      <IonHeader className="ion-no-border">
        <IonToolbar
          style={
            {
              '--background': 'transparent',
              '--border-width': '0px',
              '--color': '#111827',
            } as React.CSSProperties
          }
        >
          <IonButtons slot="start">
            <IonButton
              fill="clear"
              onClick={() => history.goBack()}
              style={
                {
                  '--color': '#111827',
                  '--border-radius': '12px',
                } as React.CSSProperties
              }
              aria-label="Go back"
            >
              <IonIcon icon={chevronBackOutline} slot="icon-only" />
            </IonButton>
          </IonButtons>
          <IonTitle style={{ fontSize: '18px', fontWeight: 700 }}>
            Reset password
          </IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent
        className="auth-content"
        style={
          {
            '--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
            '--padding-start': '0px',
            '--padding-end': '0px',
            '--padding-top': '0px',
            '--padding-bottom': '0px',
          } as React.CSSProperties
        }
      >
        <div className="auth-shell">
          <div
            className="auth-intro-block"
            style={{ alignItems: 'flex-start', textAlign: 'left' }}
          >
            <div className="auth-icon-container">
              <IonIcon icon={keyOutline} />
            </div>
            <div>
              <h1 className="auth-intro-heading">Forgot your password?</h1>
              <p className="auth-intro-body" style={{ marginTop: '8px' }}>
                Enter your account email and we'll send you a 6-digit reset
                code.
              </p>
            </div>
          </div>

          <form
            onSubmit={handleSubmit}
            className="auth-form-card"
            style={{ gap: '16px' }}
          >
            <IonInput
              type="email"
              label="Email address"
              labelPlacement="floating"
              value={email}
              onIonInput={(event) => setEmail(event.detail.value ?? '')}
              disabled={loading}
              placeholder="you@example.com"
              style={
                {
                  '--background': '#fafafa',
                  '--border-radius': '12px',
                  '--padding-start': '14px',
                  '--padding-end': '14px',
                  '--highlight-color-focused': '#6d28d9',
                } as React.CSSProperties
              }
            />

            {error && (
              <p className="auth-status-text" style={{ color: '#dc2626' }}>
                {error}
              </p>
            )}
            {status && (
              <p className="auth-status-text" style={{ color: '#16a34a' }}>
                {status}
              </p>
            )}

            <IonButton
              type="submit"
              expand="block"
              disabled={loading || !email.trim()}
              style={
                {
                  '--background': '#6d28d9',
                  '--background-activated': '#5b21b6',
                  '--border-radius': '999px',
                  '--box-shadow': 'none',
                  '--color': '#ffffff',
                  height: '52px',
                  fontSize: '15px',
                  fontWeight: 700,
                  marginTop: '4px',
                } as React.CSSProperties
              }
            >
              {loading ? 'Sending code...' : 'Send reset code'}
            </IonButton>
          </form>

          <div className="auth-footer">
            <p className="auth-footer-text">
              Remembered it?{' '}
              <button
                type="button"
                className="auth-footer-link"
                onClick={() => history.replace('/auth')}
                style={{
                  background: 'transparent',
                  border: 'none',
                  padding: 0,
                }}
                disabled={loading}
              >
                Back to sign in
              </button>
            </p>
          </div>
        </div>
      </IonContent>
    </IonPage>
  );
};

export default ForgotPasswordPage;
