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 mockAccounts = [
  { id: 'acct_1', email: 'partner1@example.com', type: 'express', status: 'active', balance: 125000, payoutsEnabled: true, created: Date.now() - 86400000 * 30 },
  { id: 'acct_2', email: 'partner2@example.com', type: 'standard', status: 'active', balance: 87500, payoutsEnabled: true, created: Date.now() - 86400000 * 60 },
  { id: 'acct_3', email: 'partner3@example.com', type: 'express', status: 'pending', balance: 0, payoutsEnabled: false, created: Date.now() - 86400000 * 5 },
  { id: 'acct_4', email: 'partner4@example.com', type: 'custom', status: 'restricted', balance: 45000, payoutsEnabled: false, created: Date.now() - 86400000 * 90 },
];

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

  const stats = useMemo(() => {
    const totalAccounts = mockAccounts.length;
    const activeAccounts = mockAccounts.filter((a) => a.status === 'active').length;
    const totalBalance = mockAccounts.reduce((sum, a) => sum + a.balance, 0);
    const payoutsEnabled = mockAccounts.filter((a) => a.payoutsEnabled).length;
    return { totalAccounts, activeAccounts, totalBalance, payoutsEnabled };
  }, []);

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

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Connect Dashboard</h1>
        <p className="subtitle">Manage connected accounts overview (Stripe Connect)</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Accounts</div>
          <div className="stat-value">{stats.totalAccounts}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active Accounts</div>
          <div className="stat-value stat-success">{stats.activeAccounts}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Balance</div>
          <div className="stat-value">{formatAmount(stats.totalBalance)}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Payouts Enabled</div>
          <div className="stat-value stat-warning">{stats.payoutsEnabled}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder="Search connected accounts..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <div className="filter-buttons">
          {['all', 'active', 'pending', 'restricted'].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">
        {filteredAccounts.length === 0 ? (
          <div className="empty-state">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" strokeWidth="2" />
              <circle cx="9" cy="7" r="4" strokeWidth="2" />
              <path d="M23 21v-2a4 4 0 0 0-3-3.87" strokeWidth="2" />
              <path d="M16 3.13a4 4 0 0 1 0 7.75" strokeWidth="2" />
            </svg>
            <h3>No connected accounts found</h3>
            <p>Try adjusting your search or filter</p>
          </div>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>Account ID</th>
                <th>Email</th>
                <th>Type</th>
                <th>Status</th>
                <th>Balance</th>
                <th>Payouts</th>
                <th>Created</th>
              </tr>
            </thead>
            <tbody>
              {filteredAccounts.map((account) => (
                <tr key={account.id}>
                  <td className="mono">{account.id}</td>
                  <td>{account.email}</td>
                  <td>
                    <span className="badge badge-active">{account.type}</span>
                  </td>
                  <td>
                    <span className={`badge badge-${account.status}`}>{account.status}</span>
                  </td>
                  <td className="amount">{formatAmount(account.balance)}</td>
                  <td>
                    <span className={`badge ${account.payoutsEnabled ? 'badge-succeeded' : 'badge-failed'}`}>
                      {account.payoutsEnabled ? 'Enabled' : 'Disabled'}
                    </span>
                  </td>
                  <td className="date">{formatDate(account.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;
