import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { ArrowRight, Shield } from 'lucide-react';
import { ReLogo, LandingPageImage } from '@/assets';
import { initiateTanflowLogin } from '@/services/tanflowAuth';

export function Auth() {
  const { login, isLoading, error } = useAuth();
  const [tanflowLoading, setTanflowLoading] = useState(false);
  const [tanflowError, setTanflowError] = useState<string | null>(null);
  const [imageLoaded, setImageLoaded] = useState(false);

  useEffect(() => {
    const img = new Image();
    img.src = LandingPageImage;
    img.onload = () => setImageLoaded(true);
    if (img.complete) setImageLoaded(true);
  }, []);

  const handleOKTALogin = async () => {
    // Preserve force-reauth flag so Okta gets prompt=login after logout (must re-enter password)
    const forceReauth = sessionStorage.getItem('__force_reauth_after_logout__');
    localStorage.clear();
    sessionStorage.clear();
    if (forceReauth) sessionStorage.setItem('__force_reauth_after_logout__', forceReauth);

    try {
      sessionStorage.setItem('auth_provider', 'okta');
      await login();
    } catch (loginError) {
      console.error('OKTA LOGIN ERROR', loginError);
    }
  };

  const handleTanflowLogin = () => {
    setTanflowError(null);
    localStorage.clear();
    sessionStorage.clear();
    sessionStorage.setItem('auth_provider', 'tanflow');

    setTanflowLoading(true);
    try {
      initiateTanflowLogin();
      // If no throw, redirect is in progress
    } catch (loginError: unknown) {
      const message = loginError instanceof Error ? loginError.message : 'Dealer login failed. Check console for details.';
      console.error('TANFLOW LOGIN ERROR', loginError);
      setTanflowError(message);
      setTanflowLoading(false);
    }
  };

  if (error) {
    console.error('Auth Error:', { message: error.message, error });
  }

  return (
    <div
      className="min-h-screen flex items-center justify-center p-4 relative overflow-hidden"
      style={{
        backgroundImage: imageLoaded ? `url(${LandingPageImage})` : 'none',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
      }}
    >
      {!imageLoaded && (
        <div className="absolute inset-0 bg-gradient-to-br from-slate-900 to-slate-800" />
      )}
      {/* Blurred overlay so background stays subdued */}
      <div className="absolute inset-0 bg-black/50 backdrop-blur-[2px]" aria-hidden />
      <div className="absolute inset-0 bg-black/30" aria-hidden />

      <Card className="w-full max-w-md shadow-2xl relative z-10 bg-gray-900/95 border border-gray-700 text-white">
        <CardHeader className="space-y-1 text-center pb-6 pt-8">
          <div className="flex flex-col items-center justify-center">
            <img
              src={ReLogo}
              alt="Royal Enfield"
              className="h-9 w-auto max-w-[180px] object-contain mb-2"
            />
            <p className="text-sm text-gray-400">Approval Portal</p>
          </div>
        </CardHeader>

        <CardContent className="space-y-5 pb-8 px-8">
          {error && (
            <div className="bg-red-900/40 border border-red-700 text-red-200 px-4 py-3 rounded-lg text-sm">
              <p className="font-medium">Authentication Error</p>
              <p>{error.message}</p>
              {(error.message?.includes('401') || error.message?.toLowerCase().includes('unauthorized')) && (
                <p className="mt-2 text-xs text-red-300">
                  If you see 401 from Okta: your Okta admin must add this site’s URL to <strong>Trusted Origins</strong> and ensure the RE Employee application is active. Use <strong>Dealer Login</strong> if you are a dealer.
                </p>
              )}
            </div>
          )}
          {tanflowError && (
            <div className="bg-amber-900/40 border border-amber-700 text-amber-200 px-4 py-3 rounded-lg text-sm">
              <p className="font-medium">Dealer Login (Tanflow)</p>
              <p>{tanflowError}</p>
            </div>
          )}

          <Button
            onClick={handleOKTALogin}
            disabled={isLoading || tanflowLoading}
            className="w-full h-12 bg-re-red hover:bg-re-red/90 text-white font-semibold text-base border-0"
            size="lg"
          >
            {isLoading ? (
              <div className="h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent" />
            ) : (
              <>
                <ArrowRight className="mr-2 h-5 w-5" />
                RE Employee Login
              </>
            )}
          </Button>

          <div className="flex items-center gap-3">
            <span className="flex-1 h-px bg-gray-600" />
            <span className="text-sm text-gray-400 uppercase tracking-wide">Or</span>
            <span className="flex-1 h-px bg-gray-600" />
          </div>

          <Button
            onClick={handleTanflowLogin}
            disabled={isLoading || tanflowLoading}
            className="w-full h-12 bg-blue-600 hover:bg-blue-700 text-white font-semibold text-base border-0"
            size="lg"
          >
            {tanflowLoading ? (
              <div className="h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent" />
            ) : (
              <>
                <Shield className="mr-2 h-5 w-5" />
                Dealer Login
              </>
            )}
          </Button>

          <div className="text-center pt-2">
            <p className="text-sm text-gray-400">Secure Single Sign On</p>
            <p className="text-xs text-gray-500 mt-1">Choose your authentication provider.</p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

