import { useState, useRef, useEffect, type CSSProperties, type FormEvent } from 'react';
import { ApiError, setHeroName } from '../network/api';
import type { HeroResponse } from '../network/api';
import { getTelegramUserId } from '../shared/telegram';
import { useT, t } from '../i18n';

const MIN_LEN = 2;
const MAX_LEN = 16;

interface NameEntryScreenProps {
  onNameSet: (hero: HeroResponse) => void;
}

const overlayStyle: CSSProperties = {
  position: 'absolute',
  inset: 0,
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  backgroundColor: 'rgba(0, 0, 0, 0.82)',
  zIndex: 100,
  fontFamily: 'system-ui, sans-serif',
};

const cardStyle: CSSProperties = {
  width: '90%',
  maxWidth: 340,
  padding: '28px 24px',
  borderRadius: 14,
  backgroundColor: 'rgba(18, 18, 32, 0.96)',
  border: '1px solid rgba(180, 140, 255, 0.25)',
  boxShadow: '0 0 40px rgba(120, 80, 220, 0.15), 0 8px 32px rgba(0,0,0,0.5)',
  display: 'flex',
  flexDirection: 'column' as const,
  alignItems: 'center',
  gap: 16,
};

const titleStyle: CSSProperties = {
  fontSize: 20,
  fontWeight: 800,
  color: '#e8dff8',
  textAlign: 'center',
  letterSpacing: 0.5,
  textShadow: '0 0 12px rgba(180, 140, 255, 0.3)',
};

const inputStyle: CSSProperties = {
  width: '100%',
  padding: '12px 14px',
  fontSize: 16,
  fontWeight: 600,
  color: '#eee',
  backgroundColor: 'rgba(255, 255, 255, 0.07)',
  border: '2px solid rgba(180, 140, 255, 0.3)',
  borderRadius: 8,
  outline: 'none',
  fontFamily: 'inherit',
  boxSizing: 'border-box',
  transition: 'border-color 200ms ease',
};

const inputFocusedBorder = 'rgba(180, 140, 255, 0.6)';

const counterStyle: CSSProperties = {
  fontSize: 11,
  color: '#888',
  alignSelf: 'flex-end',
  marginTop: -10,
};

const buttonStyle: CSSProperties = {
  width: '100%',
  padding: '13px 0',
  fontSize: 16,
  fontWeight: 700,
  color: '#fff',
  backgroundColor: '#6a40c8',
  border: 'none',
  borderRadius: 8,
  cursor: 'pointer',
  transition: 'background-color 150ms ease, opacity 150ms ease',
};

const errorStyle: CSSProperties = {
  fontSize: 12,
  fontWeight: 600,
  color: '#ff5555',
  textAlign: 'center',
  minHeight: 16,
};

export function NameEntryScreen({ onNameSet }: NameEntryScreenProps) {
  const tr = useT();
  const [name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [focused, setFocused] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    // Auto-focus on mount with a small delay for mobile keyboards
    const t = setTimeout(() => inputRef.current?.focus(), 300);
    return () => clearTimeout(t);
  }, []);

  const trimmed = name.trim();
  const isValid = trimmed.length >= MIN_LEN && trimmed.length <= MAX_LEN;

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    if (!isValid || loading) return;

    setLoading(true);
    setError(null);

    try {
      const telegramId = getTelegramUserId();
      const hero = await setHeroName(trimmed, telegramId ?? undefined);
      onNameSet(hero);
    } catch (err) {
      if (err instanceof ApiError) {
        if (err.status === 409) {
          setError(tr.nameTaken);
        } else if (err.status === 400) {
          try {
            const j = JSON.parse(err.body) as { error?: string };
            setError(j.error ?? tr.invalidName);
          } catch {
            setError(tr.invalidName);
          }
        } else {
          setError(t(tr.serverError, { status: err.status }));
        }
      } else {
        setError(tr.connectionFailed);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={overlayStyle}>
      <form style={cardStyle} onSubmit={handleSubmit}>
        <div style={titleStyle}>{tr.chooseHeroName}</div>

        <input
          ref={inputRef}
          type="text"
          value={name}
          onChange={(e) => {
            const v = e.target.value;
            if (v.length <= MAX_LEN) {
              setName(v);
              setError(null);
            }
          }}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          placeholder={tr.enterName}
          maxLength={MAX_LEN}
          autoComplete="off"
          autoCorrect="off"
          spellCheck={false}
          style={{
            ...inputStyle,
            borderColor: focused ? inputFocusedBorder : inputStyle.borderColor,
          }}
        />

        <div style={counterStyle}>
          {trimmed.length}/{MAX_LEN}
        </div>

        <div style={errorStyle}>{error ?? '\u00A0'}</div>

        <button
          type="submit"
          disabled={!isValid || loading}
          style={{
            ...buttonStyle,
            opacity: isValid && !loading ? 1 : 0.4,
            cursor: isValid && !loading ? 'pointer' : 'not-allowed',
          }}
        >
          {loading ? tr.saving : tr.continue}
        </button>
      </form>
    </div>
  );
}
