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

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

interface ServerApiResponse {
  id: string;
  name: string;
  icon: string | null;
  owner_id: string;
}

export function CreateServerModal({ onClose }: CreateServerModalProps) {
  const [name, setName] = useState('');
  const [icon, setIcon] = 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 createServer = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;

    setLoading(true);
    setError(null);
    try {
      const result = await api.post<ServerApiResponse>('/servers', {
        name: name.trim(),
        icon: icon.trim() || undefined,
      });
      const newServer = {
        id: result.id,
        name: result.name,
        icon: result.icon,
        ownerId: result.owner_id,
      };
      useServerStore.getState().addServer(newServer);
      useServerStore.getState().setActiveServer(newServer.id);
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create 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">CREATE SERVER</span>
          <button onClick={onClose} className="text-xs text-gb-red">[x]</button>
        </div>

        <form onSubmit={createServer} className="space-y-3">
          <div>
            <label className="text-xs text-gb-fg-f block mb-1">NAME:</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="server name"
              required
              className="terminal-input w-full"
            />
          </div>
          <div>
            <label className="text-xs text-gb-fg-f block mb-1">ICON URL:</label>
            <input
              type="text"
              value={icon}
              onChange={(e) => setIcon(e.target.value)}
              placeholder="https://..."
              className="terminal-input w-full"
            />
          </div>
          {error && <div className="text-xs text-gb-red">{error}</div>}
          <button
            type="submit"
            disabled={loading || !name.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 ? 'CREATING...' : '[CREATE SERVER]'}
          </button>
        </form>
      </div>
    </div>
  );
}
