import { FormEvent, useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import AuthShell from '@/calyx-app/pages/auth/AuthShell';
import { authService } from '@/services/auth';
import { useAuth } from '@/contexts/AuthContext';
import { useToast } from '@/hooks/use-toast';
import { prefetchSignup, prefetchCalyxHome } from '@/lib/prefetch';

export default function Signin() {
  const navigate = useNavigate();
  const location = useLocation();
  const { login, isAuthenticated, role } = useAuth();
  const { toast } = useToast();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [remember, setRemember] = useState(true);
  const [loading, setLoading] = useState(false);
  const [googleLoading, setGoogleLoading] = useState(false);

  useEffect(() => {
    const saved = authService.getSavedEmail();
    if (saved) setEmail(saved);
  }, []);

  useEffect(() => {
    const googleError = (location.state as any)?.googleError;
    if (googleError) {
      toast({ title: 'Sign-in failed', description: googleError, variant: 'destructive' });
      window.history.replaceState({}, '', location.pathname);
    }
  }, [location.state, location.pathname, toast]);

  // Show a notice when redirected here by httpClient after a 401 (expired session).
  useEffect(() => {
    const params = new URLSearchParams(location.search);
    if (params.get('reason') === 'expired') {
      toast({
        title: 'Session expired',
        description: 'Please sign in again to continue.',
        variant: 'destructive',
      });
      params.delete('reason');
      const qs = params.toString();
      window.history.replaceState({}, '', location.pathname + (qs ? `?${qs}` : ''));
    }
  }, [location.search, location.pathname, toast]);

  useEffect(() => {
    if (isAuthenticated) {
      if (role === 'SUPERADMIN') navigate('/admin/dashboard', { replace: true });
      else navigate('/calyx/home', { replace: true });
    }
  }, [isAuthenticated, role, navigate]);

  const handleGoogle = async () => {
    setGoogleLoading(true);
    try {
      const res = await authService.initiateGoogleAuth();
      if (res.status === 'success' && res.data?.authUrl) {
        window.location.href = res.data.authUrl;
      } else {
        toast({ title: 'Error', description: 'Failed to connect to Google.', variant: 'destructive' });
      }
    } catch (err: any) {
      toast({ title: 'Error', description: err.message || 'Failed to connect to Google.', variant: 'destructive' });
    } finally {
      setGoogleLoading(false);
    }
  };

  const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await authService.signin({ email, password });
      if (res.status === 'success' && res.data?.accessToken) {
        if (remember) authService.saveEmail(email);
        else authService.clearSavedEmail();
        login(res.data.accessToken, remember);
        toast({ title: 'Welcome back', description: res.message });
      }
    } catch (err: any) {
      const msg = err.message || 'Something went wrong';
      if (msg.includes('UserNotConfirmedException')) {
        toast({ title: 'Email not verified', description: 'Please verify your email to continue.', variant: 'destructive' });
        navigate('/verify-otp', { state: { email, password, mode: 'signup' } });
      } else {
        toast({ title: 'Sign-in failed', description: msg, variant: 'destructive' });
      }
    } finally {
      setLoading(false);
    }
  };

  const disabled = loading || googleLoading;

  return (
    <AuthShell side="signin">
      <div className="auth-card">
        <div className="head">
          <div className="eyebrow-mono">Sign in</div>
          <h1>Welcome <em>back.</em></h1>
          <p className="lede">Pick up right where you left off — your next booking is waiting.</p>
        </div>

        <div className="sso">
          <button type="button" aria-label="Continue with Google" onClick={handleGoogle} disabled={disabled}>
            <svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg">
              <path d="M17.64 9.2c0-.64-.06-1.25-.17-1.84H9v3.49h4.84a4.14 4.14 0 01-1.8 2.72v2.26h2.92c1.7-1.57 2.68-3.88 2.68-6.63z" fill="#4285F4" />
              <path d="M9 18c2.43 0 4.47-.81 5.96-2.18l-2.92-2.26c-.81.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.03-3.7H.96v2.33A9 9 0 009 18z" fill="#34A853" />
              <path d="M3.97 10.71A5.41 5.41 0 013.68 9c0-.59.1-1.17.29-1.71V4.96H.96A9 9 0 000 9c0 1.45.35 2.82.96 4.04l3.01-2.33z" fill="#FBBC05" />
              <path d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.58A8.97 8.97 0 009 0 9 9 0 00.96 4.96L3.97 7.3C4.68 5.16 6.66 3.58 9 3.58z" fill="#EA4335" />
            </svg>
            {googleLoading ? 'Connecting…' : 'Google'}
          </button>
          <button type="button" aria-label="Continue with Apple" disabled={disabled}>
            <svg width="16" height="18" viewBox="0 0 16 18" fill="#000" xmlns="http://www.w3.org/2000/svg">
              <path d="M13.27 9.47c-.02-2.16 1.77-3.21 1.85-3.26-1.01-1.47-2.58-1.68-3.14-1.7-1.34-.13-2.61.79-3.29.79-.69 0-1.73-.77-2.84-.75-1.46.02-2.81.85-3.56 2.15-1.52 2.63-.39 6.53 1.09 8.67.72 1.04 1.59 2.22 2.7 2.18 1.08-.04 1.5-.7 2.81-.7s1.68.7 2.83.68c1.17-.02 1.91-1.06 2.62-2.12.83-1.22 1.17-2.41 1.19-2.47-.03-.01-2.27-.87-2.3-3.45zM10.95 3.1c.59-.72.99-1.71.88-2.7-.85.03-1.88.56-2.5 1.27-.55.63-1.03 1.65-.9 2.62.95.07 1.92-.48 2.52-1.19z" />
            </svg>
            Apple
          </button>
        </div>

        <div className="divider">or continue with email</div>

        <form className="form-stack" onSubmit={onSubmit}>
          <div className="field">
            <label htmlFor="cz-email">Email</label>
            <input
              id="cz-email"
              type="email"
              placeholder="you@studio.co"
              autoComplete="email"
              required
              value={email}
              onChange={e => setEmail(e.target.value)}
              disabled={disabled}
            />
          </div>
          <div className="field">
            <label htmlFor="cz-pw">
              Password <a href="/forgot-password">Forgot?</a>
            </label>
            <input
              id="cz-pw"
              type="password"
              placeholder="••••••••"
              autoComplete="current-password"
              required
              value={password}
              onChange={e => setPassword(e.target.value)}
              disabled={disabled}
            />
          </div>

          <label className="checkbox-row">
            <input
              type="checkbox"
              checked={remember}
              onChange={e => setRemember(e.target.checked)}
              disabled={disabled}
            />
            Keep me signed in on this device
          </label>

          <button
            type="submit"
            className="btn-primary-lg"
            disabled={disabled}
            onMouseEnter={prefetchCalyxHome}
            onFocus={prefetchCalyxHome}
          >
            {loading ? 'Signing in…' : <>Sign in <span>→</span></>}
          </button>
        </form>

        <div className="auth-alt">
          New to Calynza? <a href="/signup" onMouseEnter={prefetchSignup}>Start free — no card needed</a>
        </div>

        <div className="legal">
          By continuing you agree to our <a href="/terms">Terms</a> and <a href="/privacy">Privacy Policy</a>.
        </div>
      </div>
    </AuthShell>
  );
}
