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

function SecretsSection({ secrets, secretsLoading, onAddSecret, onRotateSecret, onDeleteSecret }) {
  const [addOpen, setAddOpen] = useState(false);
  const [addName, setAddName] = useState('');
  const [addValue, setAddValue] = useState('');
  const [addScope, setAddScope] = useState('global');
  const [addBusy, setAddBusy] = useState(false);
  const [addError, setAddError] = useState('');
  const [rotatingName, setRotatingName] = useState(null);
  const [rotateValue, setRotateValue] = useState('');
  const [rotateBusy, setRotateBusy] = useState(false);
  const [rotateError, setRotateError] = useState('');
  const [deletingId, setDeletingId] = useState(null);

  async function handleAdd(e) {
    e.preventDefault();
    if (!addName.trim() || !addValue.trim()) return;
    setAddBusy(true);
    setAddError('');
    try {
      await onAddSecret({ name: addName.trim(), value: addValue.trim(), scope: addScope });
      setAddName('');
      setAddValue('');
      setAddScope('global');
      setAddOpen(false);
    } catch (err) {
      setAddError(err.message || 'Failed to save secret');
    } finally {
      setAddBusy(false);
    }
  }

  async function handleRotate(secret) {
    if (!rotateValue.trim()) return;
    setRotateBusy(true);
    setRotateError('');
    try {
      await onRotateSecret(secret.name, rotateValue.trim(), secret.scope);
      setRotatingName(null);
      setRotateValue('');
    } catch (err) {
      setRotateError(err.message || 'Failed to rotate secret');
    } finally {
      setRotateBusy(false);
    }
  }

  async function handleDelete(secret) {
    setDeletingId(secret.id);
    try {
      await onDeleteSecret(secret.name, secret.scope);
    } finally {
      setDeletingId(null);
    }
  }

  function formatDate(iso) {
    if (!iso) return 'Never';
    try {
      return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
    } catch {
      return iso;
    }
  }

  return (
    <div className="config-secrets-panel">
      <div className="config-secrets-head">
        <div>
          <span className="config-section-title">Secrets vault</span>
          <p>Integration credentials stored encrypted at rest. Values are never shown after saving.</p>
        </div>
        <button
          type="button"
          className="config-save-btn"
          onClick={() => { setAddOpen(o => !o); setAddError(''); }}
        >
          {addOpen ? 'Cancel' : 'Add secret'}
        </button>
      </div>

      {addOpen && (
        <form className="secrets-add-form" onSubmit={handleAdd}>
          <div className="secrets-add-fields">
            <label className="config-env-field">
              <span className="config-env-field-top">
                <b>Name</b>
              </span>
              <input
                type="text"
                autoComplete="off"
                placeholder="e.g. GITHUB_TOKEN"
                value={addName}
                onChange={e => setAddName(e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, '_'))}
                required
              />
            </label>
            <label className="config-env-field">
              <span className="config-env-field-top">
                <b>Value</b>
              </span>
              <input
                type="password"
                autoComplete="new-password"
                placeholder="Paste secret value"
                value={addValue}
                onChange={e => setAddValue(e.target.value)}
                required
              />
            </label>
          </div>
          <div className="secrets-add-footer">
            <label className="secrets-scope-field">
              <span>Scope</span>
              <select value={addScope} onChange={e => setAddScope(e.target.value)}>
                <option value="global">global (all agents)</option>
              </select>
            </label>
            {addError && <span className="secrets-error">{addError}</span>}
            <button type="submit" className="config-save-btn" disabled={addBusy || !addName.trim() || !addValue.trim()}>
              {addBusy ? 'Saving...' : 'Save secret'}
            </button>
          </div>
        </form>
      )}

      {secretsLoading && (
        <div className="secrets-empty">Loading...</div>
      )}

      {!secretsLoading && secrets.length === 0 && (
        <div className="secrets-empty">No secrets configured. Add integration credentials above.</div>
      )}

      {!secretsLoading && secrets.length > 0 && (
        <div className="config-tools-list">
          {secrets.map(secret => (
            <div key={secret.id} className="config-tool-row on">
              <div className="secrets-row-inner">
                <div className="secrets-row-meta">
                  <div className="config-tool-titleline">
                    <span className="config-tool-name" style={{ textTransform: 'none' }}>{secret.name}</span>
                    <span className="config-tool-risk">{secret.scope}</span>
                    {secret.source && secret.source !== 'manual' && (
                      <span className="config-tool-risk">{secret.source}</span>
                    )}
                  </div>
                  <div className="config-tool-status">
                    <span className="ready">Active</span>
                    <span>Rotated {formatDate(secret.rotated_at)}</span>
                    {secret.last_used_at && <span>Used {formatDate(secret.last_used_at)}</span>}
                  </div>
                </div>
                <div className="secrets-row-actions">
                  {rotatingName === secret.id ? (
                    <div className="secrets-rotate-inline">
                      <input
                        type="password"
                        autoComplete="new-password"
                        placeholder="New value"
                        value={rotateValue}
                        onChange={e => setRotateValue(e.target.value)}
                        autoFocus
                      />
                      {rotateError && <span className="secrets-error">{rotateError}</span>}
                      <button
                        type="button"
                        className="secrets-action-btn"
                        onClick={() => handleRotate(secret)}
                        disabled={rotateBusy || !rotateValue.trim()}
                      >
                        {rotateBusy ? '...' : 'Save'}
                      </button>
                      <button
                        type="button"
                        className="secrets-action-btn secondary"
                        onClick={() => { setRotatingName(null); setRotateValue(''); setRotateError(''); }}
                      >
                        Cancel
                      </button>
                    </div>
                  ) : (
                    <>
                      <button
                        type="button"
                        className="secrets-action-btn secondary"
                        onClick={() => { setRotatingName(secret.id); setRotateValue(''); setRotateError(''); }}
                      >
                        Rotate
                      </button>
                      <button
                        type="button"
                        className="secrets-action-btn danger"
                        disabled={deletingId === secret.id}
                        onClick={() => handleDelete(secret)}
                      >
                        {deletingId === secret.id ? '...' : 'Delete'}
                      </button>
                    </>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default function SecretsTab() {
  const {
    secrets,
    secretsLoading,
    handleAddSecret,
    handleRotateSecret,
    handleDeleteSecret,
  } = useDashboard();
  return (
    <SecretsSection
      secrets={secrets || []}
      secretsLoading={secretsLoading}
      onAddSecret={handleAddSecret}
      onRotateSecret={handleRotateSecret}
      onDeleteSecret={handleDeleteSecret}
    />
  );
}
