/**
 * API Key Manager Component
 */
import { useState, useEffect } from 'react';

const ApiKeyManager = () => {
  const [keys, setKeys] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [newKeyName, setNewKeyName] = useState('');
  const [generatedKey, setGeneratedKey] = useState(null);
  const [generating, setGenerating] = useState(false);

  const { ajaxUrl, nonce, apiUrl } = window.samurAiAdmin || {};

  useEffect(() => {
    fetchKeys();
  }, []);

  const fetchKeys = async () => {
    try {
      setLoading(true);
      const response = await fetch(`${apiUrl}/api-keys`, {
        headers: {
          'X-WP-Nonce': nonce,
        },
      });

      if (!response.ok) {
        throw new Error('Failed to fetch API keys');
      }

      const data = await response.json();
      setKeys(data);
      setError(null);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const generateKey = async (e) => {
    e.preventDefault();

    if (!newKeyName.trim()) {
      setError('Please enter a name for the API key');
      return;
    }

    try {
      setGenerating(true);
      setError(null);

      const response = await fetch(`${apiUrl}/api-keys`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': nonce,
        },
        body: JSON.stringify({ name: newKeyName }),
      });

      if (!response.ok) {
        throw new Error('Failed to generate API key');
      }

      const data = await response.json();
      setGeneratedKey(data);
      setNewKeyName('');
      await fetchKeys();
    } catch (err) {
      setError(err.message);
    } finally {
      setGenerating(false);
    }
  };

  const deleteKey = async (id) => {
    if (!confirm('Are you sure you want to delete this API key?')) {
      return;
    }

    try {
      const response = await fetch(`${apiUrl}/api-keys/${id}`, {
        method: 'DELETE',
        headers: {
          'X-WP-Nonce': nonce,
        },
      });

      if (!response.ok) {
        throw new Error('Failed to delete API key');
      }

      await fetchKeys();
    } catch (err) {
      setError(err.message);
    }
  };

  const copyToClipboard = (text) => {
    navigator.clipboard.writeText(text);
    alert('API key copied to clipboard!');
  };

  const closeGeneratedKey = () => {
    setGeneratedKey(null);
  };

  if (loading && keys.length === 0) {
    return <div className="loading">Loading API keys...</div>;
  }

  return (
    <div className="api-key-manager">
      {error && (
        <div className="notice notice-error">
          <p>{error}</p>
        </div>
      )}

      {generatedKey && (
        <div className="generated-key-modal">
          <div className="generated-key-content">
            <h3>API Key Generated Successfully!</h3>
            <p className="warning-text">
              Make sure to copy your API key now. You won't be able to see it again!
            </p>
            <div className="key-display">
              <code>{generatedKey.key}</code>
              <button
                className="button button-primary"
                onClick={() => copyToClipboard(generatedKey.key)}
              >
                Copy Key
              </button>
            </div>
            <div className="key-info">
              <p><strong>Name:</strong> {generatedKey.name}</p>
              <p><strong>Created:</strong> {generatedKey.created}</p>
            </div>
            <button className="button" onClick={closeGeneratedKey}>
              Close
            </button>
          </div>
        </div>
      )}

      <div className="generate-key-form">
        <h3>Generate New API Key</h3>
        <form onSubmit={generateKey}>
          <div className="form-group">
            <label htmlFor="key-name">Key Name</label>
            <input
              type="text"
              id="key-name"
              className="regular-text"
              value={newKeyName}
              onChange={(e) => setNewKeyName(e.target.value)}
              placeholder="e.g., Production Server, Development"
              disabled={generating}
            />
          </div>
          <button
            type="submit"
            className="button button-primary"
            disabled={generating}
          >
            {generating ? 'Generating...' : 'Generate API Key'}
          </button>
        </form>
      </div>

      <div className="api-keys-list">
        <h3>Existing API Keys</h3>
        {keys.length === 0 ? (
          <p>No API keys found. Generate one to get started.</p>
        ) : (
          <table className="wp-list-table widefat fixed striped">
            <thead>
              <tr>
                <th>Name</th>
                <th>Key</th>
                <th>Created</th>
                <th>Last Used</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {keys.map((key) => (
                <tr key={key.id}>
                  <td>{key.name}</td>
                  <td>
                    <code>{key.key_prefix}</code>
                  </td>
                  <td>{key.created}</td>
                  <td>{key.last_used || 'Never'}</td>
                  <td>
                    <button
                      className="button button-small button-link-delete"
                      onClick={() => deleteKey(key.id)}
                    >
                      Delete
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <div className="mcp-server-info">
        <h3>MCP Server Information</h3>
        <p>
          <strong>Endpoint:</strong> <code>{apiUrl}/mcp</code>
        </p>
        <p>
          To use this MCP server, include your API key in requests using either:
        </p>
        <ul>
          <li><code>X-API-Key</code> header</li>
          <li><code>Authorization: Bearer YOUR_KEY</code> header</li>
        </ul>
      </div>

      <div className="mcp-setup-help">
        <h3>Help Setting Up</h3>
        <p>
          To connect this MCP server to your AI chatbot (Claude Desktop, Cline, or other MCP-compatible clients),
          you'll need to configure the server endpoint and authentication. Generate an API key above, then follow
          the step-by-step instructions in our comprehensive setup guide.{' '}
          <a
            href="https://websamurai.io/chatbot_setup/"
            target="_blank"
            rel="noopener noreferrer"
            className="setup-guide-link"
          >
            View Complete Setup Guide →
          </a>
        </p>
      </div>
    </div>
  );
};

export default ApiKeyManager;
