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 mockCustomers = [
  { id: 'cus_1', name: 'Acme Corporation', email: 'billing@acme.com', balance: 0, paymentMethods: 2, created: Date.now() - 86400000 * 30 },
  { id: 'cus_2', name: 'TechStart Inc', email: 'finance@techstart.io', balance: -500, paymentMethods: 1, created: Date.now() - 86400000 * 60 },
  { id: 'cus_3', name: 'Global Ventures', email: 'payments@globalv.com', balance: 1200, paymentMethods: 3, created: Date.now() - 86400000 * 15 },
  { id: 'cus_4', name: 'Startup Labs', email: 'admin@startuplabs.dev', balance: 0, paymentMethods: 1, created: Date.now() - 86400000 * 45 },
  { id: 'cus_5', name: 'Enterprise Co', email: 'billing@enterprise.com', balance: -2500, paymentMethods: 4, created: Date.now() - 86400000 * 90 },
  { id: 'cus_6', name: 'Innovation Hub', email: 'finance@innovhub.com', balance: 0, paymentMethods: 2, created: Date.now() - 86400000 * 7 },
];

const App = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCustomer, setSelectedCustomer] = useState<typeof mockCustomers[0] | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();

  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredCustomers = useMemo(() => {
    return mockCustomers.filter((customer) =>
      customer.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      customer.email.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      customer.id.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const stats = useMemo(() => {
    const totalCustomers = mockCustomers.length;
    const withBalance = mockCustomers.filter((c) => c.balance !== 0).length;
    const avgPaymentMethods = (mockCustomers.reduce((sum, c) => sum + c.paymentMethods, 0) / totalCustomers).toFixed(1);
    return { totalCustomers, withBalance, avgPaymentMethods };
  }, []);

  const handleViewDetails = (customer: typeof mockCustomers[0]) => {
    startTransition(() => {
      setSelectedCustomer(customer);
      show(`Viewing details for ${customer.name}`, 'info');
    });
  };

  const formatBalance = (balance: number) => {
    const formatted = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(Math.abs(balance) / 100);
    return balance < 0 ? `-${formatted}` : formatted;
  };

  const formatDate = (timestamp: number) => {
    return new Date(timestamp).toLocaleDateString();
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Customer Manager</h1>
        <p className="subtitle">Search, view, and manage customer accounts</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Customers</div>
          <div className="stat-value">{stats.totalCustomers}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">With Balance</div>
          <div className="stat-value stat-warning">{stats.withBalance}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Avg Payment Methods</div>
          <div className="stat-value stat-success">{stats.avgPaymentMethods}</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>

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

      <div className="layout-split">
        <div className="data-grid">
          {filteredCustomers.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 customers found</h3>
              <p>Try a different search term</p>
            </div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Customer</th>
                  <th>Email</th>
                  <th>Balance</th>
                  <th>Payment Methods</th>
                  <th>Created</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {filteredCustomers.map((customer) => (
                  <tr key={customer.id}>
                    <td>
                      <div className="customer-info">
                        <strong>{customer.name}</strong>
                        <span className="mono">{customer.id}</span>
                      </div>
                    </td>
                    <td>{customer.email}</td>
                    <td className={customer.balance < 0 ? 'amount negative' : 'amount'}>
                      {formatBalance(customer.balance)}
                    </td>
                    <td>{customer.paymentMethods}</td>
                    <td className="date">{formatDate(customer.created)}</td>
                    <td>
                      <button className="btn-action" onClick={() => handleViewDetails(customer)}>
                        View
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {selectedCustomer && (
          <div className="detail-panel">
            <div className="detail-header">
              <h3>Customer Details</h3>
              <button className="btn-close" onClick={() => setSelectedCustomer(null)}>×</button>
            </div>
            <div className="detail-content">
              <div className="detail-row">
                <span className="detail-label">Customer ID</span>
                <span className="mono">{selectedCustomer.id}</span>
              </div>
              <div className="detail-row">
                <span className="detail-label">Name</span>
                <span>{selectedCustomer.name}</span>
              </div>
              <div className="detail-row">
                <span className="detail-label">Email</span>
                <span>{selectedCustomer.email}</span>
              </div>
              <div className="detail-row">
                <span className="detail-label">Balance</span>
                <span className={selectedCustomer.balance < 0 ? 'negative' : ''}>
                  {formatBalance(selectedCustomer.balance)}
                </span>
              </div>
              <div className="detail-row">
                <span className="detail-label">Payment Methods</span>
                <span>{selectedCustomer.paymentMethods} active</span>
              </div>
              <div className="detail-row">
                <span className="detail-label">Created</span>
                <span>{formatDate(selectedCustomer.created)}</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>
  );
};

export default App;
