"use client";
import { useDashboard } from '../dashboard-context';

export default function EnvTab() {
  const {
    configEnv,
    configEnvValues,
    configEnvSaving,
    configEnvSaved,
    setConfigEnvSaved,
    setConfigEnvValues,
    saveEnvValues,
  } = useDashboard();
  return (
    <div className="tools-pane">
      <div className="config-secrets-panel">
        <div className="config-secrets-head">
          <div>
            <span className="config-section-title">Local config</span>
            <p>Paste only the values you want to add or replace. These are non-credential config vars.</p>
          </div>
          <button
            type="button"
            className="config-save-btn"
            onClick={saveEnvValues}
            disabled={configEnvSaving || !Object.values(configEnvValues).some(v => String(v || '').trim())}
          >
            {configEnvSaving ? 'Saving...' : 'Save Config'}
          </button>
        </div>
        {configEnvSaved && <div className="config-env-saved">Saved to .env.local. Tools refresh immediately for this running server.</div>}
        <div className="config-env-grid">
          {[...new Set(configEnv.map(item => item.group))].map(group => (
            <div key={group} className="config-env-group">
              <div className="config-env-group-title">{group}</div>
              {configEnv.filter(item => item.group === group).map(item => (
                <label key={item.name} className="config-env-field">
                  <span className="config-env-field-top">
                    <b>{item.label}</b>
                    <em className={item.configured ? 'ready' : ''}>{item.configured ? 'Configured' : 'Not set'}</em>
                  </span>
                  <small>{item.description}</small>
                  <input
                    type="text"
                    autoComplete="off"
                    placeholder={item.configured ? 'Current value saved' : `Set ${item.name}`}
                    value={configEnvValues[item.name] || ''}
                    onChange={e => {
                      setConfigEnvSaved(false);
                      setConfigEnvValues(values => ({ ...values, [item.name]: e.target.value }));
                    }}
                  />
                  <code>{item.name}</code>
                </label>
              ))}
            </div>
          ))}
          {configEnv.length === 0 && (
            <div className="secrets-empty">No local config variables defined.</div>
          )}
        </div>
      </div>
    </div>
  );
}
