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

function 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;
}

type Toast = { id: number; message: string; type: 'success' | 'error' };

function useToast() {
  const [toasts, setToasts] = useState<Toast[]>([]);

  const showToast = useCallback((message: string, type: 'success' | 'error' = 'success') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  }, []);

  return { toasts, showToast };
}

type Customer = {
  id: string;
  name: string;
  email: string;
  phone: string;
  totalSpent: number;
  orders: number;
  lastOrder: string;
  status: 'active' | 'inactive';
};

const mockCustomers: Customer[] = [
  { id: 'c1', name: 'John Doe', email: 'john@example.com', phone: '555-0101', totalSpent: 1250.00, orders: 12, lastOrder: '2024-02-10', status: 'active' },
  { id: 'c2', name: 'Jane Smith', email: 'jane@example.com', phone: '555-0102', totalSpent: 890.50, orders: 7, lastOrder: '2024-02-12', status: 'active' },
  { id: 'c3', name: 'Bob Johnson', email: 'bob@example.com', phone: '555-0103', totalSpent: 2340.00, orders: 18, lastOrder: '2024-02-13', status: 'active' },
  { id: 'c4', name: 'Alice Williams', email: 'alice@example.com', phone: '555-0104', totalSpent: 450.99, orders: 4, lastOrder: '2024-01-28', status: 'inactive' },
  { id: 'c5', name: 'Charlie Brown', email: 'charlie@example.com', phone: '555-0105', totalSpent: 3200.00, orders: 22, lastOrder: '2024-02-11', status: 'active' },
  { id: 'c6', name: 'Diana Prince', email: 'diana@example.com', phone: '555-0106', totalSpent: 1255.50, orders: 9, lastOrder: '2024-02-09', status: 'active' },
  { id: 'c7', name: 'Ethan Hunt', email: 'ethan@example.com', phone: '555-0107', totalSpent: 670.99, orders: 5, lastOrder: '2024-01-15', status: 'inactive' },
  { id: 'c8', name: 'Fiona Green', email: 'fiona@example.com', phone: '555-0108', totalSpent: 1990.00, orders: 14, lastOrder: '2024-02-13', status: 'active' },
];

export default function App() {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all');
  const [isPending, startTransition] = useTransition();
  const { toasts, showToast } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

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

  const stats = useMemo(() => ({
    total: mockCustomers.length,
    active: mockCustomers.filter(c => c.status === 'active').length,
    totalRevenue: mockCustomers.reduce((sum, c) => sum + c.totalSpent, 0),
    avgOrderValue: mockCustomers.reduce((sum, c) => sum + c.totalSpent, 0) / mockCustomers.reduce((sum, c) => sum + c.orders, 0),
  }), []);

  const handleSearch = (value: string) => {
    startTransition(() => setSearchQuery(value));
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Customer Directory</h1>
        <p>Manage customer relationships and history</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">
          <div className="stat-label">Active</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Revenue</div>
          <div className="stat-value">${stats.totalRevenue.toLocaleString()}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Avg Order Value</div>
          <div className="stat-value">${stats.avgOrderValue.toFixed(2)}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search customers..."
          value={searchQuery}
          onChange={(e) => handleSearch(e.target.value)}
          className="search-input"
        />
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value as any)}
          className="filter-select"
        >
          <option value="all">All Status</option>
          <option value="active">Active</option>
          <option value="inactive">Inactive</option>
        </select>
      </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" style={{ opacity: isPending ? 0.6 : 1 }}>
          {filteredCustomers.map(customer => (
            <div key={customer.id} className="data-card">
              <div className="customer-avatar">
                {customer.name.split(' ').map(n => n[0]).join('')}
              </div>
              <div className="data-card-content">
                <h3>{customer.name}</h3>
                <p className="customer-email">{customer.email}</p>
                <p className="customer-phone">{customer.phone}</p>
                <div className="customer-stats">
                  <div>
                    <span className="stat-label-sm">Total Spent</span>
                    <span className="stat-value-sm">${customer.totalSpent.toLocaleString()}</span>
                  </div>
                  <div>
                    <span className="stat-label-sm">Orders</span>
                    <span className="stat-value-sm">{customer.orders}</span>
                  </div>
                </div>
                <div className="customer-footer">
                  <span className="last-order">Last: {customer.lastOrder}</span>
                  <span className={`status-badge status-${customer.status}`}>
                    {customer.status}
                  </span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="toast-container">
        {toasts.map(toast => (
          <div key={toast.id} className={`toast toast-${toast.type}`}>
            {toast.message}
          </div>
        ))}
      </div>
    </div>
  );
}
