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 mockPortalSessions = [
  { id: 'bps_1', customer: 'Acme Corp', configuration: 'Default', url: 'https://billing.stripe.com/session/test_abc123', created: Date.now() - 3600000, returnUrl: 'https://example.com/account' },
  { id: 'bps_2', customer: 'TechStart', configuration: 'Custom Portal', url: 'https://billing.stripe.com/session/test_xyz789', created: Date.now() - 7200000, returnUrl: 'https://techstart.io/billing' },
  { id: 'bps_3', customer: 'Global Ventures', configuration: 'Default', url: 'https://billing.stripe.com/session/test_def456', created: Date.now() - 14400000, returnUrl: 'https://globalventures.com/settings' },
];

const mockConfigurations = [
  { id: 'bpc_1', name: 'Default', features: ['update_payment_method', 'cancel_subscription', 'update_subscription'], active: true },
  { id: 'bpc_2', name: 'Custom Portal', features: ['update_payment_method', 'view_invoices'], active: true },
  { id: 'bpc_3', name: 'Limited Access', features: ['view_invoices'], active: false },
];

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

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredSessions = useMemo(() => {
    return mockPortalSessions.filter((session) =>
      session.customer.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      session.id.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const filteredConfigurations = useMemo(() => {
    return mockConfigurations.filter((config) =>
      config.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      config.id.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const stats = useMemo(() => {
    const totalSessions = mockPortalSessions.length;
    const last24h = mockPortalSessions.filter((s) => s.created > Date.now() - 86400000).length;
    const totalConfigs = mockConfigurations.length;
    const activeConfigs = mockConfigurations.filter((c) => c.active).length;
    return { totalSessions, last24h, totalConfigs, activeConfigs };
  }, []);

  const handleViewChange = (newView: 'sessions' | 'configurations') => {
    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>Billing Portal</h1>
        <p className="subtitle">Customer billing portal sessions and configurations</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Sessions</div>
          <div className="stat-value">{stats.totalSessions}</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">Total Configurations</div>
          <div className="stat-value">{stats.totalConfigs}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active Configurations</div>
          <div className="stat-value stat-success">{stats.activeConfigs}</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 === 'sessions' ? 'active' : ''}`}
            onClick={() => handleViewChange('sessions')}
          >
            Portal Sessions
          </button>
          <button
            className={`filter-btn ${view === 'configurations' ? 'active' : ''}`}
            onClick={() => handleViewChange('configurations')}
          >
            Configurations
          </button>
        </div>
      </div>

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

      <div className="data-grid">
        {view === 'sessions' ? (
          filteredSessions.length === 0 ? (
            <div className="empty-state">
              <h3>No portal sessions found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Session ID</th>
                  <th>Customer</th>
                  <th>Configuration</th>
                  <th>Created</th>
                  <th>Return URL</th>
                </tr>
              </thead>
              <tbody>
                {filteredSessions.map((session) => (
                  <tr key={session.id}>
                    <td className="mono">{session.id}</td>
                    <td>{session.customer}</td>
                    <td>{session.configuration}</td>
                    <td className="date">{formatDate(session.created)}</td>
                    <td className="mono">{session.returnUrl}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )
        ) : (
          filteredConfigurations.length === 0 ? (
            <div className="empty-state">
              <h3>No configurations found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Configuration ID</th>
                  <th>Name</th>
                  <th>Features</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {filteredConfigurations.map((config) => (
                  <tr key={config.id}>
                    <td className="mono">{config.id}</td>
                    <td><strong>{config.name}</strong></td>
                    <td>{config.features.length} features enabled</td>
                    <td>
                      <span className={`badge ${config.active ? 'badge-active' : 'badge-inactive'}`}>
                        {config.active ? 'Active' : 'Inactive'}
                      </span>
                    </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;
