import React, { useState, useEffect } from 'react';

export default function Settings() {
  const [githubToken, setGithubToken] = useState('');
  const [giteaToken, setGiteaToken] = useState('');
  const [giteaURL, setGiteaURL] = useState('');

  function normalizeAndValidateGiteaUrl(rawUrl) {
    const value = (rawUrl || '').trim();
    if (!value) return { ok: true, value: '' };

    let parsed;
    try {
      parsed = new URL(value);
    } catch (_) {
      return {
        ok: false,
        error: 'Ungültige Gitea-URL. Beispiel für IPv6: http://[2001:db8::1]:3000'
      };
    }

    if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
      return {
        ok: false,
        error: 'Die Gitea-URL muss mit http:// oder https:// beginnen.'
      };
    }

    return { ok: true, value: value.replace(/\/$/, '') };
  }

  useEffect(() => {
    window.electronAPI.loadCredentials().then(data => {
      if (data) {
        setGithubToken(data.githubToken || '');
        setGiteaToken(data.giteaToken || '');
        setGiteaURL(data.giteaURL || '');
      }
    });
  }, []);

  const save = () => {
    const checkedUrl = normalizeAndValidateGiteaUrl(giteaURL);
    if (!checkedUrl.ok) {
      alert(checkedUrl.error);
      return;
    }

    window.electronAPI.saveCredentials({ githubToken, giteaToken, giteaURL: checkedUrl.value });
    alert('Settings saved securely!');
  }

  return (
    <div style={{ padding: 20 }}>
      <h2>Settings</h2>
      <div>
        <label>GitHub Token:</label>
        <input type="password" value={githubToken} onChange={e => setGithubToken(e.target.value)} />
      </div>
      <div>
        <label>Gitea Token:</label>
        <input type="password" value={giteaToken} onChange={e => setGiteaToken(e.target.value)} />
      </div>
      <div>
        <label>Gitea URL:</label>
        <input type="text" value={giteaURL} onChange={e => setGiteaURL(e.target.value)} />
      </div>
      <button onClick={save} style={{ marginTop: 10 }}>Save</button>
    </div>
  );
}
