import React, { useState, useEffect } from 'react';

const PasswordField = ({ value, onChange, required = false, label = 'Password', onValidityChange }) => {
    const [showPassword, setShowPassword] = useState(false);
    const [strength, setStrength] = useState({ score: 0, text: '', color: '' });
    const [confirmWeak, setConfirmWeak] = useState(false);

    useEffect(() => {
        if (value) {
            const result = calculatePasswordStrength(value);
            setStrength(result);
            
            // Reset confirm weak if password becomes strong
            if (result.score >= 3) {
                setConfirmWeak(false);
            }
        } else {
            setStrength({ score: 0, text: '', color: '' });
            setConfirmWeak(false);
        }
    }, [value]);

    // Notify parent of validity changes
    useEffect(() => {
        if (onValidityChange) {
            const isWeak = value && strength.score < 3;
            const isValid = !value || !isWeak || confirmWeak;
            onValidityChange(isValid);
        }
    }, [value, strength.score, confirmWeak, onValidityChange]);

    const calculatePasswordStrength = (password) => {
        let score = 0;
        
        if (!password) return { score: 0, text: '', color: '' };
        
        // Length check
        if (password.length >= 8) score++;
        if (password.length >= 12) score++;
        
        // Character variety
        if (/[a-z]/.test(password)) score++;
        if (/[A-Z]/.test(password)) score++;
        if (/[0-9]/.test(password)) score++;
        if (/[^a-zA-Z0-9]/.test(password)) score++;
        
        // Determine strength
        if (score <= 2) {
            return { score: 1, text: 'Weak', color: '#e53e3e' };
        } else if (score <= 4) {
            return { score: 2, text: 'Fair', color: '#d69e2e' };
        } else if (score <= 5) {
            return { score: 3, text: 'Good', color: '#38a169' };
        } else {
            return { score: 4, text: 'Strong', color: '#2f855a' };
        }
    };

    const generatePassword = () => {
        const length = 16;
        const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{}|;:,.<>?';
        let password = '';
        
        // Ensure at least one of each type
        password += 'abcdefghijklmnopqrstuvwxyz'[Math.floor(Math.random() * 26)];
        password += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[Math.floor(Math.random() * 26)];
        password += '0123456789'[Math.floor(Math.random() * 10)];
        password += '!@#$%^&*()_+-='[Math.floor(Math.random() * 14)];
        
        // Fill the rest
        for (let i = password.length; i < length; i++) {
            password += charset[Math.floor(Math.random() * charset.length)];
        }
        
        // Shuffle
        password = password.split('').sort(() => Math.random() - 0.5).join('');
        
        onChange(password);
        setShowPassword(true);
    };

    const isWeak = strength.score < 3;
    const canSubmit = !value || !isWeak || confirmWeak;

    return (
        <div className="password-field-wrapper">
            <label>{label} {required && '*'}</label>
            <div className="password-input-group">
                <input
                    type={showPassword ? 'text' : 'password'}
                    value={value}
                    onChange={(e) => onChange(e.target.value)}
                    required={required}
                    className="password-input"
                />
                <button
                    type="button"
                    className="password-toggle"
                    onClick={() => setShowPassword(!showPassword)}
                    title={showPassword ? 'Hide password' : 'Show password'}
                >
                    {showPassword ? '👁️' : '👁️‍🗨️'}
                </button>
                <button
                    type="button"
                    className="password-generate"
                    onClick={generatePassword}
                    title="Generate strong password"
                >
                    🔑 Generate
                </button>
            </div>

            {value && (
                <>
                    <div className="password-strength">
                        <div className="strength-bar">
                            <div 
                                className="strength-fill"
                                style={{ 
                                    width: `${(strength.score / 4) * 100}%`,
                                    backgroundColor: strength.color
                                }}
                            />
                        </div>
                        <span className="strength-text" style={{ color: strength.color }}>
                            {strength.text}
                        </span>
                    </div>

                    {isWeak && (
                        <div className="password-warning">
                            <label className="weak-confirm">
                                <input
                                    type="checkbox"
                                    checked={confirmWeak}
                                    onChange={(e) => setConfirmWeak(e.target.checked)}
                                />
                                <span>Confirm use of weak password</span>
                            </label>
                        </div>
                    )}
                </>
            )}

            <style jsx>{`
                .password-field-wrapper {
                    margin-bottom: 16px;
                }

                .password-field-wrapper label {
                    display: block;
                    font-weight: 500;
                    color: #333;
                    margin-bottom: 8px;
                    font-size: 14px;
                }

                .password-input-group {
                    display: flex;
                    gap: 8px;
                }

                .password-input {
                    flex: 1;
                    padding: 10px 14px;
                    border: 1px solid #e0e0e0;
                    border-radius: 8px;
                    font-size: 14px;
                    transition: border-color 0.2s;
                }

                .password-input:focus {
                    outline: none;
                    border-color: #1976d2;
                    box-shadow: 0 0 0 3px rgba(25, 118, 210, 0.1);
                }

                .password-toggle,
                .password-generate {
                    padding: 10px 14px;
                    border: 1px solid #e0e0e0;
                    border-radius: 8px;
                    background: white;
                    cursor: pointer;
                    font-size: 14px;
                    transition: all 0.2s;
                }

                .password-toggle:hover,
                .password-generate:hover {
                    background: #f5f5f5;
                    border-color: #1976d2;
                }

                .password-strength {
                    margin-top: 8px;
                    display: flex;
                    align-items: center;
                    gap: 12px;
                }

                .strength-bar {
                    flex: 1;
                    height: 6px;
                    background: #e0e0e0;
                    border-radius: 3px;
                    overflow: hidden;
                }

                .strength-fill {
                    height: 100%;
                    transition: width 0.3s, background-color 0.3s;
                }

                .strength-text {
                    font-size: 13px;
                    font-weight: 600;
                    min-width: 60px;
                }

                .password-warning {
                    margin-top: 8px;
                    padding: 12px;
                    background: #fff3cd;
                    border: 1px solid #ffc107;
                    border-radius: 6px;
                }

                .weak-confirm {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    cursor: pointer;
                    font-size: 13px;
                    color: #856404;
                }

                .weak-confirm input[type="checkbox"] {
                    width: auto;
                    margin: 0;
                }
            `}</style>
        </div>
    );
};

export default PasswordField;
