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 mockPayouts = [
  { id: 'po_1', amount: 125000, currency: 'usd', status: 'paid', arrivalDate: Date.now() - 86400000 * 1, bankAccount: '****4242', created: Date.now() - 86400000 * 3 },
  { id: 'po_2', amount: 87500, currency: 'usd', status: 'in_transit', arrivalDate: Date.now() + 86400000 * 1, bankAccount: '****4242', created: Date.now() - 86400000 * 1 },
  { id: 'po_3', amount: 220000, currency: 'usd', status: 'pending', arrivalDate: Date.now() + 86400000 * 2, bankAccount: '****4242', created: Date.now() },
  { id: 'po_4', amount: 95000, currency: 'eur', status: 'paid', arrivalDate: Date.now() - 86400000 * 8, bankAccount: '****5555', created: Date.now() - 86400000 * 10 },
  { id: 'po_5', amount: 150000, currency: 'usd', status: 'failed', arrivalDate: Date.now() - 86400000 * 2, bankAccount: '****4242', created: Date.now() - 86400000 * 4 },
];

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 filteredPayouts = useMemo(() => {
    return mockPayouts.filter((payout) => {
      const matchesSearch = payout.id.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        payout.bankAccount.includes(debouncedSearch);
      const matchesStatus = statusFilter === 'all' || payout.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => {
    const totalPaid = mockPayouts.filter((p) => p.status === 'paid').reduce((sum, p) => sum + p.amount, 0);
    const pending = mockPayouts.filter((p) => p.status === 'pending').length;
    const inTransit = mockPayouts.filter((p) => p.status === 'in_transit').length;
    const failed = mockPayouts.filter((p) => p.status === 'failed').length;
    return { totalPaid, pending, inTransit, failed };
  }, []);

  const handleFilterChange = (status: string) => {
    startTransition(() => {
      setStatusFilter(status);
      show(`Filtered by: ${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).toLocaleDateString();
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Payout Dashboard</h1>
        <p className="subtitle">Track payout schedule, amounts, and bank accounts</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Paid</div>
          <div className="stat-value stat-success">{formatAmount(stats.totalPaid, 'usd')}</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">In Transit</div>
          <div className="stat-value">{stats.inTransit}</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 payouts..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          {['all', 'paid', 'in_transit', 'pending', 'failed'].map((status) => (
            <button
              key={status}
              className={`filter-btn ${statusFilter === status ? 'active' : ''}`}
              onClick={() => handleFilterChange(status)}
            >
              {status.replace('_', ' ').charAt(0).toUpperCase() + status.slice(1).replace('_', ' ')}
            </button>
          ))}
        </div>
      </div>

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

      <div className="data-grid">
        {filteredPayouts.length === 0 ? (
          <div className="empty-state">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <rect x="2" y="5" width="20" height="14" rx="2" strokeWidth="2" />
              <line x1="2" y1="10" x2="22" y2="10" strokeWidth="2" />
            </svg>
            <h3>No payouts found</h3>
            <p>Try adjusting your search or filter</p>
          </div>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>Payout ID</th>
                <th>Amount</th>
                <th>Status</th>
                <th>Bank Account</th>
                <th>Arrival Date</th>
                <th>Created</th>
              </tr>
            </thead>
            <tbody>
              {filteredPayouts.map((payout) => (
                <tr key={payout.id}>
                  <td className="mono">{payout.id}</td>
                  <td className="amount">{formatAmount(payout.amount, payout.currency)}</td>
                  <td>
                    <span className={`badge badge-${payout.status}`}>
                      {payout.status.replace('_', ' ')}
                    </span>
                  </td>
                  <td className="mono">{payout.bankAccount}</td>
                  <td className="date">{formatDate(payout.arrivalDate)}</td>
                  <td className="date">{formatDate(payout.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;
