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

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

// Mock Data
const mockPayments = [
  { id: 'pi_1', amount: 5000, currency: 'usd', status: 'succeeded', customer: 'John Doe', created: Date.now() - 3600000 },
  { id: 'pi_2', amount: 12500, currency: 'usd', status: 'succeeded', customer: 'Jane Smith', created: Date.now() - 7200000 },
  { id: 'pi_3', amount: 3000, currency: 'usd', status: 'pending', customer: 'Bob Johnson', created: Date.now() - 1800000 },
  { id: 'pi_4', amount: 8900, currency: 'eur', status: 'succeeded', customer: 'Alice Brown', created: Date.now() - 14400000 },
  { id: 'pi_5', amount: 15000, currency: 'usd', status: 'failed', customer: 'Charlie Wilson', created: Date.now() - 900000 },
  { id: 'pi_6', amount: 4200, currency: 'gbp', status: 'succeeded', customer: 'Eva Davis', created: Date.now() - 10800000 },
];

const App = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredPayments = useMemo(() => {
    return mockPayments.filter((payment) => {
      const matchesSearch =
        payment.id.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        payment.customer.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || payment.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => {
    const total = mockPayments.reduce((sum, p) => sum + (p.status === 'succeeded' ? p.amount : 0), 0);
    const succeeded = mockPayments.filter((p) => p.status === 'succeeded').length;
    const pending = mockPayments.filter((p) => p.status === 'pending').length;
    const failed = mockPayments.filter((p) => p.status === 'failed').length;
    return { total, succeeded, pending, failed };
  }, []);

  const handleFilterChange = (status: string) => {
    startTransition(() => {
      setStatusFilter(status);
      show(`Filter applied: ${status}`, 'info');
    });
  };

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

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

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Payments Dashboard</h1>
        <p className="subtitle">Monitor payment intents and transaction status</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Revenue</div>
          <div className="stat-value">{formatAmount(stats.total, 'usd')}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Succeeded</div>
          <div className="stat-value stat-success">{stats.succeeded}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Pending</div>
          <div className="stat-value stat-warning">{stats.pending}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Failed</div>
          <div className="stat-value stat-danger">{stats.failed}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder="Search by ID or customer..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          {['all', 'succeeded', 'pending', 'failed'].map((status) => (
            <button
              key={status}
              className={`filter-btn ${statusFilter === status ? 'active' : ''}`}
              onClick={() => handleFilterChange(status)}
            >
              {status.charAt(0).toUpperCase() + status.slice(1)}
            </button>
          ))}
        </div>
      </div>

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

      <div className="data-grid">
        {filteredPayments.length === 0 ? (
          <div className="empty-state">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <circle cx="12" cy="12" r="10" strokeWidth="2" />
              <line x1="12" y1="8" x2="12" y2="12" strokeWidth="2" />
              <line x1="12" y1="16" x2="12.01" y2="16" strokeWidth="2" />
            </svg>
            <h3>No payments found</h3>
            <p>Try adjusting your search or filter</p>
          </div>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>Payment ID</th>
                <th>Customer</th>
                <th>Amount</th>
                <th>Status</th>
                <th>Created</th>
              </tr>
            </thead>
            <tbody>
              {filteredPayments.map((payment) => (
                <tr key={payment.id}>
                  <td className="mono">{payment.id}</td>
                  <td>{payment.customer}</td>
                  <td className="amount">{formatAmount(payment.amount, payment.currency)}</td>
                  <td>
                    <span className={`badge badge-${payment.status}`}>{payment.status}</span>
                  </td>
                  <td className="date">{formatDate(payment.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;
