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 Order = {
  id: string;
  orderNumber: string;
  customer: string;
  total: number;
  status: 'pending' | 'processing' | 'fulfilled' | 'cancelled';
  fulfillmentStatus: 'unfulfilled' | 'partial' | 'fulfilled';
  date: string;
  items: number;
};

const mockOrders: Order[] = [
  { id: 'o1', orderNumber: '#1001', customer: 'John Doe', total: 156.99, status: 'fulfilled', fulfillmentStatus: 'fulfilled', date: '2024-02-12', items: 3 },
  { id: 'o2', orderNumber: '#1002', customer: 'Jane Smith', total: 89.50, status: 'processing', fulfillmentStatus: 'partial', date: '2024-02-13', items: 2 },
  { id: 'o3', orderNumber: '#1003', customer: 'Bob Johnson', total: 234.00, status: 'pending', fulfillmentStatus: 'unfulfilled', date: '2024-02-13', items: 5 },
  { id: 'o4', orderNumber: '#1004', customer: 'Alice Williams', total: 45.99, status: 'fulfilled', fulfillmentStatus: 'fulfilled', date: '2024-02-11', items: 1 },
  { id: 'o5', orderNumber: '#1005', customer: 'Charlie Brown', total: 320.00, status: 'processing', fulfillmentStatus: 'unfulfilled', date: '2024-02-13', items: 4 },
  { id: 'o6', orderNumber: '#1006', customer: 'Diana Prince', total: 125.50, status: 'cancelled', fulfillmentStatus: 'unfulfilled', date: '2024-02-10', items: 2 },
  { id: 'o7', orderNumber: '#1007', customer: 'Ethan Hunt', total: 67.99, status: 'fulfilled', fulfillmentStatus: 'fulfilled', date: '2024-02-12', items: 3 },
  { id: 'o8', orderNumber: '#1008', customer: 'Fiona Green', total: 199.00, status: 'processing', fulfillmentStatus: 'partial', date: '2024-02-13', items: 2 },
];

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

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredOrders = useMemo(() => {
    return mockOrders.filter(o => {
      const matchesSearch = o.orderNumber.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
                           o.customer.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'all' || o.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => ({
    total: mockOrders.length,
    pending: mockOrders.filter(o => o.status === 'pending').length,
    revenue: mockOrders.filter(o => o.status !== 'cancelled').reduce((sum, o) => sum + o.total, 0),
    unfulfilled: mockOrders.filter(o => o.fulfillmentStatus === 'unfulfilled').length,
  }), []);

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

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Order Management</h1>
        <p>Track and manage customer orders</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Orders</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Pending</div>
          <div className="stat-value" style={{ color: stats.pending > 0 ? '#f59e0b' : 'inherit' }}>
            {stats.pending}
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Revenue</div>
          <div className="stat-value">${stats.revenue.toLocaleString()}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Unfulfilled</div>
          <div className="stat-value" style={{ color: stats.unfulfilled > 0 ? '#ef4444' : 'inherit' }}>
            {stats.unfulfilled}
          </div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search orders..."
          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="pending">Pending</option>
          <option value="processing">Processing</option>
          <option value="fulfilled">Fulfilled</option>
          <option value="cancelled">Cancelled</option>
        </select>
      </div>

      {filteredOrders.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📦</div>
          <h3>No orders found</h3>
          <p>Try adjusting your search or filters</p>
        </div>
      ) : (
        <div className="data-table" style={{ opacity: isPending ? 0.6 : 1 }}>
          <table>
            <thead>
              <tr>
                <th>Order</th>
                <th>Customer</th>
                <th>Date</th>
                <th>Items</th>
                <th>Total</th>
                <th>Status</th>
                <th>Fulfillment</th>
              </tr>
            </thead>
            <tbody>
              {filteredOrders.map(order => (
                <tr key={order.id}>
                  <td className="order-number">{order.orderNumber}</td>
                  <td>{order.customer}</td>
                  <td>{order.date}</td>
                  <td>{order.items}</td>
                  <td className="order-total">${order.total.toFixed(2)}</td>
                  <td>
                    <span className={`status-badge status-${order.status}`}>
                      {order.status}
                    </span>
                  </td>
                  <td>
                    <span className={`fulfillment-badge fulfillment-${order.fulfillmentStatus}`}>
                      {order.fulfillmentStatus}
                    </span>
                  </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>
  );
}
