import React, { useState, useMemo, useTransition, useEffect, useCallback } from 'react';

interface Integration {
  id: string;
  name: string;
  type: 'CRM' | 'Marketing' | 'Sales' | 'Analytics';
  status: 'connected' | 'error' | 'rate-limited';
  apiCalls: number;
  rateLimit: number;
  lastSync: string;
  health: number;
}

const mockIntegrations: Integration[] = [
  { id: '1', name: 'Salesforce', type: 'CRM', status: 'connected', apiCalls: 8450, rateLimit: 10000, lastSync: '2024-02-13 11:30', health: 98 },
  { id: '2', name: 'Mailchimp', type: 'Marketing', status: 'connected', apiCalls: 5230, rateLimit: 10000, lastSync: '2024-02-13 11:25', health: 100 },
  { id: '3', name: 'Stripe', type: 'Sales', status: 'rate-limited', apiCalls: 9950, rateLimit: 10000, lastSync: '2024-02-13 11:20', health: 45 },
  { id: '4', name: 'Google Analytics', type: 'Analytics', status: 'connected', apiCalls: 3200, rateLimit: 50000, lastSync: '2024-02-13 11:28', health: 100 },
  { id: '5', name: 'Slack', type: 'CRM', status: 'error', apiCalls: 1200, rateLimit: 5000, lastSync: '2024-02-13 10:00', health: 12 },
];

const useDebounce = <T,>(value: T, delay: number): T => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);
  return debouncedValue;
};

interface Toast {
  id: number;
  message: string;
  type: 'success' | 'error' | 'info';
}

const useToast = () => {
  const [toasts, setToasts] = useState<Toast[]>([]);
  const addToast = useCallback((message: string, type: Toast['type'] = 'info') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  }, []);
  return { toasts, addToast };
};

const App = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedIntegration, setSelectedIntegration] = useState<Integration | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredIntegrations = useMemo(() => {
    if (!debouncedSearch) return mockIntegrations;
    const term = debouncedSearch.toLowerCase();
    return mockIntegrations.filter(i => i.name.toLowerCase().includes(term));
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockIntegrations.length,
    connected: mockIntegrations.filter(i => i.status === 'connected').length,
    errors: mockIntegrations.filter(i => i.status === 'error').length,
    avgHealth: (mockIntegrations.reduce((sum, i) => sum + i.health, 0) / mockIntegrations.length).toFixed(0),
  }), []);

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    startTransition(() => {
      setSearchTerm(e.target.value);
    });
  };

  const handleSelectIntegration = (integration: Integration) => {
    setSelectedIntegration(integration);
    addToast(`Viewing ${integration.name}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Integration Status</h1>
        <p>API usage, rate limits, connection health</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Integrations</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Connected</div>
          <div className="stat-value">{stats.connected}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Errors</div>
          <div className="stat-value">{stats.errors}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Avg Health</div>
          <div className="stat-value">{stats.avgHealth}%</div>
        </div>
      </div>

      <div className="search-bar">
        <input
          type="text"
          placeholder="Search integrations..."
          value={searchTerm}
          onChange={handleSearch}
          className="search-input"
        />
        {isPending && <span className="search-loading">Searching...</span>}
      </div>

      {filteredIntegrations.length === 0 ? (
        <div className="empty-state">
          <h3>No integrations found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Type</th>
                <th>Status</th>
                <th>API Calls</th>
                <th>Rate Limit</th>
                <th>Health</th>
                <th>Last Sync</th>
              </tr>
            </thead>
            <tbody>
              {filteredIntegrations.map(integration => (
                <tr
                  key={integration.id}
                  onClick={() => handleSelectIntegration(integration)}
                  className={selectedIntegration?.id === integration.id ? 'selected' : ''}
                >
                  <td>{integration.name}</td>
                  <td>{integration.type}</td>
                  <td>
                    <span className={`status-badge status-${integration.status}`}>
                      {integration.status}
                    </span>
                  </td>
                  <td>{integration.apiCalls.toLocaleString()} / {integration.rateLimit.toLocaleString()}</td>
                  <td>{((integration.apiCalls / integration.rateLimit) * 100).toFixed(0)}%</td>
                  <td>{integration.health}%</td>
                  <td>{integration.lastSync}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedIntegration && (
        <div className="detail-panel">
          <h3>Integration Details</h3>
          <div className="detail-grid">
            <div><strong>Name:</strong> {selectedIntegration.name}</div>
            <div><strong>Type:</strong> {selectedIntegration.type}</div>
            <div><strong>Status:</strong> {selectedIntegration.status}</div>
            <div><strong>API Calls:</strong> {selectedIntegration.apiCalls.toLocaleString()}</div>
            <div><strong>Rate Limit:</strong> {selectedIntegration.rateLimit.toLocaleString()}</div>
            <div><strong>Usage:</strong> {((selectedIntegration.apiCalls / selectedIntegration.rateLimit) * 100).toFixed(1)}%</div>
            <div><strong>Health:</strong> {selectedIntegration.health}%</div>
            <div><strong>Last Sync:</strong> {selectedIntegration.lastSync}</div>
          </div>
        </div>
      )}

      <div className="toast-container">
        {toasts.map(toast => (
          <div key={toast.id} className={`toast toast-${toast.type}`}>
            {toast.message}
          </div>
        ))}
      </div>
    </div>
  );
};

export default App;
