import { useState } from 'react';

interface Props {
  onConnect: (url: string) => void;
  onLocalMode: () => void;
}

function normalizeUrl(raw: string): string {
  const trimmed = raw.trim().replace(/\/$/, '');
  if (!trimmed) return '';
  if (!/^https?:\/\//i.test(trimmed)) return 'https://' + trimmed;
  return trimmed;
}

function isValidUrl(url: string): boolean {
  try {
    const u = new URL(url);
    return u.protocol === 'http:' || u.protocol === 'https:';
  } catch {
    return false;
  }
}

export default function SetupScreen({ onConnect, onLocalMode }: Props) {
  const [url, setUrl] = useState('');
  const [error, setError] = useState('');
  const [connecting, setConnecting] = useState(false);

  function handleConnect() {
    const normalized = normalizeUrl(url);
    if (!isValidUrl(normalized)) {
      setError('Enter a valid URL, e.g. https://bills.yourdomain.com');
      return;
    }
    setError('');
    setConnecting(true);
    onConnect(normalized);
  }

  function handleKey(e: React.KeyboardEvent) {
    if (e.key === 'Enter') handleConnect();
  }

  return (
    <div className="setup-root">
      <div className="setup-card">
        {/* Logo mark */}
        <div className="logo-mark" aria-hidden="true">
          <svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect width="40" height="40" rx="10" fill="#6366f1" fillOpacity="0.15" />
            <path d="M20 8v4M20 28v4M8 20h4M28 20h4" stroke="#6366f1" strokeWidth="2" strokeLinecap="round" />
            <rect x="13" y="13" width="14" height="14" rx="3" stroke="#6366f1" strokeWidth="2" />
            <path d="M16 20h8M20 16v8" stroke="#6366f1" strokeWidth="1.5" strokeLinecap="round" />
          </svg>
        </div>

        <h1 className="setup-title">Bill Tracker</h1>
        <p className="setup-subtitle">Connect to your server to get started.</p>

        <div className="form-group">
          <label className="form-label" htmlFor="server-url">Server URL</label>
          <input
            id="server-url"
            className="form-input"
            type="url"
            inputMode="url"
            autoCapitalize="none"
            autoCorrect="off"
            spellCheck={false}
            placeholder="https://bills.yourdomain.com"
            value={url}
            onChange={e => { setUrl(e.target.value); setError(''); }}
            onKeyDown={handleKey}
            disabled={connecting}
          />
          {error && <p className="form-error">{error}</p>}
          <p className="form-hint">
            The address of your Bill Tracker server. Must be reachable from this device.
          </p>
        </div>

        <button
          className="btn-primary"
          onClick={handleConnect}
          disabled={connecting || !url.trim()}
        >
          {connecting ? 'Connecting…' : 'Continue'}
        </button>

        <div className="divider">
          <span>or</span>
        </div>

        <button
          className="btn-secondary"
          style={{ cursor: 'pointer' }}
          onClick={onLocalMode}
          disabled={connecting}
        >
          <span>Run on this phone</span>
        </button>

        <p className="setup-footer">
          To change your server later, go to <strong>Android Settings → Apps → Bill Tracker → Clear Storage</strong>.
        </p>
      </div>
    </div>
  );
}
