import { useState, useEffect, useRef } from 'react';
import { supabase } from './supabaseClient';

type Mode = 'signin' | 'signup' | 'forgot';
type Step = 'credentials' | 'otp';
type ListSize = 'Under 500' | '500-2000' | '2000+';

interface Props {
  onOtpVerified: () => void;
}

const Login = ({ onOtpVerified }: Props) => {
  const [mode, setMode]         = useState<Mode>('signin');
  const [step, setStep]         = useState<Step>('credentials');
  const [email, setEmail]       = useState('');
  const [password, setPassword] = useState('');
  const [otpCode, setOtpCode]   = useState('');
  const [loading, setLoading]   = useState(false);
  const [error, setError]       = useState('');
  const [message, setMessage]   = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const countdownRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const otpInputRef  = useRef<HTMLInputElement>(null);

  // Vetting form fields
  const [websiteUrl, setWebsiteUrl]   = useState('');
  const [useCase, setUseCase]         = useState('');
  const [listMethod, setListMethod]   = useState('');
  const [listSize, setListSize]       = useState<ListSize>('Under 500');

  useEffect(() => {
    return () => { if (countdownRef.current) clearInterval(countdownRef.current); };
  }, []);

  useEffect(() => {
    if (step === 'otp') setTimeout(() => otpInputRef.current?.focus(), 100);
  }, [step]);

  const startCountdown = () => {
    setCountdown(60);
    if (countdownRef.current) clearInterval(countdownRef.current);
    countdownRef.current = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) { clearInterval(countdownRef.current!); return 0; }
        return prev - 1;
      });
    }, 1000);
  };

  const sendOtp = async (emailAddr: string) => {
    const res  = await fetch('/api/auth/send-otp', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: emailAddr }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || 'Failed to send verification code.');
    startCountdown();
  };

  const handleCredentials = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setMessage('');
    try {
      if (mode === 'signin') {
        const { error: authErr } = await supabase.auth.signInWithPassword({ email, password });
        if (authErr) throw authErr;
        await sendOtp(email);
        setStep('otp');
        setOtpCode('');
      } else if (mode === 'signup') {
        // Vetting pipeline — no account created yet, manual review by owner
        const res  = await fetch('/api/auth/request-access', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            business_email:       email,
            website_url:          websiteUrl,
            use_case:             useCase,
            list_building_method: listMethod,
            estimated_list_size:  listSize,
          }),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Submission failed. Please try again.');
        setMessage('Thank you! Your trial request has been submitted. To protect our email delivery network, our team manually reviews all businesses. If approved, an account setup link will be sent to you within 24 hours.');
        setMode('signin');
        setPassword('');
        setWebsiteUrl('');
        setUseCase('');
        setListMethod('');
        setListSize('Under 500');
      } else {
        const { error: authErr } = await supabase.auth.resetPasswordForEmail(email, {
          redirectTo: window.location.origin,
        });
        if (authErr) throw authErr;
        setMessage('Password reset link sent. Check your inbox.');
        setMode('signin');
        setEmail('');
      }
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleOtp = async (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = otpCode.trim();
    if (trimmed.length !== 6) { setError('Enter the 6-digit code from your email.'); return; }
    setLoading(true);
    setError('');
    try {
      const res  = await fetch('/api/auth/verify-otp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, code: trimmed, userAgent: navigator.userAgent }),
      });
      const data = await res.json();
      if (data.success) {
        onOtpVerified();
      } else {
        setError(data.error || 'Invalid or expired code.');
        setOtpCode('');
        otpInputRef.current?.focus();
      }
    } catch {
      setError('Network error. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleResend = async () => {
    if (countdown > 0) return;
    setError('');
    try {
      await sendOtp(email);
      setMessage('A new code was sent to your email.');
    } catch (err: any) {
      setError(err.message);
    }
  };

  const handleBackToSignIn = async () => {
    await supabase.auth.signOut();
    setStep('credentials');
    setOtpCode('');
    setError('');
    setMessage('');
  };

  const reset = (nextMode: Mode) => {
    setMode(nextMode);
    setError('');
    setMessage('');
  };

  return (
    <div className="min-h-screen bg-slate-900 flex items-center justify-center p-4">
      <div className="w-full max-w-md">

        <div className="text-center mb-8">
          <img
            src="/images/sunbeltaiserviceslog.png"
            alt="Sunbelt AI Services"
            className="mx-auto mb-4 h-16 w-16 object-contain rounded-xl bg-white p-1.5 shadow-lg border border-slate-700/50"
            onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }}
          />
          <h1 className="text-3xl font-bold tracking-tight text-blue-400">Sunbelt Mail Matrix</h1>
          <p className="text-slate-500 text-sm mt-2 uppercase tracking-widest font-bold">Email Campaign Management</p>
        </div>

        {/* ── STEP 2: OTP VERIFICATION ── */}
        {step === 'otp' ? (
          <div className="bg-white rounded-2xl shadow-2xl p-8">
            <div className="text-center mb-6">
              <div className="w-14 h-14 bg-blue-50 rounded-full flex items-center justify-center mx-auto mb-4 text-2xl">🔐</div>
              <h2 className="text-xl font-bold text-slate-800">Check your email</h2>
              <p className="text-slate-500 text-sm mt-2">We sent a 6-digit code to</p>
              <p className="font-bold text-slate-700 text-sm mt-0.5 break-all">{email}</p>
            </div>

            {error && (
              <div className="bg-red-50 text-red-700 p-3 rounded-lg text-sm mb-4 border border-red-100">{error}</div>
            )}
            {message && (
              <div className="bg-green-50 text-green-700 p-3 rounded-lg text-sm mb-4 border border-green-100">{message}</div>
            )}

            <form onSubmit={handleOtp} className="space-y-5">
              <div>
                <label className="text-[10px] font-black uppercase tracking-widest text-slate-400 block mb-2">
                  Verification Code
                </label>
                <input
                  ref={otpInputRef}
                  type="text"
                  inputMode="numeric"
                  maxLength={6}
                  value={otpCode}
                  onChange={e => setOtpCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                  placeholder="000000"
                  className="w-full border-2 border-slate-200 focus:border-blue-500 p-4 rounded-xl text-center text-3xl font-mono tracking-[0.6em] outline-none transition-colors text-slate-900 placeholder:text-slate-200 placeholder:tracking-[0.6em]"
                  autoComplete="one-time-code"
                />
              </div>
              <button
                type="submit"
                disabled={loading || otpCode.length !== 6}
                className="w-full bg-blue-600 text-white py-3.5 rounded-xl font-bold hover:bg-blue-700 transition-colors disabled:opacity-50"
              >
                {loading ? 'Verifying…' : 'Verify & Sign In'}
              </button>
            </form>

            <div className="text-center mt-5 space-y-2">
              {countdown > 0 ? (
                <p className="text-slate-400 text-sm">Resend available in {countdown}s</p>
              ) : (
                <button onClick={handleResend} className="text-blue-600 text-sm font-medium hover:underline">
                  Resend code
                </button>
              )}
              <div>
                <button onClick={handleBackToSignIn} className="text-slate-400 text-xs hover:text-slate-600 transition-colors">
                  ← Back to sign in
                </button>
              </div>
            </div>
          </div>

        ) : (
        /* ── STEP 1: CREDENTIALS / VETTING ── */
          <div className="bg-white rounded-2xl shadow-2xl p-8">
            <h2 className="text-xl font-bold text-slate-800 mb-6">
              {mode === 'signin' ? 'Sign in to your account' : mode === 'signup' ? 'Request an Invitation' : 'Reset your password'}
            </h2>

            {error && (
              <div className="bg-red-50 text-red-700 p-3 rounded-lg text-sm mb-4 border border-red-100">{error}</div>
            )}
            {message && (
              <div className="bg-green-50 text-green-700 p-3 rounded-lg text-sm mb-4 border border-green-100">{message}</div>
            )}

            <form onSubmit={handleCredentials} className="space-y-4">
              <div>
                <label className="text-[10px] font-black uppercase tracking-widest text-slate-400 block mb-1">
                  {mode === 'signup' ? 'Business Email Address' : 'Email Address'}
                </label>
                <input
                  type="email"
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  required
                  autoComplete="email"
                  placeholder={mode === 'signup' ? 'you@yourcompany.com' : 'you@example.com'}
                  className="w-full border border-slate-200 p-3 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 text-slate-800"
                />
              </div>

              {/* Password — sign in only */}
              {mode === 'signin' && (
                <div>
                  <label className="text-[10px] font-black uppercase tracking-widest text-slate-400 block mb-1">
                    Password
                  </label>
                  <div className="relative">
                    <input
                      type={showPassword ? 'text' : 'password'}
                      value={password}
                      onChange={e => setPassword(e.target.value)}
                      required
                      autoComplete="current-password"
                      placeholder="••••••••"
                      className="w-full border border-slate-200 p-3 pr-11 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 text-slate-800"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(v => !v)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors"
                      tabIndex={-1}
                      aria-label={showPassword ? 'Hide password' : 'Show password'}
                    >
                      {showPassword ? (
                        <svg xmlns="http://www.w3.org/2000/svg" className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                        </svg>
                      ) : (
                        <svg xmlns="http://www.w3.org/2000/svg" className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                        </svg>
                      )}
                    </button>
                  </div>
                </div>
              )}

              {/* Vetting fields — request access only */}
              {mode === 'signup' && (
                <>
                  <div>
                    <label className="text-[10px] font-black uppercase tracking-widest text-slate-400 block mb-1">
                      Company Website URL
                    </label>
                    <input
                      type="url"
                      value={websiteUrl}
                      onChange={e => setWebsiteUrl(e.target.value)}
                      required
                      placeholder="https://yourcompany.com"
                      className="w-full border border-slate-200 p-3 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 text-slate-800"
                    />
                  </div>

                  <div>
                    <label className="text-[10px] font-black uppercase tracking-widest text-slate-400 block mb-1">
                      Primary Use Case for Campaigns
                    </label>
                    <textarea
                      value={useCase}
                      onChange={e => setUseCase(e.target.value)}
                      required
                      rows={2}
                      placeholder="e.g., Sending marketing newsletters and service schedules to our existing local clients."
                      className="w-full border border-slate-200 p-3 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 text-slate-800 text-sm resize-none"
                    />
                  </div>

                  <div>
                    <label className="text-[10px] font-black uppercase tracking-widest text-slate-400 block mb-1">
                      How was your current email list built?
                    </label>
                    <input
                      type="text"
                      value={listMethod}
                      onChange={e => setListMethod(e.target.value)}
                      required
                      placeholder="e.g., Contact forms on our website, point of sale signups"
                      className="w-full border border-slate-200 p-3 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 text-slate-800 text-sm"
                    />
                  </div>

                  <div>
                    <label className="text-[10px] font-black uppercase tracking-widest text-slate-400 block mb-1">
                      Estimated Contact List Size
                    </label>
                    <select
                      value={listSize}
                      onChange={e => setListSize(e.target.value as ListSize)}
                      className="w-full border border-slate-200 p-3 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 text-slate-800 bg-white"
                    >
                      <option value="Under 500">Under 500 subscribers</option>
                      <option value="500-2000">500 – 2,000 subscribers</option>
                      <option value="2000+">More than 2,000 subscribers</option>
                    </select>
                  </div>
                </>
              )}

              {mode === 'signin' && (
                <div className="text-right -mt-1">
                  <button type="button" onClick={() => reset('forgot')} className="text-xs text-slate-400 hover:text-blue-600 transition-colors">
                    Forgot password?
                  </button>
                </div>
              )}

              <button
                type="submit"
                disabled={loading}
                className="w-full bg-blue-600 text-white py-3 rounded-xl font-bold hover:bg-blue-700 transition-colors disabled:opacity-60"
              >
                {loading
                  ? '…'
                  : mode === 'signin'
                  ? 'Sign In'
                  : mode === 'signup'
                  ? 'Submit Trial Request'
                  : 'Send Reset Link'}
              </button>
            </form>

            {mode === 'signin' && (
              <p className="text-center text-[11px] text-slate-400 mt-5">
                A verification code will be sent to your email after sign-in.
              </p>
            )}

            <div className="text-center text-sm text-slate-500 mt-4 space-y-2">
              {mode === 'forgot' ? (
                <p>
                  <button onClick={() => reset('signin')} className="text-blue-600 font-bold hover:underline">
                    Back to sign in
                  </button>
                </p>
              ) : (
                <p>
                  {mode === 'signin' ? 'Want to evaluate Sunbelt Mail Matrix? ' : 'Already have an account? '}
                  <button
                    onClick={() => reset(mode === 'signin' ? 'signup' : 'signin')}
                    className="text-blue-600 font-bold hover:underline"
                  >
                    {mode === 'signin' ? 'Request Invite' : 'Sign in'}
                  </button>
                </p>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Login;
