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

interface Opportunity {
  id: string;
  name: string;
  accountName: string;
  stage: 'Prospecting' | 'Qualification' | 'Proposal' | 'Negotiation' | 'Closed Won' | 'Closed Lost';
  amount: number;
  probability: number;
  closeDate: 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 mockOpportunities: Opportunity[] = [
  { id: 'o001', name: 'Enterprise License', accountName: 'Acme Corp', stage: 'Proposal', amount: 500000, probability: 70, closeDate: '2025-03-15', owner: 'Jane Smith' },
  { id: 'o002', name: 'Cloud Migration', accountName: 'Global Inc', stage: 'Negotiation', amount: 850000, probability: 90, closeDate: '2025-02-28', owner: 'John Doe' },
  { id: 'o003', name: 'Professional Services', accountName: 'TechStart', stage: 'Qualification', amount: 125000, probability: 40, closeDate: '2025-04-10', owner: 'Alice Johnson' },
  { id: 'o004', name: 'Support Renewal', accountName: 'Premier LLC', stage: 'Prospecting', amount: 75000, probability: 20, closeDate: '2025-05-01', owner: 'Bob Wilson' },
  { id: 'o005', name: 'Platform Expansion', accountName: 'Enterprise Solutions', stage: 'Closed Won', amount: 1200000, probability: 100, closeDate: '2025-01-30', owner: 'Jane Smith' },
  { id: 'o006', name: 'Training Package', accountName: 'SmallBiz', stage: 'Closed Lost', amount: 25000, probability: 0, closeDate: '2025-01-15', owner: 'Alice Johnson' },
];

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

  const filteredOpps = useMemo(() => {
    return mockOpportunities.filter(opp => {
      const matchesSearch = opp.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
                           opp.accountName.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesStage = stageFilter === 'All' || opp.stage === stageFilter;
      return matchesSearch && matchesStage;
    });
  }, [debouncedSearch, stageFilter]);

  const stats = useMemo(() => {
    const openOpps = mockOpportunities.filter(o => !o.stage.includes('Closed'));
    return {
      total: openOpps.length,
      totalValue: openOpps.reduce((sum, o) => sum + o.amount, 0),
      weightedValue: openOpps.reduce((sum, o) => sum + (o.amount * o.probability / 100), 0),
      avgDealSize: Math.round(openOpps.reduce((sum, o) => sum + o.amount, 0) / openOpps.length),
    };
  }, []);

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

  const handleViewDetails = (opp: Opportunity) => {
    show(`Viewing ${opp.name}`);
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Opportunity Pipeline</h1>
        <p>Track pipeline, stages, amounts, and probability</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Open Opportunities</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Pipeline</div>
          <div className="stat-value">${(stats.totalValue / 1000000).toFixed(1)}M</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Weighted Pipeline</div>
          <div className="stat-value">${(stats.weightedValue / 1000000).toFixed(1)}M</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Avg Deal Size</div>
          <div className="stat-value">${(stats.avgDealSize / 1000).toFixed(0)}K</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search opportunities by name or account..."
          value={searchQuery}
          onChange={handleSearch}
          className="search-input"
        />
        <select 
          value={stageFilter} 
          onChange={(e) => setStageFilter(e.target.value)}
          className="filter-select"
        >
          <option value="All">All Stages</option>
          <option value="Prospecting">Prospecting</option>
          <option value="Qualification">Qualification</option>
          <option value="Proposal">Proposal</option>
          <option value="Negotiation">Negotiation</option>
          <option value="Closed Won">Closed Won</option>
          <option value="Closed Lost">Closed Lost</option>
        </select>
      </div>

      {filteredOpps.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">💼</div>
          <h3>No opportunities found</h3>
          <p>Try adjusting your filters</p>
        </div>
      ) : (
        <div className="data-grid">
          <table>
            <thead>
              <tr>
                <th>Opportunity Name</th>
                <th>Account</th>
                <th>Stage</th>
                <th>Amount</th>
                <th>Probability</th>
                <th>Close Date</th>
                <th>Owner</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody className={isPending ? 'loading' : ''}>
              {filteredOpps.map(opp => (
                <tr key={opp.id}>
                  <td><strong>{opp.name}</strong></td>
                  <td>{opp.accountName}</td>
                  <td><span className={`stage-badge stage-${opp.stage.toLowerCase().replace(/\s/g, '-')}`}>{opp.stage}</span></td>
                  <td>${(opp.amount / 1000).toFixed(0)}K</td>
                  <td>
                    <div className="probability-bar">
                      <div className="probability-fill" style={{ width: `${opp.probability}%` }}>
                        {opp.probability}%
                      </div>
                    </div>
                  </td>
                  <td>{opp.closeDate}</td>
                  <td>{opp.owner}</td>
                  <td>
                    <button 
                      className="btn-primary"
                      onClick={() => handleViewDetails(opp)}
                    >
                      View
                    </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;
