import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';
import { useMutation } from 'convex/react';
import { api } from '../../../../convex/_generated/api';

const ChangeNicknameModal = ({ targetUserId, targetUsername, currentNickname, actorUserId, onClose }) => {
    const [nickname, setNickname] = useState(currentNickname || '');
    const inputRef = useRef(null);
    const setNicknameMutation = useMutation(api.auth.setNickname);
    const isSelf = targetUserId === actorUserId;

    useEffect(() => {
        inputRef.current?.focus();
        inputRef.current?.select();
    }, []);

    const handleSave = async () => {
        try {
            await setNicknameMutation({
                actorUserId,
                targetUserId,
                displayName: nickname,
            });
            onClose();
        } catch (err) {
            console.error('Failed to set nickname:', err);
        }
    };

    const handleReset = async () => {
        try {
            await setNicknameMutation({
                actorUserId,
                targetUserId,
                displayName: '',
            });
            onClose();
        } catch (err) {
            console.error('Failed to reset nickname:', err);
        }
    };

    const handleKeyDown = (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            handleSave();
        } else if (e.key === 'Escape') {
            onClose();
        }
    };

    return ReactDOM.createPortal(
        <div
            onClick={onClose}
            style={{
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: 'rgba(0, 0, 0, 0.85)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: 10001,
            }}
        >
            <div
                onClick={(e) => e.stopPropagation()}
                style={{
                    width: '440px',
                    maxWidth: '90vw',
                    backgroundColor: 'var(--bg-primary)',
                    borderRadius: '8px',
                    boxShadow: '0 4px 20px rgba(0, 0, 0, 0.4)',
                    overflow: 'hidden',
                }}
            >
                {/* Header */}
                <div style={{ padding: '16px 16px 0 16px', position: 'relative' }}>
                    <h2 style={{ color: 'var(--header-primary)', margin: '0 0 16px 0', fontSize: '20px', fontWeight: 600 }}>
                        Change Nickname
                    </h2>
                    <button
                        onClick={onClose}
                        style={{
                            position: 'absolute',
                            top: '12px',
                            right: '12px',
                            background: 'none',
                            border: 'none',
                            color: 'var(--interactive-normal)',
                            cursor: 'pointer',
                            padding: '4px',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            borderRadius: '50%',
                        }}
                    >
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M18.4 4L12 10.4L5.6 4L4 5.6L10.4 12L4 18.4L5.6 20L12 13.6L18.4 20L20 18.4L13.6 12L20 5.6L18.4 4Z" />
                        </svg>
                    </button>
                </div>

                {/* Content */}
                <div style={{ padding: '0 16px 16px 16px' }}>
                    {/* Notice */}
                    {!isSelf && (
                        <div style={{
                            backgroundColor: 'var(--bg-tertiary)',
                            borderLeft: '4px solid var(--text-warning, #faa61a)',
                            borderRadius: '4px',
                            padding: '12px',
                            marginBottom: '16px',
                            fontSize: '14px',
                            color: 'var(--text-normal)',
                            lineHeight: '1.4',
                        }}>
                            Nicknames are visible to everyone on this server. Do not change them unless you are enforcing a naming system or clearing a bad nickname.
                        </div>
                    )}

                    {/* Label */}
                    <label style={{
                        color: 'var(--header-secondary)',
                        fontSize: '12px',
                        fontWeight: 700,
                        textTransform: 'uppercase',
                        marginBottom: '8px',
                        display: 'block',
                    }}>
                        Nickname
                    </label>

                    {/* Input */}
                    <input
                        ref={inputRef}
                        type="text"
                        value={nickname}
                        onChange={(e) => setNickname(e.target.value.slice(0, 32))}
                        onKeyDown={handleKeyDown}
                        placeholder={targetUsername}
                        maxLength={32}
                        style={{
                            width: '100%',
                            padding: '10px',
                            backgroundColor: 'var(--bg-tertiary)',
                            border: '1px solid var(--border-subtle)',
                            borderRadius: '4px',
                            color: 'var(--text-normal)',
                            fontSize: '14px',
                            outline: 'none',
                            boxSizing: 'border-box',
                        }}
                    />

                    {/* Reset link */}
                    <div
                        onClick={handleReset}
                        style={{
                            color: 'var(--text-link, #00a8fc)',
                            fontSize: '14px',
                            cursor: 'pointer',
                            marginTop: '8px',
                            marginBottom: '4px',
                            userSelect: 'none',
                        }}
                    >
                        Reset Nickname
                    </div>
                </div>

                {/* Footer */}
                <div style={{
                    display: 'flex',
                    gap: '12px',
                    padding: '16px',
                    backgroundColor: 'var(--bg-secondary)',
                    borderTop: '1px solid var(--border-subtle)',
                }}>
                    <button
                        onClick={onClose}
                        style={{
                            flex: 1,
                            padding: '10px 0',
                            backgroundColor: 'var(--bg-tertiary)',
                            color: 'var(--text-normal)',
                            border: 'none',
                            borderRadius: '3px',
                            cursor: 'pointer',
                            fontSize: '14px',
                            fontWeight: 500,
                        }}
                    >
                        Cancel
                    </button>
                    <button
                        onClick={handleSave}
                        style={{
                            flex: 1,
                            padding: '10px 0',
                            backgroundColor: 'var(--brand-experiment)',
                            color: '#fff',
                            border: 'none',
                            borderRadius: '3px',
                            cursor: 'pointer',
                            fontSize: '14px',
                            fontWeight: 500,
                        }}
                    >
                        Save
                    </button>
                </div>
            </div>
        </div>,
        document.body
    );
};

export default ChangeNicknameModal;
