import React, { useState } from 'react';

interface LoginProps {
  defaultUrl: string;
  onLogin: (url: string, token: string) => void;
}

export function Login({ defaultUrl, onLogin }: LoginProps): React.ReactElement {
  const [url, setUrl] = useState(defaultUrl);
  const [token, setToken] = useState('');
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent): Promise<void> {
    e.preventDefault();
    setError(null);
    if (!url.trim() || !token.trim()) {
      setError('Both fields are required');
      return;
    }
    try {
      const res = await fetch(`${url.replace(/\/$/, '')}/api/state`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) {
        setError(`Auth failed: HTTP ${res.status}`);
        return;
      }
      onLogin(url.trim(), token.trim());
    } catch (err) {
      setError((err as Error).message);
    }
  }

  return (
    <div
      style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 24,
      }}
    >
      <form
        onSubmit={handleSubmit}
        style={{
          background: '#161616',
          border: '1px solid #262626',
          borderRadius: 8,
          padding: 32,
          width: '100%',
          maxWidth: 420,
          display: 'flex',
          flexDirection: 'column',
          gap: 16,
        }}
      >
        <div>
          <h1 style={{ margin: 0, color: '#f7c948', fontSize: 22 }}>Shade Observer</h1>
          <p style={{ margin: '4px 0 0', color: '#a3a3a3', fontSize: 13 }}>
            Connect to your observer endpoint
          </p>
        </div>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span style={{ fontSize: 11, color: '#a3a3a3', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
            Observer URL
          </span>
          <input
            type="text"
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            placeholder="https://shade.example.com/shade-observer"
            style={inputStyle}
          />
        </label>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span style={{ fontSize: 11, color: '#a3a3a3', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
            Bearer token
          </span>
          <input
            type="password"
            value={token}
            onChange={(e) => setToken(e.target.value)}
            placeholder="SHADE_OBSERVER_TOKEN value"
            style={inputStyle}
          />
        </label>

        {error && (
          <div style={{ color: '#ef4444', fontSize: 12, padding: '8px 10px', background: 'rgba(239, 68, 68, 0.1)', borderRadius: 4 }}>
            {error}
          </div>
        )}

        <button
          type="submit"
          style={{
            background: '#f7c948',
            color: '#0a0a0a',
            border: 'none',
            padding: '10px 16px',
            borderRadius: 6,
            fontSize: 13,
            fontWeight: 600,
            cursor: 'pointer',
            fontFamily: 'inherit',
          }}
        >
          Connect
        </button>
      </form>
    </div>
  );
}

const inputStyle: React.CSSProperties = {
  background: '#0a0a0a',
  border: '1px solid #262626',
  borderRadius: 6,
  padding: '10px 12px',
  fontSize: 13,
  color: '#e5e5e5',
  fontFamily: 'system-ui, -apple-system, sans-serif',
  outline: 'none',
};
