import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import api from '../lib/api'; // Our API client
import { getImagePath } from '../lib/utils';

// Import shadcn/ui components
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { OTPVerification } from './OTPVerification';

export function LoginPage() {
    // State to hold form data, errors, and loading status
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [showPassword, setShowPassword] = useState(false);
    
    // OTP verification state
    const [showOTP, setShowOTP] = useState(false);
    const [loginData, setLoginData] = useState(null);

    // Hook for programmatic navigation after login
    const navigate = useNavigate();

    // Check for existing token on component mount
    useEffect(() => {
        if (typeof window !== "undefined") {
            const token = localStorage.getItem("accessToken");
            if (token) {
                navigate('/dashboard');
            }
        }
    }, [navigate]);

    // Handle username input - only allow numbers
    const handleUsernameChange = (e) => {
        const value = e.target.value;
        // Only allow numbers and limit to 8 digits
        if (/^\d{0,8}$/.test(value)) {
            setUsername(value);
            // Clear error when user starts typing valid input
            if (error && /^\d+$/.test(value)) {
                setError('');
            }
        } else {
            // Set error for invalid characters
            setError('Login ID must contain only numbers (0-9).');
        }
    };

    // Handle paste event to filter out non-numeric characters
    const handleUsernamePaste = (e) => {
        e.preventDefault();
        const pastedText = e.clipboardData.getData('text');
        const numericOnly = pastedText.replace(/\D/g, '').slice(0, 8);
        if (numericOnly) {
            setUsername(numericOnly);
            if (error) {
                setError('');
            }
        } else {
            setError('Login ID must contain only numbers (0-9).');
        }
    };

    const handleLogin = async (e) => {
        e.preventDefault(); // Prevent page reload on form submission
        setIsLoading(true);
        setError('');

        // Validate that username contains only numbers
        if (!/^\d+$/.test(username)) {
            setError('Login ID must contain only numbers (0-9).');
            setIsLoading(false);
            return;
        }

        // Validate that username is not empty
        if (!username.trim()) {
            setError('Login ID is required.');
            setIsLoading(false);
            return;
        }

        // Validate that password is not empty
        if (!password.trim()) {
            setError('Password is required.');
            setIsLoading(false);
            return;
        }

        try {
                      
            const response = await api.post('/login', {
                id: username,
                password: password
            });
            
            
            // Check if the response indicates OTP will be sent
            if (response.data.responseCode === "0") {
               
                // Store the login data for OTP verification
                setLoginData({
                    username: username,
                    password: password,
                    access_token: response.data.access_token, // Store the access token if provided
                    responseDesc: response.data.responseDesc
                });
                
                // Show OTP verification screen
                setShowOTP(true);
            } else {
               
                // Handle other response codes
                setError(response.data.responseDesc || 'Login failed. Please try again.');
            }

        } catch (err) {
           
            // Set a user-friendly error message
            setError(err.response?.data?.responseDesc || err.response?.data?.detail || 'An unexpected error occurred.');
        } finally {
            // Re-enable the button whether the request succeeded or failed
            setIsLoading(false);
        }
    };

    const handleBackToLogin = () => {
        setShowOTP(false);
        setLoginData(null);
        setError('');
    };

    const togglePasswordVisibility = () => {
        setShowPassword(!showPassword);
    };

    // If OTP verification is active, show the OTP component
    if (showOTP && loginData) {
        return (
            <OTPVerification 
                loginData={loginData} 
                onBackToLogin={handleBackToLogin}
            />
        );
    }

    return (
        <div className="relative flex justify-center items-center min-h-screen bg-gradient-to-br from-gray-50 to-blue-100 overflow-hidden">
            {/* Decorative Background Graphics */}
            <svg className="absolute left-[-100px] top-[-100px] w-[400px] h-[400px] opacity-30 blur-2xl z-0" viewBox="0 0 400 400" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="200" cy="200" r="200" fill="#60A5FA" />
            </svg>
            <svg className="absolute right-[-120px] bottom-[-120px] w-[350px] h-[350px] opacity-20 blur-2xl z-0" viewBox="0 0 350 350" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="175" cy="175" r="175" fill="#818CF8" />
            </svg>
            <svg className="absolute left-1/2 top-0 -translate-x-1/2 w-[200px] h-[200px] opacity-10 blur-3xl z-0" viewBox="0 0 200 200" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect width="200" height="200" rx="100" fill="#F472B6" />
            </svg>
            
            {/* Form Side */}
            <div className="flex w-full items-center justify-center p-2 z-10">
                <Card className="w-full max-w-sm md:max-w-2xl min-h-[420px] rounded-2xl shadow-2xl border border-gray-200 bg-white py-3 px-3 md:py-4 md:px-6 flex flex-col md:flex-row justify-center items-center">
                    <div className="flex flex-col md:flex-row items-center justify-center gap-2 md:gap-4 w-full">
                        {/* Logo Section */}
                        <div className="flex flex-col items-center justify-center w-full md:w-auto mb-1 md:mb-4">
                            <img 
                                src={getImagePath("telangana-police-logo.svg")} 
                                alt="Telangana Police Logo" 
                                className="w-20 h-20 sm:w-28 sm:h-28 md:w-36 md:h-36 object-contain"
                            />
                        </div>
                        
                        {/* Separator (only on desktop) */}
                        <div className="hidden md:block h-[180px] md:h-[200px] w-px bg-gray-200 mx-2 md:mx-3" />
                        
                        {/* Login Form */}
                        <div className="grid flex-1 min-w-0 w-full">
                            <div className="col-start-1 row-start-1">
                                <CardHeader className="text-center pb-2">
                                    <CardTitle className="text-lg md:text-xl font-bold font-sans">Sign in to your account</CardTitle>
                                    <CardDescription className="mb-2 md:mb-4 text-gray-500 text-xs md:text-sm">Welcome back! Please enter your credentials.</CardDescription>
                                </CardHeader>
                                <form onSubmit={handleLogin}>
                                    <CardContent className="space-y-3 md:space-y-4">
                                        <div>
                                            <Label htmlFor="username" className="block mb-1 text-xs md:text-sm font-medium font-sans">Login ID</Label>
                                            <Input 
                                                id="username" 
                                                className="h-9 md:h-10 px-3 md:px-4 border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-100 text-sm md:text-base font-mono"
                                                type="text" 
                                                inputMode="numeric"
                                                pattern="[0-9]*"
                                                maxLength={8}
                                                placeholder="Enter your Login ID" 
                                                value={username}
                                                onChange={handleUsernameChange}
                                                onPaste={handleUsernamePaste}
                                                required 
                                                aria-invalid={!!error}
                                                aria-describedby={error ? "login-error" : undefined}
                                            />
                                        </div>
                                        <div>
                                            <Label htmlFor="password" className="block mb-1 text-xs md:text-sm font-medium font-sans">Password</Label>
                                            <div className="relative">
                                                <Input 
                                                    id="password" 
                                                    className="h-9 md:h-10 px-3 md:px-4 pr-10 border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-100 text-sm md:text-base"
                                                    type={showPassword ? "text" : "password"}
                                                    placeholder="Enter your password"
                                                    value={password}
                                                    onChange={(e) => setPassword(e.target.value)}
                                                    required 
                                                />
                                                <Button
                                                    type="button"
                                                    variant="ghost"
                                                    size="sm"
                                                    className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7 p-0 hover:bg-gray-100 rounded-md"
                                                    onClick={togglePasswordVisibility}
                                                    aria-label={showPassword ? "Hide password" : "Show password"}
                                                >
                                                    {showPassword ? (
                                                        <svg className="h-4 w-4 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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.878 9.878L3 3m6.878 6.878L21 21" />
                                                        </svg>
                                                    ) : (
                                                        <svg className="h-4 w-4 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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>
                                        {error && (
                                            <div id="login-error" className="text-red-600 text-xs md:text-sm text-center mt-1" role="alert">
                                                {error}
                                            </div>
                                        )}
                                        <Button 
                                            type="submit" 
                                            className="w-full h-9 md:h-10 text-sm md:text-base font-semibold bg-blue-600 hover:bg-blue-700 transition-colors"
                                            disabled={isLoading}
                                        >
                                            {isLoading ? 'Signing In...' : 'Sign In'}
                                        </Button>
                                    </CardContent>
                                </form>
                            </div>
                        </div>
                    </div>
                </Card>
            </div>
            
            {/* Footer */}
            <div className="absolute bottom-0 left-0 right-0 p-4 text-center text-sm text-gray-500">
                <p>© 2025 PushpakAI. All rights reserved.</p>
            </div>
        </div>
    );
}