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 mockPaymentLinks = [
  { id: 'plink_1', url: 'https://buy.stripe.com/test_abc123', product: 'Pro Plan', amount: 9900, active: true, purchases: 45 },
  { id: 'plink_2', url: 'https://buy.stripe.com/test_xyz789', product: 'Enterprise', amount: 29900, active: true, purchases: 12 },
  { id: 'plink_3', url: 'https://buy.stripe.com/test_def456', product: 'Starter', amount: 2900, active: false, purchases: 89 },
];

const mockCheckoutSessions = [
  { id: 'cs_1', customer: 'john@example.com', amount: 9900, status: 'complete', paymentStatus: 'paid', created: Date.now() - 3600000 },
  { id: 'cs_2', customer: 'jane@example.com', amount: 29900, status: 'open', paymentStatus: 'unpaid', created: Date.now() - 7200000 },
  { id: 'cs_3', customer: 'bob@example.com', amount: 2900, status: 'expired', paymentStatus: 'unpaid', created: Date.now() - 86400000 },
];

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

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredLinks = useMemo(() => {
    return mockPaymentLinks.filter((link) =>
      link.id.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      link.product.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

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

  const stats = useMemo(() => {
    const totalLinks = mockPaymentLinks.length;
    const activeLinks = mockPaymentLinks.filter((l) => l.active).length;
    const totalSessions = mockCheckoutSessions.length;
    const completeSessions = mockCheckoutSessions.filter((s) => s.status === 'complete').length;
    return { totalLinks, activeLinks, totalSessions, completeSessions };
  }, []);

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

  const formatAmount = (amount: number) => {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount / 100);
  };

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

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Checkout Manager</h1>
        <p className="subtitle">Manage payment links and checkout sessions</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Payment Links</div>
          <div className="stat-value">{stats.totalLinks}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active Links</div>
          <div className="stat-value stat-success">{stats.activeLinks}</div>
        </div>
        <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">Complete Sessions</div>
          <div className="stat-value stat-success">{stats.completeSessions}</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 === 'links' ? 'active' : ''}`}
            onClick={() => handleViewChange('links')}
          >
            Payment Links
          </button>
          <button
            className={`filter-btn ${view === 'sessions' ? 'active' : ''}`}
            onClick={() => handleViewChange('sessions')}
          >
            Checkout Sessions
          </button>
        </div>
      </div>

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

      <div className="data-grid">
        {view === 'links' ? (
          filteredLinks.length === 0 ? (
            <div className="empty-state">
              <h3>No payment links found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Link ID</th>
                  <th>Product</th>
                  <th>Amount</th>
                  <th>URL</th>
                  <th>Status</th>
                  <th>Purchases</th>
                </tr>
              </thead>
              <tbody>
                {filteredLinks.map((link) => (
                  <tr key={link.id}>
                    <td className="mono">{link.id}</td>
                    <td>{link.product}</td>
                    <td className="amount">{formatAmount(link.amount)}</td>
                    <td className="mono">{link.url}</td>
                    <td>
                      <span className={`badge ${link.active ? 'badge-active' : 'badge-inactive'}`}>
                        {link.active ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td>{link.purchases}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )
        ) : (
          filteredSessions.length === 0 ? (
            <div className="empty-state">
              <h3>No checkout sessions found</h3>
              <p>Try adjusting your search</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Session ID</th>
                  <th>Customer</th>
                  <th>Amount</th>
                  <th>Status</th>
                  <th>Payment Status</th>
                  <th>Created</th>
                </tr>
              </thead>
              <tbody>
                {filteredSessions.map((session) => (
                  <tr key={session.id}>
                    <td className="mono">{session.id}</td>
                    <td>{session.customer}</td>
                    <td className="amount">{formatAmount(session.amount)}</td>
                    <td>
                      <span className={`badge badge-${session.status}`}>{session.status}</span>
                    </td>
                    <td>
                      <span className={`badge badge-${session.paymentStatus}`}>{session.paymentStatus}</span>
                    </td>
                    <td className="date">{formatDate(session.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;
