import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { AlertCircle, ArrowLeft, Smartphone } from 'lucide-react';
import { toast } from 'sonner';
import { API } from '@/api/API';
import { useDispatch } from 'react-redux';
import { setCredentials } from '@/store/slices/authSlice';

export function ProspectiveLoginPage() {
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [step, setStep] = useState<'PHONE' | 'OTP'>('PHONE');
    const [phone, setPhone] = useState('');
    const [otp, setOtp] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');

    const handleSendOtp = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!phone || phone.length < 10) {
            setError('Please enter a valid 10-digit phone number');
            return;
        }

        setIsLoading(true);
        setError('');

        try {
            const response = await API.sendOtp(phone) as any;

            if (response.ok) {
                setStep('OTP');
                toast.success('OTP sent successfully!');
            } else {
                console.error('Send OTP error response:', response);
                const errorMessage = response.data?.message || 'Failed to send OTP';
                setError(errorMessage);
                toast.error(errorMessage);
            }
        } catch (err: any) {
            console.error('Send OTP network error:', err);
            setError('Network error. Please try again.');
            toast.error('Network error. Please try again.');
        } finally {
            setIsLoading(false);
        }
    };

    const handleVerifyOtp = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!otp || otp.length < 6) {
            setError('Please enter a valid 6-digit OTP');
            return;
        }

        setIsLoading(true);
        setError('');

        try {
            const response = await API.verifyOtp(phone, otp) as any;
            if (response.ok && response.data) {
                // Fix: Extract from nested data object
                const { token, user } = response.data.data || response.data;

                if (!token || !user) {
                    throw new Error('Invalid response format');
                }

                // Dispatch login action
                dispatch(setCredentials({ user, token }));

                // Store token in localStorage
                localStorage.setItem('token', token);

                toast.success('Logged in successfully!');
                navigate('/prospective-dashboard');
            } else {
                const errorMessage = response.data?.message || 'Invalid OTP';
                setError(errorMessage);
                toast.error(errorMessage);
            }
        } catch (err: any) {
            console.error('Verify OTP error:', err);
            setError('An unexpected error occurred');
            toast.error('An unexpected error occurred');
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 p-4 overflow-y-auto">
            <div className="absolute inset-0 overflow-hidden pointer-events-none">
                <div className="absolute -top-40 -right-40 w-80 h-80 bg-amber-600/10 rounded-full blur-3xl"></div>
                <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-amber-600/10 rounded-full blur-3xl"></div>
            </div>

            <div className="relative w-full max-w-md">
                <div className="text-center mb-8">
                    <div className="inline-flex items-center justify-center w-20 h-20 bg-amber-600 rounded-full mb-4">
                        <svg viewBox="0 0 24 24" className="w-12 h-12 text-white" fill="currentColor">
                            <path d="M12 2L4 6v6c0 5.5 3.8 10.7 8 12 4.2-1.3 8-6.5 8-12V6l-8-4zm0 2.2l6 3v4.8c0 4.5-3.1 8.7-6 10-2.9-1.3-6-5.5-6-10V7.2l6-3z"></path>
                            <circle cx="12" cy="12" r="3"></circle>
                        </svg>
                    </div>
                    <h1 className="text-white mb-2">Royal Enfield</h1>
                    <p className="text-slate-400">Dealer Login</p>
                </div>

                <div className="bg-white rounded-lg shadow-2xl p-8">
                    <div className="mb-6">
                        <Button
                            variant="ghost"
                            className="px-0 flex items-center gap-2 text-slate-600 hover:text-slate-900 mb-4 hover:bg-transparent"
                            onClick={() => step === 'OTP' ? setStep('PHONE') : navigate('/admin-login')}
                        >
                            <ArrowLeft className="w-4 h-4" />
                            {step === 'OTP' ? 'Change Phone Number' : 'Back to Login'}
                        </Button>

                        <div className="flex items-center gap-3 mb-2">
                            <div className="p-2 bg-amber-100 rounded-lg">
                                <Smartphone className="w-6 h-6 text-amber-600" />
                            </div>
                            <div>
                                <h2 className="text-slate-900 text-lg font-semibold">Dealer Login</h2>
                                <p className="text-slate-600 text-sm">Login with your registered phone number</p>
                            </div>
                        </div>
                    </div>

                    {step === 'PHONE' ? (
                        <form onSubmit={handleSendOtp} className="space-y-6">
                            <div className="space-y-2">
                                <Label htmlFor="phone">Registered Phone Number</Label>
                                <Input
                                    id="phone"
                                    type="tel"
                                    placeholder="Enter 10-digit phone number"
                                    maxLength={10}
                                    value={phone}
                                    onChange={(e) => setPhone(e.target.value.replace(/\D/g, ''))}
                                    className="w-full"
                                    disabled={isLoading}
                                />
                                <p className="text-slate-500 text-xs">Enter the phone number you used during application</p>
                            </div>

                            {error && (
                                <div className="flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-md">
                                    <AlertCircle className="w-4 h-4 text-red-600" />
                                    <span className="text-red-600 font-medium text-sm">{error}</span>
                                </div>
                            )}

                            <Button
                                type="submit"
                                className="w-full bg-amber-600 hover:bg-amber-700 h-9"
                                disabled={isLoading || phone.length < 10}
                            >
                                {isLoading ? 'Sending...' : 'Send OTP'}
                            </Button>

                            <div className="text-center text-slate-500 text-xs">
                                <p>You will receive a 6-digit OTP on your registered mobile number</p>
                            </div>
                        </form>
                    ) : (
                        <form onSubmit={handleVerifyOtp} className="space-y-6">
                            <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
                                <p className="text-green-800 text-center text-sm">OTP sent to +91 {phone}</p>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="otp">Enter OTP</Label>
                                <Input
                                    id="otp"
                                    type="text"
                                    placeholder="Enter 6-digit OTP"
                                    maxLength={6}
                                    value={otp}
                                    onChange={(e) => setOtp(e.target.value.replace(/\D/g, ''))}
                                    className="w-full text-center text-2xl tracking-widest"
                                    disabled={isLoading}
                                />
                                <p className="text-slate-500 text-xs text-center">Check your SMS for the OTP</p>
                            </div>

                            {error && (
                                <div className="flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-md">
                                    <AlertCircle className="w-4 h-4 text-red-600" />
                                    <span className="text-red-600 font-medium text-sm">{error}</span>
                                </div>
                            )}

                            <Button
                                type="submit"
                                className="w-full bg-amber-600 hover:bg-amber-700 h-9"
                                disabled={isLoading || otp.length < 6}
                            >
                                {isLoading ? 'Verifying...' : 'Verify OTP'}
                            </Button>

                            <div className="text-center text-sm">
                                <button
                                    type="button"
                                    className="text-amber-600 hover:text-amber-700 font-medium"
                                    onClick={() => setStep('PHONE')}
                                >
                                    Change Phone Number
                                </button>
                                <span className="mx-2 text-slate-400">|</span>
                                <button
                                    type="button"
                                    className="text-amber-600 hover:text-amber-700 font-medium"
                                    onClick={handleSendOtp}
                                    disabled={isLoading}
                                >
                                    Resend OTP
                                </button>
                            </div>
                        </form>
                    )}
                </div>

                <div className="text-center mt-6 text-slate-400">
                    <p>© 2025 Royal Enfield. All rights reserved.</p>
                </div>
            </div>
        </div>
    );
}
