import React, { useState, useEffect } from 'react';
import {
  IonPage,
  IonContent,
  IonHeader,
  IonToolbar,
  IonButtons,
  IonTitle,
  IonButton,
  useIonViewWillEnter,
} from '@ionic/react';
import { useHistory, useLocation } from 'react-router-dom';
import { IonIcon } from '@ionic/react';
import { chevronBackOutline, mailOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import OtpInputSlots from '../components/OtpInputSlots';
import '../styles/auth.css';

interface LocationState {
  email?: string;
  resent?: boolean;
}

const VerifyEmailPage: React.FC = () => {
  const history = useHistory();
  const location = useLocation<LocationState>();
  const { user, profile, profileStatus } = useAuth();

  const email =
    location.state?.email?.trim().toLowerCase() ||
    localStorage.getItem('kumusha_pending_verification_email') ||
    '';
  const wasResent = location.state?.resent;

  const [code, setCode] = useState<string[]>(['', '', '', '', '', '']);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [status, setStatus] = useState<string | null>(
    wasResent ? 'We sent a fresh code to your email.' : null
  );
  const [cooldown, setCooldown] = useState(wasResent ? 60 : 0);

  useEffect(() => {
    if (!email) {
      showError(
        'We could not find the email used for sign up. Please sign up again.'
      );
    }
  }, [email]);

  useEffect(() => {
    if (!user || profileStatus === 'loading') return;

    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, history]);

  useIonViewWillEnter(() => {
    setError(null);
  });

  useEffect(() => {
    let timer: ReturnType<typeof setTimeout> | undefined;
    if (cooldown > 0) {
      timer = setTimeout(() => setCooldown((c) => c - 1), 1000);
    }
    return () => {
      if (timer) {
        clearTimeout(timer);
      }
    };
  }, [cooldown]);

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

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

  const handleDigitChange = (index: number, val: string) => {
    const newCode = [...code];
    newCode[index] = val;
    setCode(newCode);
  };

  const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
    e.preventDefault();
    const pastedData = e.clipboardData
      .getData('Text')
      .replace(/[^0-9]/g, '')
      .slice(0, 6);
    if (!pastedData) return;
    const newCode = [...code];
    for (let i = 0; i < pastedData.length; i++) {
      newCode[i] = pastedData[i];
    }
    setCode(newCode);
  };

  const handleVerifyOtp = async () => {
    const token = code.join('');
    if (token.length !== 6) {
      showError('Please enter the full 6-digit code.');
      return;
    }

    if (!email) {
      showError(
        'We could not find the email used for sign up. Please go back and create your account again.'
      );
      return;
    }

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

    const { error: verifyError } = await supabase.auth.verifyOtp({
      email,
      token,
      type: 'email',
    });

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

    localStorage.removeItem('kumusha_pending_verification_email');
    showStatus('Email verified. Finishing your sign in...');
    setLoading(false);
  };

  const handleResend = async () => {
    if (cooldown > 0) return;
    if (!email) {
      showError(
        'We could not find the email used for sign up. Please go back and create your account again.'
      );
      return;
    }
    setError(null);
    setStatus(null);

    const { error: resendError } = await supabase.auth.resend({
      type: 'signup',
      email,
    });

    if (resendError) {
      showError(resendError.message);
      return;
    }

    setCode(['', '', '', '', '', '']);
    setCooldown(60);
    showStatus('A new 6-digit code has been sent.');
  };

  return (
    <IonPage style={{ backgroundColor: '#fafafa' }}>
      <IonHeader className="ion-no-border">
        <IonToolbar style={{ '--background': 'transparent' }}>
          <IonButtons slot="start">
            <IonButton fill="clear" onClick={() => history.goBack()}>
              <IonIcon icon={chevronBackOutline} slot="icon-only" />
            </IonButton>
          </IonButtons>
          <IonTitle style={{ fontSize: '0px' }}>Verify email</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',
        }}
      >
        <div className="auth-shell">
          <div
            className="auth-brand-block"
            style={{ gap: '12px', marginTop: '20px' }}
          >
            <div
              style={{
                width: '56px',
                height: '56px',
                borderRadius: '24px',
                backgroundColor: 'rgba(109,40,217,0.12)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <IonIcon
                icon={mailOutline}
                style={{ fontSize: '26px', color: '#6d28d9' }}
              />
            </div>
            <h1 className="auth-heading" style={{ fontSize: '28px' }}>
              Check your email
            </h1>
            <p className="auth-subtitle" style={{ maxWidth: '340px' }}>
              {email ? (
                <>
                  We sent a 6-digit code to <strong>{email}</strong>. Enter it
                  below to confirm your account and continue.
                </>
              ) : (
                'We could not find the email used for sign up. Go back and create your account again.'
              )}
            </p>
          </div>

          <div className="auth-card auth-card--elevated">
            <div
              style={{ display: 'flex', flexDirection: 'column', gap: '18px' }}
            >
              <OtpInputSlots
                value={code}
                onChange={handleDigitChange}
                onPaste={handlePaste}
                disabled={loading}
              />

              {status ? (
                <div
                  style={{
                    borderRadius: '12px',
                    background: 'rgba(109,40,217,0.08)',
                    color: '#6d28d9',
                    padding: '12px 14px',
                    fontSize: '13px',
                    fontWeight: '600',
                    textAlign: 'center',
                  }}
                >
                  {status}
                </div>
              ) : null}

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

              <button
                className="auth-submit-btn"
                onClick={handleVerifyOtp}
                disabled={loading || code.join('').length !== 6}
              >
                {loading ? 'Verifying...' : 'Verify Code'}
              </button>

              <button
                type="button"
                onClick={handleResend}
                disabled={cooldown > 0 || loading}
                className="auth-link-button"
                style={{
                  alignSelf: 'center',
                  fontSize: '14px',
                  padding: '4px 0',
                  color: cooldown > 0 || loading ? '#9ca3af' : '#6d28d9',
                }}
              >
                {cooldown > 0 ? `Resend code in ${cooldown}s` : 'Resend code'}
              </button>
            </div>
          </div>
        </div>
      </IonContent>
    </IonPage>
  );
};

export default VerifyEmailPage;
