import { FormEvent, useState } from 'react';
import { KeyRound, Link, PlugZap, Save } from 'lucide-react';
import { useCompanion } from '../../api/CompanionContext.js';
import { CompanionClient, DEFAULT_COMPANION_URL } from '../../api/companionClient.js';

export function SettingsScreen() {
  const { client, settings, updateSettings } = useCompanion();
  const [baseUrl, setBaseUrl] = useState(settings.baseUrl);
  const [accessKey, setAccessKey] = useState(settings.accessKey);
  const [status, setStatus] = useState('Run companion setup, paste the access key, then test the connection.');

  function save(event: FormEvent<HTMLFormElement>): void {
    event.preventDefault();
    updateSettings({ baseUrl: baseUrl || DEFAULT_COMPANION_URL, accessKey });
    setStatus('Settings saved.');
  }

  async function testConnection(): Promise<void> {
    updateSettings({ baseUrl: baseUrl || DEFAULT_COMPANION_URL, accessKey });
    setStatus('Testing connection…');

    try {
      const testClient = new CompanionClient({ baseUrl: baseUrl || DEFAULT_COMPANION_URL, accessKey });
      await testClient.health();
      const response = await testClient.validate();
      setStatus(response.message);
    } catch (caughtError) {
      setStatus(caughtError instanceof Error ? caughtError.message : 'Connection failed');
    }
  }

  return (
    <section className="screen stack-screen settings-screen">
      <article className="quest-card quest-card--compact quest-card--green">
        <div className="quest-orb quest-orb--green"><PlugZap size={32} strokeWidth={3} /></div>
        <div>
          <p className="eyebrow">Nest setup</p>
          <h2>Pair your companion</h2>
          <p>{status}</p>
        </div>
      </article>
      <form className="settings-card" onSubmit={save}>
        <label htmlFor="server-url"><Link size={18} /> Companion server URL</label>
        <input id="server-url" onChange={(event) => setBaseUrl(event.target.value)} placeholder={DEFAULT_COMPANION_URL} type="url" value={baseUrl} />
        <label htmlFor="access-key"><KeyRound size={18} /> Access key</label>
        <input id="access-key" onChange={(event) => setAccessKey(event.target.value)} placeholder="hm_…" type="password" value={accessKey} />
        <div className="button-row">
          <button className="secondary-button" type="submit"><Save size={18} /> Save</button>
          <button className="primary-button" onClick={() => void testConnection()} type="button">Test <PlugZap size={19} /></button>
        </div>
      </form>
    </section>
  );
}
