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

interface Account {
  id: string;
  name: string;
  industry: string;
  revenue: number;
  employees: number;
  parentId?: string;
  owner: string;
}

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 }>>([]);
  const show = (message: string) => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  };
  return { toasts, show };
};

const mockAccounts: Account[] = [
  { id: '001', name: 'Acme Corporation', industry: 'Technology', revenue: 5000000, employees: 250, owner: 'Jane Smith' },
  { id: '002', name: 'Global Industries', industry: 'Manufacturing', revenue: 12000000, employees: 1200, owner: 'John Doe', parentId: '001' },
  { id: '003', name: 'Tech Innovations Inc', industry: 'Technology', revenue: 3200000, employees: 85, owner: 'Alice Johnson' },
  { id: '004', name: 'Premier Services LLC', industry: 'Services', revenue: 890000, employees: 42, owner: 'Bob Wilson' },
  { id: '005', name: 'Enterprise Solutions', industry: 'Software', revenue: 7500000, employees: 320, owner: 'Jane Smith' },
];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedAccount, setSelectedAccount] = useState<Account | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();
  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredAccounts = useMemo(() => {
    return mockAccounts.filter(acc =>
      acc.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      acc.industry.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockAccounts.length,
    avgRevenue: Math.round(mockAccounts.reduce((sum, a) => sum + a.revenue, 0) / mockAccounts.length),
    totalEmployees: mockAccounts.reduce((sum, a) => sum + a.employees, 0),
  }), []);

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    startTransition(() => {
      setSearchQuery(e.target.value);
    });
  };

  const handleViewDetails = (account: Account) => {
    setSelectedAccount(account);
    show(`Viewing ${account.name}`);
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Account Manager</h1>
        <p>Manage accounts, hierarchies, and details</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Accounts</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Avg Revenue</div>
          <div className="stat-value">${(stats.avgRevenue / 1000000).toFixed(1)}M</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Employees</div>
          <div className="stat-value">{stats.totalEmployees.toLocaleString()}</div>
        </div>
      </div>

      <div className="search-bar">
        <input
          type="text"
          placeholder="Search accounts by name or industry..."
          value={searchQuery}
          onChange={handleSearch}
          className="search-input"
        />
      </div>

      {filteredAccounts.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📊</div>
          <h3>No accounts found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table>
            <thead>
              <tr>
                <th>Account Name</th>
                <th>Industry</th>
                <th>Revenue</th>
                <th>Employees</th>
                <th>Owner</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody className={isPending ? 'loading' : ''}>
              {filteredAccounts.map(account => (
                <tr key={account.id}>
                  <td>
                    <strong>{account.name}</strong>
                    {account.parentId && <span className="badge">Child</span>}
                  </td>
                  <td>{account.industry}</td>
                  <td>${(account.revenue / 1000000).toFixed(2)}M</td>
                  <td>{account.employees}</td>
                  <td>{account.owner}</td>
                  <td>
                    <button 
                      className="btn-primary"
                      onClick={() => handleViewDetails(account)}
                    >
                      View
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedAccount && (
        <div className="modal-overlay" onClick={() => setSelectedAccount(null)}>
          <div className="modal-content" onClick={e => e.stopPropagation()}>
            <h2>{selectedAccount.name}</h2>
            <div className="detail-grid">
              <div><strong>Industry:</strong> {selectedAccount.industry}</div>
              <div><strong>Revenue:</strong> ${(selectedAccount.revenue / 1000000).toFixed(2)}M</div>
              <div><strong>Employees:</strong> {selectedAccount.employees}</div>
              <div><strong>Owner:</strong> {selectedAccount.owner}</div>
              {selectedAccount.parentId && <div><strong>Parent Account:</strong> Yes</div>}
            </div>
            <button className="btn-secondary" onClick={() => setSelectedAccount(null)}>Close</button>
          </div>
        </div>
      )}

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

export default App;
