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

export default function ResetPassword() {
    const searchParams = new URLSearchParams(window.location.search);
    const key = searchParams.get('key') || '';
    const login = searchParams.get('login') || '';

    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [isValidating, setIsValidating] = useState(true);
    const [isValid, setIsValid] = useState(false);
    const [error, setError] = useState('');
    const [isSuccess, setIsSuccess] = useState(false);

    // Validate the reset key on mount
    useEffect(() => {
        const validateKey = async () => {
            if (!key || !login) {
                setError('Invalid password reset link. Please request a new one.');
                setIsValidating(false);
                return;
            }

            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/validate-reset-key`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': nonce,
                    },
                    credentials: 'include',
                    body: JSON.stringify({ key, login }),
                });

                const data = await response.json();

                if (response.ok && data.valid) {
                    setIsValid(true);
                } else {
                    setError(data.message || 'This password reset link has expired or is invalid.');
                }
            } catch {
                setError('Unable to validate reset link. Please try again later.');
            } finally {
                setIsValidating(false);
            }
        };

        validateKey();

    }, [login]);

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

        if (password !== confirmPassword) {
            setError('Passwords do not match');
            return;
        }

        if (password.length < 8) {
            setError('Password must be at least 8 characters long');
            return;
        }

        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/reset-password`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce,
                },
                credentials: 'include',
                body: JSON.stringify({ key, login, password }),
            });

            const data = await response.json();

            if (response.ok && data.success) {
                setIsSuccess(true);
                toast.success('Password reset successfully!');
            } else {
                setError(data.message || 'Failed to reset password. Please try again.');
            }
        } catch (err: any) {
            setError(err.message || 'An error occurred. Please try again later.');
        } finally {
            setIsLoading(false);
        }
    };

    // Password strength indicator
    const getPasswordStrength = (pwd: string) => {
        if (pwd.length === 0) return { label: '', color: '', width: '0%' };
        if (pwd.length < 8) return { label: 'Too short', color: 'bg-red-500', width: '25%' };

        let strength = 0;
        if (pwd.length >= 8) strength++;
        if (pwd.length >= 12) strength++;
        if (/[a-z]/.test(pwd) && /[A-Z]/.test(pwd)) strength++;
        if (/\d/.test(pwd)) strength++;
        if (/[!@#$%^&*(),.?":{}|<>]/.test(pwd)) strength++;

        if (strength <= 2) return { label: 'Weak', color: 'bg-orange-500', width: '50%' };
        if (strength <= 3) return { label: 'Medium', color: 'bg-yellow-500', width: '75%' };
        return { label: 'Strong', color: 'bg-green-500', width: '100%' };
    };

    const passwordStrength = getPasswordStrength(password);

    // Loading state
    if (isValidating) {
        return (
            <Container>
                <div className="min-h-[60vh] flex items-center justify-center py-12">
                    <div className="w-full max-w-md">
                        <div className="bg-white rounded-2xl shadow-xl p-8 border text-center">
                            <Loader2 className="w-8 h-8 animate-spin text-primary mx-auto mb-4" />
                            <p className="text-gray-600">Validating reset link...</p>
                        </div>
                    </div>
                </div>
            </Container>
        );
    }

    // Success state
    if (isSuccess) {
        return (
            <Container>
                <div className="min-h-[60vh] flex items-center justify-center py-12">
                    <div className="w-full max-w-md">
                        <div className="bg-white rounded-2xl shadow-xl p-8 border text-center">
                            <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <CheckCircle className="w-8 h-8 text-green-600" />
                            </div>
                            <h1 className="text-2xl font-bold text-gray-900 mb-2">Password Reset!</h1>
                            <p className="text-gray-600 mb-6">
                                Your password has been successfully updated. You can now log in with your new password.
                            </p>
                            <Link to="/login">
                                <Button className="w-full">Sign In</Button>
                            </Link>
                        </div>
                    </div>
                </div>
            </Container>
        );
    }

    // Error state (invalid key)
    if (!isValid && error) {
        return (
            <Container>
                <div className="min-h-[60vh] flex items-center justify-center py-12">
                    <div className="w-full max-w-md">
                        <div className="bg-white rounded-2xl shadow-xl p-8 border text-center">
                            <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <AlertCircle className="w-8 h-8 text-red-600" />
                            </div>
                            <h1 className="text-2xl font-bold text-gray-900 mb-2">Invalid Reset Link</h1>
                            <p className="text-gray-600 mb-6">{error}</p>
                            <Link to="/forgot-password">
                                <Button className="w-full">Request New Link</Button>
                            </Link>
                        </div>
                    </div>
                </div>
            </Container>
        );
    }

    // Reset form
    return (
        <Container>
            <div className="min-h-[60vh] flex items-center justify-center py-12">
                <div className="w-full max-w-md">
                    {/* Back link */}
                    <Link
                        to="/login"
                        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" />
                        Back to login
                    </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">
                                <KeyRound className="w-8 h-8 text-primary" />
                            </div>
                            <h1 className="text-2xl font-bold text-gray-900">Reset Your Password</h1>
                            <p className="text-gray-600 mt-2">
                                Enter your new password below.
                            </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="password">New Password</Label>
                                <div className="relative">
                                    <Input
                                        id="password"
                                        type={showPassword ? 'text' : 'password'}
                                        value={password}
                                        onChange={(e) => setPassword(e.target.value)}
                                        placeholder="Enter new password"
                                        required
                                        disabled={isLoading}
                                        className="pr-10"
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPassword(!showPassword)}
                                        className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                                    >
                                        {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                                    </button>
                                </div>
                                {password && (
                                    <div className="space-y-1">
                                        <div className="h-1 bg-gray-200 rounded-full overflow-hidden">
                                            <div
                                                className={`h-full transition-all ${passwordStrength.color}`}
                                                style={{ width: passwordStrength.width }}
                                            />
                                        </div>
                                        <p className="text-xs text-gray-500">
                                            Strength: <span className="font-medium">{passwordStrength.label}</span>
                                        </p>
                                    </div>
                                )}
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="confirmPassword">Confirm Password</Label>
                                <Input
                                    id="confirmPassword"
                                    type={showPassword ? 'text' : 'password'}
                                    value={confirmPassword}
                                    onChange={(e) => setConfirmPassword(e.target.value)}
                                    placeholder="Confirm new password"
                                    required
                                    disabled={isLoading}
                                />
                                {confirmPassword && password !== confirmPassword && (
                                    <p className="text-xs text-red-500">Passwords do not match</p>
                                )}
                            </div>

                            <Button
                                type="submit"
                                className="w-full"
                                disabled={isLoading || password !== confirmPassword}
                            >
                                {isLoading ? 'Resetting...' : 'Reset Password'}
                            </Button>
                        </form>

                        {/* Footer */}
                        <div className="mt-6 text-center text-sm text-gray-600">
                            Remember your password?{' '}
                            <Link to="/login" className="text-primary hover:underline">
                                Sign in
                            </Link>
                        </div>
                    </div>
                </div>
            </div>
        </Container>
    );
}
