import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import api, { setTokenTimestamp } from '../lib/api';
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";

export function OTPVerification({ loginData, onBackToLogin }) {
    const [otp, setOtp] = useState(['', '', '', '', '', '']);
    const [error, setError] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [resendCooldown, setResendCooldown] = useState(120);
    const [isResending, setIsResending] = useState(false);
    
    const navigate = useNavigate();
    const inputRefs = useRef([]);

    // Handle resend cooldown timer
    useEffect(() => {
        let timer;
        if (resendCooldown > 0) {
            timer = setTimeout(() => setResendCooldown(resendCooldown - 1), 1000);
        }
        return () => clearTimeout(timer);
    }, [resendCooldown]);

    const handleSendOTP = async () => {
        setIsResending(true);
        setError('');
        
        try {
            const response = await api.post('/login', {
                id: loginData.username,
                password: loginData.password
            });
            
            if (response.data.responseCode === "0") {
                setResendCooldown(120);
                setOtp(['', '', '', '', '', '']); // Clear OTP
              
            } else {
                setError("Failed to send OTP. Please try again.");
            }
        } catch (err) {
            setError(err.response?.data?.responseDesc || 'Failed to send OTP. Please try again.');
        } finally {
            setIsResending(false);
        }
    };

    const handleVerifyOTP = async (e) => {
        e.preventDefault();
        
        const otpString = otp.join('');
        if (otpString.length !== 6) {
            setError('Please enter the complete 6-digit OTP.');
            return;
        }

        setIsLoading(true);
        setError('');

        try {
           
            const response = await api.post('/verify-otp', {
                id: loginData.username,
                otp: otpString,
                user_type: "operator"
            }, {
                headers: {
                    'X-Skip-Auth-Redirect': 'true' // Prevent automatic redirect
                }
            });

           

            if (response.data.responseCode === "0") {
               
                
                // Check if we received an access token in the response
                if (response.data.access_token) {
                    
                    localStorage.setItem('accessToken', response.data.access_token);
                    setTokenTimestamp(); // Set timestamp for 8-hour expiration
                } else {
                    
                    // If no token in response, use the one from login data
                    if (loginData.access_token) {
                        localStorage.setItem('accessToken', loginData.access_token);
                        setTokenTimestamp(); // Set timestamp for 8-hour expiration
                    }
                }
                
                // Navigate to dashboard on success
                navigate('/dashboard');
            } else {
               
                setError(response.data.responseDesc || 'Invalid OTP. Please try again.');
                // Clear OTP on wrong attempt
                setOtp(['', '', '', '', '', '']);
                // Focus first input
                if (inputRefs.current[0]) {
                    inputRefs.current[0].focus();
                }
            }
        } catch (err) {
            console.error('OTP verification error:', err);
            console.error('Error response:', err.response?.data);
            setError(err.response?.data?.responseDesc || 'Verification failed. Please try again.');
            // Clear OTP on error
            setOtp(['', '', '', '', '', '']);
            // Focus first input
            if (inputRefs.current[0]) {
                inputRefs.current[0].focus();
            }
        } finally {
            setIsLoading(false);
        }
    };

    const handleResendOTP = async () => {
        if (resendCooldown > 0) return;
        await handleSendOTP();
    };

    const handleOtpChange = (index, value) => {
        // Only allow numbers
        if (/^\d$/.test(value) || value === '') {
            const newOtp = [...otp];
            newOtp[index] = value;
            setOtp(newOtp);

            // Auto-focus next input if value is entered
            if (value && index < 5) {
                inputRefs.current[index + 1]?.focus();
            }
        }
    };

    const handleKeyDown = (index, e) => {
        // Handle backspace to go to previous input
        if (e.key === 'Backspace' && !otp[index] && index > 0) {
            inputRefs.current[index - 1]?.focus();
        }
    };

    const handleBackToLogin = () => {
        onBackToLogin();
    };

    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" />
                        
                        {/* OTP Form Section */}
                        <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">
                                        OTP verification
                                    </CardTitle>
                                    <CardDescription className="mb-2 md:mb-4 text-gray-500 text-xs md:text-sm">
                                        OTP sent to your registered mobile number
                                    </CardDescription>
                                </CardHeader>
                                
                                <form onSubmit={handleVerifyOTP}>
                                    <CardContent className="space-y-3 md:space-y-4">
                                        {/* OTP Input Boxes */}
                                        <div className="flex justify-center">
                                            <div className="flex gap-2 md:gap-3">
                                                {otp.map((digit, index) => (
                                                    <Input
                                                        key={index}
                                                        ref={el => inputRefs.current[index] = el}
                                                        type="text"
                                                        maxLength={1}
                                                        required
                                                        value={digit}
                                                        onChange={(e) => handleOtpChange(index, e.target.value)}
                                                        onKeyDown={(e) => handleKeyDown(index, e)}
                                                        placeholder="0"
                                                        className="w-10 h-10 md:w-12 md:h-12 text-center text-lg md:text-xl font-mono border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-100"
                                                        autoComplete="one-time-code"
                                                        inputMode="numeric"
                                                        pattern="[0-9]*"
                                                    />
                                                ))}
                                            </div>
                                        </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 || otp.join('').length < 6}
                                        >
                                            {isLoading ? "Verifying..." : "Verify"}
                                        </Button>
                                        
                                        <div className="text-center">
                                            <Button
                                                type="button"
                                                variant="link"
                                                onClick={handleResendOTP}
                                                disabled={resendCooldown > 0 || isResending}
                                                className="text-xs md:text-sm text-gray-600 hover:text-gray-800"
                                            >
                                                {resendCooldown > 0 
                                                    ? `Resend code in ${resendCooldown}s` 
                                                    : isResending 
                                                        ? "Sending..." 
                                                        : "Resend code"
                                                }
                                            </Button>
                                        </div>
                                        
                                        {error && (
                                            <div className="text-red-600 text-xs md:text-sm text-center mt-1" role="alert">
                                                {error}
                                            </div>
                                        )}
                                    </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>
    );
}
