import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams, Link } from 'react-router-dom';
import { toast } from 'sonner';
import Container from '@/components/Layout/Container';
import SEOHead from '@/components/SEOHead';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { LogIn, Eye, EyeOff, ArrowLeft } from 'lucide-react';

export default function Login() {
    const navigate = useNavigate();
    const [searchParams] = useSearchParams();
    const redirectTo = searchParams.get('redirect') || '/my-account';

    // Redirect logged-in users to account page
    useEffect(() => {
        const user = (window as any).woonoowCustomer?.user;
        if (user?.isLoggedIn) {
            navigate(redirectTo, { replace: true });
        }
    }, [navigate, redirectTo]);

    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setError('');
        setIsLoading(true);

        try {
            const apiRoot = (window as any).woonoowCustomer?.apiRoot || '/wp-json/woonoow/v1';
            const nonce = (window as any).woonoowCustomer?.nonce || '';

            const response = await fetch(`${apiRoot}/auth/customer-login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce,
                },
                credentials: 'include',
                body: JSON.stringify({ username, password }),
            });

            const data = await response.json();

            if (data.success) {
                // Update window config with new nonce and user data
                if ((window as any).woonoowCustomer) {
                    (window as any).woonoowCustomer.nonce = data.nonce;
                    (window as any).woonoowCustomer.user = {
                        isLoggedIn: true,
                        id: data.user.id,
                        name: data.user.name,
                        email: data.user.email,
                        firstName: data.user.first_name,
                        lastName: data.user.last_name,
                        avatar: data.user.avatar,
                    };
                }

                // Merge guest wishlist to account
                const GUEST_WISHLIST_KEY = 'woonoow_guest_wishlist';
                try {
                    const stored = localStorage.getItem(GUEST_WISHLIST_KEY);
                    if (stored) {
                        const guestProductIds = JSON.parse(stored) as number[];
                        if (guestProductIds.length > 0) {
                            // Merge each product to account wishlist
                            const newNonce = data.nonce;
                            for (const productId of guestProductIds) {
                                try {
                                    await fetch(`${apiRoot}/account/wishlist`, {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/json',
                                            'X-WP-Nonce': newNonce,
                                        },
                                        credentials: 'include',
                                        body: JSON.stringify({ product_id: productId }),
                                    });
                                } catch {
                                    // Skip if product already in wishlist or other error
                                    console.debug('Wishlist merge skipped for product:', productId);
                                }
                            }
                            // Clear guest wishlist after merge
                            localStorage.removeItem(GUEST_WISHLIST_KEY);
                        }
                    }
                } catch (e) {
                    console.error('Failed to merge guest wishlist:', e);
                }

                toast.success('Login successful!');

                // Set the target URL with hash route, then force reload
                // The hash change alone doesn't reload the page, so cookies won't be refreshed
                const basePath = (window as any).woonoowCustomer?.basePath || '/store';
                const targetUrl = window.location.origin + basePath + '/#' + redirectTo;
                window.location.href = targetUrl;
                // Force page reload to refresh cookies and server-side state
                window.location.reload();
            } else {
                setError(data.message || 'Login failed');
            }
        } catch (err: any) {
            setError(err.message || 'An error occurred. Please try again.');
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <Container>
            <SEOHead title="Login" description="Sign in to your account" />
            <div className="min-h-[60vh] flex items-center justify-center py-12">
                <div className="w-full max-w-md">
                    {/* Back link */}
                    <Link
                        to="/shop"
                        className="inline-flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-6 no-underline"
                    >
                        <ArrowLeft className="w-4 h-4" />
                        Continue shopping
                    </Link>

                    <div className="bg-white rounded-2xl shadow-xl p-8 border">
                        {/* Header */}
                        <div className="text-center mb-8">
                            <div className="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
                                <LogIn className="w-8 h-8 text-primary" />
                            </div>
                            <h1 className="text-2xl font-bold text-gray-900">Welcome Back</h1>
                            <p className="text-gray-600 mt-2">Sign in to your account</p>
                        </div>

                        {/* Error message */}
                        {error && (
                            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6">
                                {error}
                            </div>
                        )}

                        {/* Form */}
                        <form onSubmit={handleSubmit} className="space-y-6">
                            <div className="space-y-2">
                                <Label htmlFor="username">Email or Username</Label>
                                <Input
                                    id="username"
                                    type="text"
                                    value={username}
                                    onChange={(e) => setUsername(e.target.value)}
                                    placeholder="Enter your email or username"
                                    required
                                    autoComplete="username"
                                    disabled={isLoading}
                                />
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="password">Password</Label>
                                <div className="relative">
                                    <Input
                                        id="password"
                                        type={showPassword ? 'text' : 'password'}
                                        value={password}
                                        onChange={(e) => setPassword(e.target.value)}
                                        placeholder="Enter your password"
                                        required
                                        autoComplete="current-password"
                                        disabled={isLoading}
                                        className="pr-10"
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPassword(!showPassword)}
                                        className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                                        tabIndex={-1}
                                    >
                                        {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                                    </button>
                                </div>
                            </div>

                            <Button
                                type="submit"
                                className="w-full"
                                disabled={isLoading}
                            >
                                {isLoading ? 'Signing in...' : 'Sign In'}
                            </Button>
                        </form>

                        {/* Footer links */}
                        <div className="mt-6 text-center text-sm text-gray-600">
                            <Link
                                to="/forgot-password"
                                className="hover:text-primary"
                            >
                                Forgot your password?
                            </Link>
                        </div>
                    </div>
                </div>
            </div>
        </Container>
    );
}
