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

interface Company {
  id: string;
  name: string;
  domain: string;
  industry: string;
  employees: number;
  revenue: string;
  contactCount: number;
  dealCount: number;
}

const mockCompanies: Company[] = [
  { id: '1', name: 'Acme Corp', domain: 'acme.com', industry: 'Technology', employees: 500, revenue: '$5M', contactCount: 12, dealCount: 3 },
  { id: '2', name: 'TechCo', domain: 'techco.io', industry: 'Software', employees: 250, revenue: '$2.5M', contactCount: 8, dealCount: 5 },
  { id: '3', name: 'StartupXYZ', domain: 'startupxyz.com', industry: 'SaaS', employees: 50, revenue: '$500K', contactCount: 15, dealCount: 2 },
  { id: '4', name: 'BigCorp', domain: 'bigcorp.com', industry: 'Enterprise', employees: 2000, revenue: '$50M', contactCount: 25, dealCount: 10 },
  { id: '5', name: 'MediumBiz', domain: 'mediumbiz.net', industry: 'Services', employees: 150, revenue: '$1.5M', contactCount: 10, dealCount: 4 },
];

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

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

const useToast = () => {
  const [toasts, setToasts] = useState<Toast[]>([]);
  const addToast = useCallback((message: string, type: Toast['type'] = 'info') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  }, []);
  return { toasts, addToast };
};

const App = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCompany, setSelectedCompany] = useState<Company | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredCompanies = useMemo(() => {
    if (!debouncedSearch) return mockCompanies;
    const term = debouncedSearch.toLowerCase();
    return mockCompanies.filter(c =>
      c.name.toLowerCase().includes(term) ||
      c.domain.toLowerCase().includes(term) ||
      c.industry.toLowerCase().includes(term)
    );
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockCompanies.length,
    totalContacts: mockCompanies.reduce((sum, c) => sum + c.contactCount, 0),
    totalDeals: mockCompanies.reduce((sum, c) => sum + c.dealCount, 0),
    totalEmployees: mockCompanies.reduce((sum, c) => sum + c.employees, 0),
  }), []);

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

  const handleSelectCompany = (company: Company) => {
    setSelectedCompany(company);
    addToast(`Viewing ${company.name}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Company Directory</h1>
        <p>Browse and manage company accounts</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Companies</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Contacts</div>
          <div className="stat-value">{stats.totalContacts}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Deals</div>
          <div className="stat-value">{stats.totalDeals}</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 companies..."
          value={searchTerm}
          onChange={handleSearch}
          className="search-input"
        />
        {isPending && <span className="search-loading">Searching...</span>}
      </div>

      {filteredCompanies.length === 0 ? (
        <div className="empty-state">
          <h3>No companies found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Company Name</th>
                <th>Domain</th>
                <th>Industry</th>
                <th>Employees</th>
                <th>Revenue</th>
                <th>Contacts</th>
                <th>Deals</th>
              </tr>
            </thead>
            <tbody>
              {filteredCompanies.map(company => (
                <tr
                  key={company.id}
                  onClick={() => handleSelectCompany(company)}
                  className={selectedCompany?.id === company.id ? 'selected' : ''}
                >
                  <td>{company.name}</td>
                  <td>{company.domain}</td>
                  <td>{company.industry}</td>
                  <td>{company.employees}</td>
                  <td>{company.revenue}</td>
                  <td>{company.contactCount}</td>
                  <td>{company.dealCount}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedCompany && (
        <div className="detail-panel">
          <h3>Company Details</h3>
          <div className="detail-grid">
            <div><strong>Name:</strong> {selectedCompany.name}</div>
            <div><strong>Domain:</strong> {selectedCompany.domain}</div>
            <div><strong>Industry:</strong> {selectedCompany.industry}</div>
            <div><strong>Employees:</strong> {selectedCompany.employees}</div>
            <div><strong>Revenue:</strong> {selectedCompany.revenue}</div>
            <div><strong>Associated Contacts:</strong> {selectedCompany.contactCount}</div>
            <div><strong>Associated Deals:</strong> {selectedCompany.dealCount}</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;
