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

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;
};

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

const mockEndpoints = [
  { id: 'we_1', url: 'https://api.example.com/stripe/webhooks', status: 'enabled', events: ['payment_intent.succeeded', 'charge.failed'], deliveries: 1250, failures: 12 },
  { id: 'we_2', url: 'https://app.mysite.com/webhooks/stripe', status: 'enabled', events: ['customer.created', 'subscription.updated'], deliveries: 850, failures: 3 },
  { id: 'we_3', url: 'https://webhook.site/test', status: 'disabled', events: ['invoice.paid'], deliveries: 45, failures: 45 },
];

const mockDeliveries = [
  { id: 'evt_1', event: 'payment_intent.succeeded', endpoint: 'we_1', status: 'succeeded', attempts: 1, created: Date.now() - 3600000 },
  { id: 'evt_2', event: 'charge.failed', endpoint: 'we_1', status: 'failed', attempts: 3, created: Date.now() - 7200000 },
  { id: 'evt_3', event: 'customer.created', endpoint: 'we_2', status: 'succeeded', attempts: 1, created: Date.now() - 10800000 },
  { id: 'evt_4', event: 'subscription.updated', endpoint: 'we_2', status: 'succeeded', attempts: 1, created: Date.now() - 14400000 },
];

const App = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [view, setView] = useState<'endpoints' | 'deliveries'>('endpoints');
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredEndpoints = useMemo(() => {
    return mockEndpoints.filter((endpoint) =>
      endpoint.url.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      endpoint.id.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const filteredDeliveries = useMemo(() => {
    return mockDeliveries.filter((delivery) =>
      delivery.event.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      delivery.id.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const stats = useMemo(() => {
    const totalEndpoints = mockEndpoints.length;
    const activeEndpoints = mockEndpoints.filter((e) => e.status === 'enabled').length;
    const totalDeliveries = mockDeliveries.length;
    const failedDeliveries = mockDeliveries.filter((d) => d.status === 'failed').length;
    return { totalEndpoints, activeEndpoints, totalDeliveries, failedDeliveries };
  }, []);

  const handleViewChange = (newView: 'endpoints' | 'deliveries') => {
    startTransition(() => {
      setView(newView);
      show(`Switched to ${newView} view`, 'info');
    });
  };

  const formatDate = (timestamp: number) => {
    return new Date(timestamp).toLocaleString();
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Webhook Manager</h1>
        <p className="subtitle">Manage webhook endpoints and monitor delivery logs</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Endpoints</div>
          <div className="stat-value">{stats.totalEndpoints}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active Endpoints</div>
          <div className="stat-value stat-success">{stats.activeEndpoints}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Deliveries</div>
          <div className="stat-value">{stats.totalDeliveries}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Failed Deliveries</div>
          <div className="stat-value stat-danger">{stats.failedDeliveries}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder={`Search ${view}...`}
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          <button
            className={`filter-btn ${view === 'endpoints' ? 'active' : ''}`}
            onClick={() => handleViewChange('endpoints')}
          >
            Endpoints
          </button>
          <button
            className={`filter-btn ${view === 'deliveries' ? 'active' : ''}`}
            onClick={() => handleViewChange('deliveries')}
          >
            Delivery Logs
          </button>
        </div>
      </div>

      {isPending && <div className="loading-indicator">Switching view...</div>}

      <div className="data-grid">
        {view === 'endpoints' ? (
          filteredEndpoints.length === 0 ? (
            <div className="empty-state">
              <h3>No endpoints found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Endpoint ID</th>
                  <th>URL</th>
                  <th>Status</th>
                  <th>Events</th>
                  <th>Deliveries</th>
                  <th>Failures</th>
                </tr>
              </thead>
              <tbody>
                {filteredEndpoints.map((endpoint) => (
                  <tr key={endpoint.id}>
                    <td className="mono">{endpoint.id}</td>
                    <td className="mono">{endpoint.url}</td>
                    <td>
                      <span className={`badge badge-${endpoint.status}`}>{endpoint.status}</span>
                    </td>
                    <td>{endpoint.events.length} events</td>
                    <td>{endpoint.deliveries}</td>
                    <td className={endpoint.failures > 0 ? 'stat-danger' : ''}>{endpoint.failures}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )
        ) : (
          filteredDeliveries.length === 0 ? (
            <div className="empty-state">
              <h3>No delivery logs found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Event ID</th>
                  <th>Event Type</th>
                  <th>Endpoint</th>
                  <th>Status</th>
                  <th>Attempts</th>
                  <th>Created</th>
                </tr>
              </thead>
              <tbody>
                {filteredDeliveries.map((delivery) => (
                  <tr key={delivery.id}>
                    <td className="mono">{delivery.id}</td>
                    <td>{delivery.event}</td>
                    <td className="mono">{delivery.endpoint}</td>
                    <td>
                      <span className={`badge badge-${delivery.status}`}>{delivery.status}</span>
                    </td>
                    <td>{delivery.attempts}</td>
                    <td className="date">{formatDate(delivery.created)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )
        )}
      </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;
