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

interface Lead {
  id: string;
  name: string;
  company: string;
  status: 'New' | 'Working' | 'Qualified' | 'Unqualified';
  source: string;
  email: string;
  rating: 'Hot' | 'Warm' | 'Cold';
}

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 mockLeads: Lead[] = [
  { id: 'l001', name: 'John Smith', company: 'TechCorp', status: 'New', source: 'Web', email: 'jsmith@techcorp.com', rating: 'Hot' },
  { id: 'l002', name: 'Emma Wilson', company: 'StartupXYZ', status: 'Working', source: 'Referral', email: 'ewilson@startup.com', rating: 'Warm' },
  { id: 'l003', name: 'David Lee', company: 'Enterprise Inc', status: 'Qualified', source: 'Trade Show', email: 'dlee@enterprise.com', rating: 'Hot' },
  { id: 'l004', name: 'Lisa Chen', company: 'SmallBiz LLC', status: 'Working', source: 'Cold Call', email: 'lchen@smallbiz.com', rating: 'Warm' },
  { id: 'l005', name: 'Mark Johnson', company: 'Global Corp', status: 'New', source: 'Web', email: 'mjohnson@global.com', rating: 'Hot' },
  { id: 'l006', name: 'Sara Davis', company: 'Local Shop', status: 'Unqualified', source: 'Social Media', email: 'sdavis@local.com', rating: 'Cold' },
];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('All');
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();
  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredLeads = useMemo(() => {
    return mockLeads.filter(lead => {
      const matchesSearch = lead.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
                           lead.company.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStatus = statusFilter === 'All' || lead.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [debouncedSearch, statusFilter]);

  const stats = useMemo(() => ({
    total: mockLeads.length,
    qualified: mockLeads.filter(l => l.status === 'Qualified').length,
    hot: mockLeads.filter(l => l.rating === 'Hot').length,
    conversionRate: Math.round((mockLeads.filter(l => l.status === 'Qualified').length / mockLeads.length) * 100),
  }), []);

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

  const handleConvert = (lead: Lead) => {
    show(`Converting lead: ${lead.name}`);
  };

  const getRatingColor = (rating: string) => {
    switch(rating) {
      case 'Hot': return '#ef4444';
      case 'Warm': return '#f59e0b';
      case 'Cold': return '#3b82f6';
      default: return '#6b7280';
    }
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Lead Tracker</h1>
        <p>Track leads, status, and conversion funnel</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Leads</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Qualified</div>
          <div className="stat-value">{stats.qualified}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Hot Leads</div>
          <div className="stat-value">{stats.hot}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Conversion Rate</div>
          <div className="stat-value">{stats.conversionRate}%</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search leads by name or company..."
          value={searchQuery}
          onChange={handleSearch}
          className="search-input"
        />
        <select 
          value={statusFilter} 
          onChange={(e) => setStatusFilter(e.target.value)}
          className="filter-select"
        >
          <option value="All">All Status</option>
          <option value="New">New</option>
          <option value="Working">Working</option>
          <option value="Qualified">Qualified</option>
          <option value="Unqualified">Unqualified</option>
        </select>
      </div>

      {filteredLeads.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">🎯</div>
          <h3>No leads found</h3>
          <p>Try adjusting your filters</p>
        </div>
      ) : (
        <div className="data-grid">
          <table>
            <thead>
              <tr>
                <th>Name</th>
                <th>Company</th>
                <th>Status</th>
                <th>Source</th>
                <th>Rating</th>
                <th>Email</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody className={isPending ? 'loading' : ''}>
              {filteredLeads.map(lead => (
                <tr key={lead.id}>
                  <td><strong>{lead.name}</strong></td>
                  <td>{lead.company}</td>
                  <td><span className={`status-badge status-${lead.status.toLowerCase()}`}>{lead.status}</span></td>
                  <td>{lead.source}</td>
                  <td>
                    <span className="rating-badge" style={{ backgroundColor: getRatingColor(lead.rating) }}>
                      {lead.rating}
                    </span>
                  </td>
                  <td>{lead.email}</td>
                  <td>
                    <button 
                      className="btn-primary"
                      onClick={() => handleConvert(lead)}
                    >
                      Convert
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
