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 mockEvents = [
  { id: 'evt_1', type: 'payment_intent.succeeded', data: '{"id":"pi_123","amount":5000}', created: Date.now() - 3600000 },
  { id: 'evt_2', type: 'charge.failed', data: '{"id":"ch_456","error":"card_declined"}', created: Date.now() - 7200000 },
  { id: 'evt_3', type: 'customer.created', data: '{"id":"cus_789","email":"john@example.com"}', created: Date.now() - 10800000 },
  { id: 'evt_4', type: 'subscription.updated', data: '{"id":"sub_012","status":"active"}', created: Date.now() - 14400000 },
  { id: 'evt_5', type: 'invoice.paid', data: '{"id":"in_345","amount_paid":9900}', created: Date.now() - 18000000 },
  { id: 'evt_6', type: 'payout.paid', data: '{"id":"po_678","amount":125000}', created: Date.now() - 21600000 },
];

const App = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [typeFilter, setTypeFilter] = useState('all');
  const [selectedEvent, setSelectedEvent] = useState<typeof mockEvents[0] | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const eventTypes = useMemo(() => {
    const types = [...new Set(mockEvents.map((e) => e.type))];
    return types;
  }, []);

  const filteredEvents = useMemo(() => {
    return mockEvents.filter((event) => {
      const matchesSearch =
        event.id.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        event.type.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        event.data.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesType = typeFilter === 'all' || event.type === typeFilter;
      return matchesSearch && matchesType;
    });
  }, [debouncedSearch, typeFilter]);

  const stats = useMemo(() => {
    const totalEvents = mockEvents.length;
    const last24h = mockEvents.filter((e) => e.created > Date.now() - 86400000).length;
    const uniqueTypes = eventTypes.length;
    return { totalEvents, last24h, uniqueTypes };
  }, [eventTypes]);

  const handleFilterChange = (type: string) => {
    startTransition(() => {
      setTypeFilter(type);
      show(`Filtered by: ${type}`, 'info');
    });
  };

  const handleViewEvent = (event: typeof mockEvents[0]) => {
    setSelectedEvent(event);
    show(`Viewing event ${event.id}`, 'info');
  };

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

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Event Log</h1>
        <p className="subtitle">Real-time event stream with type filters and payload viewer</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Events</div>
          <div className="stat-value">{stats.totalEvents}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Last 24 Hours</div>
          <div className="stat-value stat-success">{stats.last24h}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Event Types</div>
          <div className="stat-value stat-warning">{stats.uniqueTypes}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder="Search events..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          <button
            className={`filter-btn ${typeFilter === 'all' ? 'active' : ''}`}
            onClick={() => handleFilterChange('all')}
          >
            All
          </button>
          {eventTypes.slice(0, 4).map((type) => (
            <button
              key={type}
              className={`filter-btn ${typeFilter === type ? 'active' : ''}`}
              onClick={() => handleFilterChange(type)}
            >
              {type.split('.')[0]}
            </button>
          ))}
        </div>
      </div>

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

      <div className="layout-split">
        <div className="data-grid">
          {filteredEvents.length === 0 ? (
            <div className="empty-state">
              <h3>No events found</h3>
              <p>Try adjusting your search or filter</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Event ID</th>
                  <th>Type</th>
                  <th>Created</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {filteredEvents.map((event) => (
                  <tr key={event.id}>
                    <td className="mono">{event.id}</td>
                    <td>{event.type}</td>
                    <td className="date">{formatDate(event.created)}</td>
                    <td>
                      <button className="btn-action btn-sm" onClick={() => handleViewEvent(event)}>
                        View
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {selectedEvent && (
          <div className="detail-panel">
            <div className="detail-header">
              <h3>Event Payload</h3>
              <button className="btn-close" onClick={() => setSelectedEvent(null)}>×</button>
            </div>
            <div className="detail-content">
              <div className="detail-row">
                <span className="detail-label">Event ID</span>
                <span className="mono">{selectedEvent.id}</span>
              </div>
              <div className="detail-row">
                <span className="detail-label">Type</span>
                <span>{selectedEvent.type}</span>
              </div>
              <div className="detail-row">
                <span className="detail-label">Created</span>
                <span>{formatDate(selectedEvent.created)}</span>
              </div>
              <div className="payload-viewer">
                <h4>Payload Data</h4>
                <pre>{JSON.stringify(JSON.parse(selectedEvent.data), null, 2)}</pre>
              </div>
            </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;
