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

const useDebounce = <T,>(value: T, delay: number): T => {
  const [debouncedValue, setDebouncedValue] = useState(value);

  React.useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);

  return debouncedValue;
};

const useToast = () => {
  const [toast, setToast] = useState<string | null>(null);

  const showToast = (message: string) => {
    setToast(message);
    setTimeout(() => setToast(null), 3000);
  };

  return { toast, showToast };
};

const mockCustomers = [
  { id: 'C001', name: 'Acme Corp', email: 'billing@acme.com', phone: '555-0101', balance: 12500.00, status: 'active' },
  { id: 'C002', name: 'Tech Solutions Inc', email: 'ap@techsolutions.com', phone: '555-0102', balance: 8750.50, status: 'active' },
  { id: 'C003', name: 'Global Enterprises', email: 'finance@global.com', phone: '555-0103', balance: 0, status: 'active' },
  { id: 'C004', name: 'Startup LLC', email: 'admin@startup.co', phone: '555-0104', balance: 3200.00, status: 'active' },
  { id: 'C005', name: 'Enterprise Co', email: 'payments@enterprise.com', phone: '555-0105', balance: 15000.00, status: 'inactive' },
  { id: 'C006', name: 'Small Biz Inc', email: 'owner@smallbiz.com', phone: '555-0106', balance: 1850.75, status: 'active' },
];

type Customer = typeof mockCustomers[0];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [isPending, startTransition] = useTransition();
  const { toast, showToast } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredCustomers = useMemo(() => {
    return mockCustomers.filter((customer) => {
      const matchesSearch =
        customer.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        customer.email.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
        customer.id.includes(debouncedSearch);
      const matchesFilter = filterStatus === 'all' || customer.status === filterStatus;
      return matchesSearch && matchesFilter;
    });
  }, [debouncedSearch, filterStatus]);

  const stats = useMemo(() => {
    const total = mockCustomers.length;
    const active = mockCustomers.filter(c => c.status === 'active').length;
    const inactive = mockCustomers.filter(c => c.status === 'inactive').length;
    const totalBalance = mockCustomers.reduce((sum, c) => sum + c.balance, 0);
    return { total, active, inactive, totalBalance };
  }, []);

  const handleFilterChange = (status: string) => {
    startTransition(() => {
      setFilterStatus(status);
      showToast(`Filter: ${status === 'all' ? 'All Customers' : status.charAt(0).toUpperCase() + status.slice(1)}`);
    });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Customer Manager</h1>
        <p>Customer directory with balances and contact information</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Customers</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card stat-success">
          <div className="stat-label">Active</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card stat-warning">
          <div className="stat-label">Inactive</div>
          <div className="stat-value">{stats.inactive}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Balance</div>
          <div className="stat-value">${stats.totalBalance.toLocaleString('en-US', { minimumFractionDigits: 2 })}</div>
        </div>
      </div>

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

      {filteredCustomers.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">👥</div>
          <h3>No customers found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className={`data-grid ${isPending ? 'loading' : ''}`}>
          <table>
            <thead>
              <tr>
                <th>Customer ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Balance</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filteredCustomers.map((customer) => (
                <tr key={customer.id}>
                  <td className="customer-id">{customer.id}</td>
                  <td className="customer-name">{customer.name}</td>
                  <td>{customer.email}</td>
                  <td>{customer.phone}</td>
                  <td className="amount">${customer.balance.toLocaleString('en-US', { minimumFractionDigits: 2 })}</td>
                  <td>
                    <span className={`status-badge status-${customer.status}`}>
                      {customer.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {toast && <div className="toast">{toast}</div>}
    </div>
  );
};

export default App;
