import { useState } from 'react';
import { invoke } from '@tauri-apps/api/tauri';
import './App.css';

// Types matching the Rust backend
interface EnvelopeData {
  ucxl_uri: string;
  content: string;
  content_type: string;
  author?: string;
  title?: string;
  tags: string[];
}

interface SearchQueryData {
  text?: string;
  tags: string[];
  author?: string;
  content_type?: string;
  limit?: number;
  offset?: number;
}

type UiToCoreCommand = 
  | { GetEnvelope: { envelope_id: string } }
  | { GetEnvelopeByUri: { uri: string } }
  | { StoreEnvelope: { envelope: EnvelopeData } }
  | { ExecuteUCXLGet: { uri: string; version?: string; at_time?: string } }
  | { ExecuteUCXLPost: { uri: string; markdown_content: string; author?: string; title?: string } }
  | { SearchEnvelopes: { query: SearchQueryData } }
  | 'GetStoreStats'
  | 'InitializeDHT'
  | 'GetNetworkStatus'
  | 'GetBZZZStats'
  | { StoreToDHT: { envelope: EnvelopeData } }
  | { RetrieveFromDHT: { envelope_id: string } }
  | 'GetPeerList';

function App() {
  const [activeTab, setActiveTab] = useState<'get' | 'post' | 'search' | 'store' | 'dht' | 'network'>('get');
  const [uri, setUri] = useState('ucxl://example.com/test');
  const [response, setResponse] = useState('');
  const [loading, setLoading] = useState(false);
  const [dhtInitialized, setDhtInitialized] = useState(false);
  
  // Form states
  const [markdownContent, setMarkdownContent] = useState('# Example Document\n\nThis is example markdown content.');
  const [author, setAuthor] = useState('User');
  const [title, setTitle] = useState('Test Document');
  const [searchText, setSearchText] = useState('');
  const [searchTags, setSearchTags] = useState('');

  const executeCommand = async (command: UiToCoreCommand) => {
    setLoading(true);
    try {
      const result = await invoke('handle_command', { command });
      setResponse(JSON.stringify(result, null, 2));
    } catch (err) {
      setResponse(`Error: ${err}`);
    } finally {
      setLoading(false);
    }
  };

  const handleGetEnvelope = () => {
    executeCommand({ GetEnvelopeByUri: { uri } });
  };

  const handlePostMarkdown = () => {
    executeCommand({ 
      ExecuteUCXLPost: { 
        uri, 
        markdown_content: markdownContent, 
        author: author || undefined,
        title: title || undefined 
      } 
    });
  };

  const handleSearch = () => {
    const query: SearchQueryData = {
      text: searchText || undefined,
      tags: searchTags ? searchTags.split(',').map(t => t.trim()) : [],
      limit: 10
    };
    executeCommand({ SearchEnvelopes: { query } });
  };

  const handleGetStats = () => {
    executeCommand('GetStoreStats');
  };
  
  const handleInitializeDHT = () => {
    executeCommand('InitializeDHT').then(() => {
      setDhtInitialized(true);
    });
  };
  
  const handleGetNetworkStatus = () => {
    executeCommand('GetNetworkStatus');
  };
  
  const handleGetBZZZStats = () => {
    executeCommand('GetBZZZStats');
  };
  
  const handleStoreToDHT = () => {
    const envelope: EnvelopeData = {
      ucxl_uri: uri,
      content: markdownContent,
      content_type: 'text/markdown',
      author: author || undefined,
      title: title || undefined,
      tags: ['dht', 'test']
    };
    executeCommand({ StoreToDHT: { envelope } });
  };
  
  const handleRetrieveFromDHT = () => {
    const envelopeId = searchText; // Use search input as envelope ID
    executeCommand({ RetrieveFromDHT: { envelope_id: envelopeId } });
  };
  
  const handleGetPeerList = () => {
    executeCommand('GetPeerList');
  };

  return (
    <div className="container">
      <h1>UCXL Browser</h1>
      
      {/* Tab Navigation */}
      <div className="tabs">
        <button 
          className={activeTab === 'get' ? 'tab-active' : 'tab'} 
          onClick={() => setActiveTab('get')}
        >
          Get Content
        </button>
        <button 
          className={activeTab === 'post' ? 'tab-active' : 'tab'} 
          onClick={() => setActiveTab('post')}
        >
          Post Markdown
        </button>
        <button 
          className={activeTab === 'search' ? 'tab-active' : 'tab'} 
          onClick={() => setActiveTab('search')}
        >
          Search
        </button>
        <button 
          className={activeTab === 'store' ? 'tab-active' : 'tab'} 
          onClick={() => setActiveTab('store')}
        >
          Store Info
        </button>
        <button 
          className={activeTab === 'dht' ? 'tab-active' : 'tab'} 
          onClick={() => setActiveTab('dht')}
        >
          DHT Operations
        </button>
        <button 
          className={activeTab === 'network' ? 'tab-active' : 'tab'} 
          onClick={() => setActiveTab('network')}
        >
          Network Status
        </button>
      </div>

      {/* Tab Content */}
      <div className="tab-content">
        {activeTab === 'get' && (
          <div className="section">
            <h3>Retrieve Content</h3>
            <div className="form-row">
              <input
                type="text"
                value={uri}
                onChange={(e) => setUri(e.target.value)}
                placeholder="Enter UCXL URI"
                className="uri-input"
              />
              <button onClick={handleGetEnvelope} disabled={loading}>
                {loading ? 'Loading...' : 'Get Envelope'}
              </button>
            </div>
          </div>
        )}

        {activeTab === 'post' && (
          <div className="section">
            <h3>Submit Markdown Context</h3>
            <div className="form-row">
              <input
                type="text"
                value={uri}
                onChange={(e) => setUri(e.target.value)}
                placeholder="UCXL URI"
                className="uri-input"
              />
            </div>
            <div className="form-row">
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="Document Title"
              />
              <input
                type="text"
                value={author}
                onChange={(e) => setAuthor(e.target.value)}
                placeholder="Author"
              />
            </div>
            <div className="form-row">
              <textarea
                value={markdownContent}
                onChange={(e) => setMarkdownContent(e.target.value)}
                placeholder="Enter Markdown content..."
                rows={10}
                className="markdown-editor"
              />
            </div>
            <div className="form-row">
              <button onClick={handlePostMarkdown} disabled={loading}>
                {loading ? 'Submitting...' : 'Submit Context'}
              </button>
            </div>
          </div>
        )}

        {activeTab === 'search' && (
          <div className="section">
            <h3>Search Envelopes</h3>
            <div className="form-row">
              <input
                type="text"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                placeholder="Search text in content and titles"
                className="search-input"
              />
            </div>
            <div className="form-row">
              <input
                type="text"
                value={searchTags}
                onChange={(e) => setSearchTags(e.target.value)}
                placeholder="Tags (comma-separated)"
              />
              <button onClick={handleSearch} disabled={loading}>
                {loading ? 'Searching...' : 'Search'}
              </button>
            </div>
          </div>
        )}

        {activeTab === 'store' && (
          <div className="section">
            <h3>Store Information</h3>
            <div className="form-row">
              <button onClick={handleGetStats} disabled={loading}>
                {loading ? 'Loading...' : 'Get Store Stats'}
              </button>
            </div>
          </div>
        )}

        {activeTab === 'dht' && (
          <div className="section">
            <h3>DHT Operations</h3>
            {!dhtInitialized && (
              <div className="form-row">
                <button onClick={handleInitializeDHT} disabled={loading}>
                  {loading ? 'Initializing...' : 'Initialize DHT Network'}
                </button>
                <p className="dht-status">DHT network must be initialized before use</p>
              </div>
            )}
            
            {dhtInitialized && (
              <>
                <div className="form-row">
                  <input
                    type="text"
                    value={uri}
                    onChange={(e) => setUri(e.target.value)}
                    placeholder="UCXL URI for DHT storage"
                    className="uri-input"
                  />
                </div>
                
                <div className="form-row">
                  <input
                    type="text"
                    value={title}
                    onChange={(e) => setTitle(e.target.value)}
                    placeholder="Document Title"
                  />
                  <input
                    type="text"
                    value={author}
                    onChange={(e) => setAuthor(e.target.value)}
                    placeholder="Author"
                  />
                </div>
                
                <div className="form-row">
                  <textarea
                    value={markdownContent}
                    onChange={(e) => setMarkdownContent(e.target.value)}
                    placeholder="Markdown content to store in DHT..."
                    rows={8}
                    className="markdown-editor"
                  />
                </div>
                
                <div className="form-row">
                  <button onClick={handleStoreToDHT} disabled={loading}>
                    {loading ? 'Storing...' : 'Store to DHT'}
                  </button>
                </div>
                
                <hr />
                
                <div className="form-row">
                  <input
                    type="text"
                    value={searchText}
                    onChange={(e) => setSearchText(e.target.value)}
                    placeholder="Enter Envelope ID to retrieve from DHT"
                    className="search-input"
                  />
                  <button onClick={handleRetrieveFromDHT} disabled={loading}>
                    {loading ? 'Retrieving...' : 'Retrieve from DHT'}
                  </button>
                </div>
              </>
            )}
          </div>
        )}

        {activeTab === 'network' && (
          <div className="section">
            <h3>Network Status & Monitoring</h3>
            <div className="form-row">
              <button onClick={handleGetNetworkStatus} disabled={loading}>
                {loading ? 'Loading...' : 'Get Network Status'}
              </button>
              <button onClick={handleGetBZZZStats} disabled={loading}>
                {loading ? 'Loading...' : 'Get BZZZ Stats'}
              </button>
              <button onClick={handleGetPeerList} disabled={loading}>
                {loading ? 'Loading...' : 'Get Peer List'}
              </button>
            </div>
            
            <div className="network-info">
              <p>Monitor DHT network health, peer connections, and performance metrics</p>
              <ul>
                <li><strong>Network Status</strong>: Overall network health and connectivity</li>
                <li><strong>BZZZ Stats</strong>: Gateway statistics and performance metrics</li>
                <li><strong>Peer List</strong>: Connected peers and their capabilities</li>
              </ul>
            </div>
          </div>
        )}
      </div>

      {/* Response Display */}
      <div className="response-section">
        <h3>Response</h3>
        <pre className="response">{response}</pre>
      </div>
    </div>
  );
}

export default App;
