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

interface Webhook {
  id: string;
  url: string;
  eventType: string;
  status: 'active' | 'inactive' | 'failed';
  lastTriggered: string;
  successRate: number;
  totalCalls: number;
}

const mockWebhooks: Webhook[] = [
  { id: '1', url: 'https://api.example.com/contact-created', eventType: 'contact.created', status: 'active', lastTriggered: '2024-02-13 11:30', successRate: 98.5, totalCalls: 1234 },
  { id: '2', url: 'https://api.example.com/deal-updated', eventType: 'deal.updated', status: 'active', lastTriggered: '2024-02-13 10:15', successRate: 100, totalCalls: 567 },
  { id: '3', url: 'https://api.example.com/ticket-closed', eventType: 'ticket.closed', status: 'active', lastTriggered: '2024-02-13 09:00', successRate: 95.2, totalCalls: 892 },
  { id: '4', url: 'https://api.example.com/form-submit', eventType: 'form.submitted', status: 'failed', lastTriggered: '2024-02-12 16:45', successRate: 12.3, totalCalls: 45 },
  { id: '5', url: 'https://api.example.com/email-opened', eventType: 'email.opened', status: 'inactive', lastTriggered: '2024-02-10 14:20', successRate: 100, totalCalls: 3456 },
];

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 [selectedWebhook, setSelectedWebhook] = useState<Webhook | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredWebhooks = useMemo(() => {
    if (!debouncedSearch) return mockWebhooks;
    const term = debouncedSearch.toLowerCase();
    return mockWebhooks.filter(w => w.url.toLowerCase().includes(term) || w.eventType.toLowerCase().includes(term));
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockWebhooks.length,
    active: mockWebhooks.filter(w => w.status === 'active').length,
    failed: mockWebhooks.filter(w => w.status === 'failed').length,
    totalCalls: mockWebhooks.reduce((sum, w) => sum + w.totalCalls, 0),
  }), []);

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

  const handleSelectWebhook = (webhook: Webhook) => {
    setSelectedWebhook(webhook);
    addToast(`Viewing webhook for ${webhook.eventType}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Webhook Manager</h1>
        <p>Webhook subscriptions, event types</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Webhooks</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Failed</div>
          <div className="stat-value">{stats.failed}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Calls</div>
          <div className="stat-value">{(stats.totalCalls / 1000).toFixed(1)}K</div>
        </div>
      </div>

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

      {filteredWebhooks.length === 0 ? (
        <div className="empty-state">
          <h3>No webhooks found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>URL</th>
                <th>Event Type</th>
                <th>Status</th>
                <th>Success Rate</th>
                <th>Total Calls</th>
                <th>Last Triggered</th>
              </tr>
            </thead>
            <tbody>
              {filteredWebhooks.map(webhook => (
                <tr
                  key={webhook.id}
                  onClick={() => handleSelectWebhook(webhook)}
                  className={selectedWebhook?.id === webhook.id ? 'selected' : ''}
                >
                  <td style={{ maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis' }}>{webhook.url}</td>
                  <td>{webhook.eventType}</td>
                  <td>
                    <span className={`status-badge status-${webhook.status}`}>
                      {webhook.status}
                    </span>
                  </td>
                  <td>{webhook.successRate}%</td>
                  <td>{webhook.totalCalls.toLocaleString()}</td>
                  <td>{webhook.lastTriggered}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedWebhook && (
        <div className="detail-panel">
          <h3>Webhook Details</h3>
          <div className="detail-grid">
            <div><strong>URL:</strong> {selectedWebhook.url}</div>
            <div><strong>Event Type:</strong> {selectedWebhook.eventType}</div>
            <div><strong>Status:</strong> {selectedWebhook.status}</div>
            <div><strong>Success Rate:</strong> {selectedWebhook.successRate}%</div>
            <div><strong>Total Calls:</strong> {selectedWebhook.totalCalls.toLocaleString()}</div>
            <div><strong>Last Triggered:</strong> {selectedWebhook.lastTriggered}</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;
