import { useEffect, useState } from 'react';
import { TimezoneSelect } from '../../TimezoneSelect';
import { useConnection } from '../../../context/ConnectionContext';
import { configSaveNote } from '../../../data/configNotes';

const SECTIONS = [
  {
    title: 'Identity',
    fields: [
      { key: 'name', label: 'Organization name', type: 'text' },
      { key: 'timezone', label: 'Timezone', type: 'timezone' },
    ],
  },
  {
    title: 'Network',
    fields: [
      { key: 'port', label: 'Client port', type: 'number' },
      { key: 'web_port', label: 'Web access port', type: 'number' },
    ],
  },
  {
    title: 'Limits',
    fields: [
      { key: 'max_devices_per_user', label: 'Max devices per user', type: 'number' },
      { key: 'online_window_seconds', label: 'Online window (seconds)', type: 'number' },
    ],
  },
  {
    title: 'Scope',
    fields: [
      { key: 'members_scope', label: 'Members list scope', type: 'scope' },
      { key: 'availability_scope', label: 'Availability scope', type: 'scope' },
    ],
  },
  {
    title: 'Naming',
    fields: [
      { key: 'enforce_safe_naming', label: 'Enforce cross-OS-safe file names', type: 'bool' },
      { key: 'staging_max_age_days', label: 'Staging max age (days)', type: 'number' },
    ],
  },
  {
    title: 'Invite codes',
    fields: [
      { key: 'disable_invite_codes', label: 'Disable project invite codes', type: 'bool' },
    ],
  },
  {
    title: 'Visibility',
    fields: [
      { key: 'enable_organization', label: 'Enable organization features', type: 'bool' },
      { key: 'hide_owner', label: 'Hide owner account from user list', type: 'bool' },
    ],
  },
];

export function ServerConfigForm() {
  const { api, logout } = useConnection();
  const [config, setConfig] = useState(null);
  const [owner, setOwner] = useState('');
  const [error, setError] = useState(null);
  const [saveNote, setSaveNote] = useState(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    let live = true;
    (async () => {
      const result = await api.getAdminConfig();
      if (!live) return;
      if (result.ok) {
        setConfig(result.config);
        setOwner(result.owner ?? '');
      } else {
        setError(result.error ?? 'Could not load server config.');
      }
    })();
    return () => { live = false; };
  }, [api]);

  const update = (key, value) => {
    setConfig((c) => ({ ...c, [key]: value }));
    setSaveNote(null);
  };

  const save = async () => {
    setBusy(true);
    setError(null);
    const result = await api.saveAdminConfig(config);
    setBusy(false);
    if (result.ok) setSaveNote(configSaveNote(result.deferred));
    else setError(result.error ?? 'Save failed.');
  };

  const shutdown = async () => {
    if (!window.confirm('The server will shutdown. It will only automatically restart if you have a configuration or process to do so.')) {
      return;
    }
    setBusy(true);
    setError(null);
    const result = await api.shutdownServer();
    setBusy(false);
    if (result.ok) logout();
    else setError(result.error ?? 'Shutdown failed.');
  };

  if (!config) {
    return <div className="server-config">{error ? <div className="server-config-error">{error}</div> : 'Loading…'}</div>;
  }

  return (
    <div className="server-config">
      <h2 className="server-config-title">Server Config</h2>
      {SECTIONS.map((section) => (
        <fieldset key={section.title} className="server-config-section">
          <legend>{section.title}</legend>
          {section.fields.map((field) => (
            <label key={field.key} className="server-config-field">
              <span className="server-config-field-label">{field.label}</span>
              {field.type === 'bool' ? (
                <input
                  type="checkbox"
                  checked={Boolean(config[field.key])}
                  onChange={(e) => update(field.key, e.target.checked)}
                />
              ) : field.type === 'timezone' ? (
                <TimezoneSelect
                  value={config[field.key]}
                  onChange={(value) => update(field.key, value)}
                />
              ) : field.type === 'scope' ? (
                <select value={config[field.key]} onChange={(e) => update(field.key, e.target.value)}>
                  <option value="project">Project</option>
                  <option value="org">Org</option>
                </select>
              ) : (
                <input
                  type={field.type === 'number' ? 'number' : 'text'}
                  value={config[field.key]}
                  {...(field.type === 'number' ? { step: '1', min: '0' } : {})}
                  onChange={(e) =>
                    update(field.key, field.type === 'number' ? Number(e.target.value) : e.target.value)
                  }
                />
              )}
            </label>
          ))}
        </fieldset>
      ))}
      <fieldset className="server-config-section">
        <legend>Owner</legend>
        <label className="server-config-field">
          <span className="server-config-field-label">Server owner</span>
          <input type="text" value={owner} readOnly disabled title="Set in serverconfig.conf" />
        </label>
      </fieldset>
      {error && <div className="server-config-error">{error}</div>}
      <div className="server-config-actions">
        <button type="button" className="server-config-save" disabled={busy} onClick={save}>
          {busy ? 'Saving…' : 'Save'}
        </button>
        <button type="button" className="server-config-save server-config-shutdown" disabled={busy} onClick={shutdown}>
          Shutdown Server
        </button>
        {saveNote && <span className="server-config-note">{saveNote}</span>}
      </div>
    </div>
  );
}
