import { useState, useEffect } from 'react';
import { api } from '../lib/api.ts';
import { useServerStore } from '../stores/server.ts';

interface JoinServerModalProps {
  onClose: () => void;
}

interface JoinServerApiResponse {
  server_id: string;
  message: string;
}

export function JoinServerModal({ onClose }: JoinServerModalProps) {
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        onClose();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [onClose]);

  const joinServer = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!code.trim()) return;

    setLoading(true);
    setError(null);
    try {
      const result = await api.post<JoinServerApiResponse>(`/invites/${code.trim()}/join`);
      await useServerStore.getState().fetchServers();
      useServerStore.getState().setActiveServer(result.server_id);
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to join server');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
      onClick={onClose}
    >
      <div
        className="bg-gb-bg border border-gb-bg-t p-4 min-w-[350px] font-mono"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between mb-3">
          <span className="text-sm text-gb-orange">JOIN SERVER</span>
          <button onClick={onClose} className="text-xs text-gb-red">[x]</button>
        </div>

        <form onSubmit={joinServer} className="space-y-3">
          <div>
            <label className="text-xs text-gb-fg-f block mb-1">INVITE CODE:</label>
            <input
              type="text"
              value={code}
              onChange={(e) => setCode(e.target.value)}
              placeholder="enter invite code"
              required
              className="terminal-input w-full"
            />
          </div>
          {error && <div className="text-xs text-gb-red">{error}</div>}
          <button
            type="submit"
            disabled={loading || !code.trim()}
            className="w-full px-3 py-1.5 bg-gb-orange text-gb-bg text-xs font-mono hover:bg-gb-yellow transition-colors disabled:opacity-50"
          >
            {loading ? 'JOINING...' : '[JOIN SERVER]'}
          </button>
        </form>
      </div>
    </div>
  );
}
