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 { LogIn } from 'lucide-react';
import { ReLogo, LandingPageImage } from '@/assets';
// import { initiateTanflowLogin } from '@/services/tanflowAuth';

export function Auth() {
  const { login, isLoading, error } = useAuth();
  const [tanflowLoading] = useState(false);
  const [imageLoaded, setImageLoaded] = useState(false);

  // Preload the background image
  useEffect(() => {
    const img = new Image();
    img.src = LandingPageImage;
    img.onload = () => {
      setImageLoaded(true);
    };
    // If image is already cached, trigger load immediately
    if (img.complete) {
      setImageLoaded(true);
    }
  }, []);

  const handleOKTALogin = async () => {
    // Clear any existing session data
    localStorage.clear();
    sessionStorage.clear();

    try {
      await login();
    } catch (loginError) {
      console.error('========================================');
      console.error('OKTA LOGIN ERROR');
      console.error('Error details:', loginError);
      console.error('Error message:', (loginError as Error)?.message);
      console.error('Error stack:', (loginError as Error)?.stack);
      console.error('========================================');
    }
  };

  /* const handleTanflowLogin = () => {
    // Clear any existing session data
    localStorage.clear();
    sessionStorage.clear();

    setTanflowLoading(true);
    try {
      initiateTanflowLogin();
    } catch (loginError) {
      console.error('========================================');
      console.error('TANFLOW LOGIN ERROR');
      console.error('Error details:', loginError);
      setTanflowLoading(false);
    }
  }; */

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

  return (
    <div
      className="min-h-screen flex items-center justify-center p-4 relative"
      style={{
        backgroundImage: imageLoaded ? `url(${LandingPageImage})` : 'none',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        transition: 'background-image 0.3s ease-in-out'
      }}
    >
      {/* Fallback background while image loads */}
      {!imageLoaded && (
        <div className="absolute inset-0 bg-gradient-to-br from-slate-900 to-slate-800"></div>
      )}
      {/* Overlay for better readability */}
      <div className="absolute inset-0 bg-black/40"></div>

      <Card className="w-full max-w-md shadow-xl relative z-10 bg-black backdrop-blur-sm border-gray-800">
        <CardHeader className="space-y-1 text-center pb-6">
          <div className="flex flex-col items-center justify-center mb-4">
            <img
              src={ReLogo}
              alt="Royal Enfield Logo"
              className="h-10 w-auto max-w-[168px] object-contain mb-2"
            />
            <p className="text-xs text-gray-300 text-center truncate">Approval Portal</p>
          </div>
        </CardHeader>

        <CardContent className="space-y-4">
          {error && (
            <div className="bg-red-900/50 border border-red-700 text-red-200 px-4 py-3 rounded-lg">
              <p className="text-sm font-medium">Authentication Error</p>
              <p className="text-sm">{error.message}</p>
            </div>
          )}

          <div className="space-y-3">
            <Button
              onClick={handleOKTALogin}
              disabled={isLoading || tanflowLoading}
              className="w-full h-12 text-base font-semibold bg-re-red hover:bg-re-red/90 text-white"
              size="lg"
            >
              {isLoading ? (
                <>
                  <div
                    className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"
                  />
                  Logging in...
                </>
              ) : (
                <>
                  <LogIn className="mr-2 h-5 w-5" />
                  RE Employee Login
                </>
              )}
            </Button>
            {/* 
            <div className="relative">
              <div className="absolute inset-0 flex items-center">
                <span className="w-full border-t border-gray-700"></span>
              </div>
              <div className="relative flex justify-center text-xs uppercase">
                <span className="bg-gray-900 px-2 text-gray-400">Or</span>
              </div>
            </div>

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

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

