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

function scopeValuePlaceholder(scopeKey) {
  switch (scopeKey) {
    case 'recipient_domain': return 'e.g. madarx.io';
    case 'repo_full_name': return 'e.g. org/repo-name';
    case 'channel_id': return 'e.g. C01234ABCDE';
    case 'zone_id': return 'e.g. abc123def456';
    case 'customer_id': return 'e.g. cus_abc123';
    case 'table': return 'e.g. users';
    default: return 'Enter value';
  }
}

function AllowlistsSection({ allowlists, allowlistsLoading, configTools, onAddAllowlistEntry, onRemoveAllowlistEntry }) {
  const [addingTool, setAddingTool] = useState(null);
  const [addValue, setAddValue] = useState('');
  const [addLabel, setAddLabel] = useState('');
  const [addBusy, setAddBusy] = useState(false);
  const [addError, setAddError] = useState('');
  const [deletingId, setDeletingId] = useState(null);

  // Only show tools that have allowlist_required true.
  const requiredTools = (configTools || []).filter(t => t.allowlist_required);

  function openAdd(tool) {
    setAddingTool(tool.name);
    setAddValue('');
    setAddLabel('');
    setAddError('');
  }

  function cancelAdd() {
    setAddingTool(null);
    setAddValue('');
    setAddLabel('');
    setAddError('');
  }

  async function handleAdd(e, tool) {
    e.preventDefault();
    if (!addValue.trim()) return;
    setAddBusy(true);
    setAddError('');
    try {
      await onAddAllowlistEntry({
        tool_name: tool.name,
        scope_key: tool.allowlist_scope_key,
        scope_value: addValue.trim(),
        label: addLabel.trim() || undefined,
      });
      cancelAdd();
    } catch (err) {
      setAddError(err.message || 'Failed to add entry');
    } finally {
      setAddBusy(false);
    }
  }

  async function handleRemove(entry) {
    setDeletingId(entry.id);
    try {
      await onRemoveAllowlistEntry(entry.id);
    } finally {
      setDeletingId(null);
    }
  }

  return (
    <div className="config-secrets-panel">
      <div className="config-secrets-head">
        <div>
          <span className="config-section-title">Destination allowlists</span>
          <p>
            Required by some tools (e.g. email recipients, Slack channels, GitHub repos).
            An empty allowlist blocks all calls for those tools — the owner must add at
            least one entry before the tool can send anything externally.
          </p>
        </div>
      </div>

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

      {!allowlistsLoading && requiredTools.length === 0 && (
        <div className="allowlists-empty-state">
          <p>
            No tools currently require destination allowlists. Tools added in Phase A
            (GitHub, Resend, Supabase writes) will appear here once their adapters are
            built. When they do, you will be able to restrict which repos, email domains,
            or database tables each tool is allowed to touch.
          </p>
        </div>
      )}

      {!allowlistsLoading && requiredTools.length > 0 && (
        <div className="allowlists-tool-list">
          {requiredTools.map(tool => {
            const entries = allowlists?.[tool.name] || [];
            const isAdding = addingTool === tool.name;
            return (
              <div key={tool.name} className="allowlists-tool-block">
                <div className="allowlists-tool-head">
                  <div className="allowlists-tool-meta">
                    <span className="config-tool-name">{tool.title || tool.name.replace(/_/g, ' ')}</span>
                    <span className="allowlists-scope-key">{tool.allowlist_scope_key}</span>
                  </div>
                  {!isAdding && (
                    <button
                      type="button"
                      className="secrets-action-btn"
                      onClick={() => openAdd(tool)}
                    >
                      Add entry
                    </button>
                  )}
                </div>

                {isAdding && (
                  <form className="secrets-add-form" onSubmit={e => handleAdd(e, tool)}>
                    <div className="secrets-add-fields">
                      <label className="config-env-field">
                        <span className="config-env-field-top">
                          <b>{tool.allowlist_scope_key}</b>
                        </span>
                        <input
                          type="text"
                          autoComplete="off"
                          placeholder={scopeValuePlaceholder(tool.allowlist_scope_key)}
                          value={addValue}
                          onChange={e => setAddValue(e.target.value)}
                          required
                          autoFocus
                        />
                      </label>
                      <label className="config-env-field">
                        <span className="config-env-field-top">
                          <b>Label</b>
                          <em style={{ fontStyle: 'normal', fontSize: '10px', color: '#68707b', background: 'transparent', padding: 0 }}>optional</em>
                        </span>
                        <input
                          type="text"
                          autoComplete="off"
                          placeholder="Human-readable note"
                          value={addLabel}
                          onChange={e => setAddLabel(e.target.value)}
                        />
                      </label>
                    </div>
                    <div className="secrets-add-footer">
                      {addError && <span className="secrets-error">{addError}</span>}
                      <button
                        type="submit"
                        className="config-save-btn"
                        disabled={addBusy || !addValue.trim()}
                      >
                        {addBusy ? 'Saving...' : 'Save entry'}
                      </button>
                      <button
                        type="button"
                        className="secrets-action-btn secondary"
                        onClick={cancelAdd}
                      >
                        Cancel
                      </button>
                    </div>
                  </form>
                )}

                {entries.length === 0 && !isAdding && (
                  <div className="allowlists-entries-empty">
                    No entries — all calls to this tool are currently blocked.
                    Add at least one destination to enable it.
                  </div>
                )}

                {entries.length > 0 && (
                  <div className="config-tools-list">
                    {entries.map(entry => (
                      <div key={entry.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' }}>{entry.scope_value}</span>
                              <span className="config-tool-risk">{entry.scope_key}</span>
                            </div>
                            {entry.label && (
                              <div className="config-tool-status">
                                <span>{entry.label}</span>
                              </div>
                            )}
                          </div>
                          <div className="secrets-row-actions">
                            <button
                              type="button"
                              className="secrets-action-btn danger"
                              disabled={deletingId === entry.id}
                              onClick={() => handleRemove(entry)}
                            >
                              {deletingId === entry.id ? '...' : 'Remove'}
                            </button>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

export default function AllowlistsTab() {
  const {
    allowlists,
    allowlistsLoading,
    configTools,
    handleAddAllowlistEntry,
    handleRemoveAllowlistEntry,
  } = useDashboard();
  return (
    <AllowlistsSection
      allowlists={allowlists || {}}
      allowlistsLoading={allowlistsLoading}
      configTools={configTools}
      onAddAllowlistEntry={handleAddAllowlistEntry}
      onRemoveAllowlistEntry={handleRemoveAllowlistEntry}
    />
  );
}
