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

interface Deal {
  id: string;
  name: string;
  amount: number;
  stage: string;
  company: string;
  closeDate: string;
  probability: number;
}

const stages = ['Prospecting', 'Qualified', 'Proposal', 'Negotiation', 'Closed Won', 'Closed Lost'];

const mockDeals: Deal[] = [
  { id: '1', name: 'Enterprise Deal A', amount: 50000, stage: 'Prospecting', company: 'Acme Corp', closeDate: '2024-03-15', probability: 20 },
  { id: '2', name: 'Mid-Market Deal B', amount: 25000, stage: 'Qualified', company: 'TechCo', closeDate: '2024-03-10', probability: 40 },
  { id: '3', name: 'SMB Deal C', amount: 10000, stage: 'Proposal', company: 'StartupXYZ', closeDate: '2024-02-28', probability: 60 },
  { id: '4', name: 'Enterprise Deal D', amount: 75000, stage: 'Negotiation', company: 'BigCorp', closeDate: '2024-03-20', probability: 80 },
  { id: '5', name: 'Mid-Market Deal E', amount: 30000, stage: 'Proposal', company: 'MediumBiz', closeDate: '2024-03-05', probability: 50 },
];

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 [selectedDeal, setSelectedDeal] = useState<Deal | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredDeals = useMemo(() => {
    if (!debouncedSearch) return mockDeals;
    const term = debouncedSearch.toLowerCase();
    return mockDeals.filter(d =>
      d.name.toLowerCase().includes(term) ||
      d.company.toLowerCase().includes(term) ||
      d.stage.toLowerCase().includes(term)
    );
  }, [debouncedSearch]);

  const dealsByStage = useMemo(() => {
    return stages.map(stage => ({
      stage,
      deals: filteredDeals.filter(d => d.stage === stage),
      totalValue: filteredDeals
        .filter(d => d.stage === stage)
        .reduce((sum, d) => sum + d.amount, 0),
    }));
  }, [filteredDeals]);

  const stats = useMemo(() => ({
    totalDeals: mockDeals.length,
    totalValue: mockDeals.reduce((sum, d) => sum + d.amount, 0),
    avgDealSize: mockDeals.reduce((sum, d) => sum + d.amount, 0) / mockDeals.length,
    weightedValue: mockDeals.reduce((sum, d) => sum + (d.amount * d.probability / 100), 0),
  }), []);

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

  const handleSelectDeal = (deal: Deal) => {
    setSelectedDeal(deal);
    addToast(`Viewing ${deal.name}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Deal Pipeline</h1>
        <p>Visual pipeline view with stage tracking</p>
      </header>

      <div className="stats-grid">
        <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">Pipeline Value</div>
          <div className="stat-value">${(stats.totalValue / 1000).toFixed(0)}K</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 className="stat-card">
          <div className="stat-label">Weighted Value</div>
          <div className="stat-value">${(stats.weightedValue / 1000).toFixed(0)}K</div>
        </div>
      </div>

      <div className="search-bar">
        <input
          type="text"
          placeholder="Search deals..."
          value={searchTerm}
          onChange={handleSearch}
          className="search-input"
        />
        {isPending && <span className="search-loading">Searching...</span>}
      </div>

      {filteredDeals.length === 0 ? (
        <div className="empty-state">
          <h3>No deals found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="pipeline-view">
          {dealsByStage.map(({ stage, deals, totalValue }) => (
            <div key={stage} className="pipeline-stage">
              <div className="stage-header">
                <h3>{stage}</h3>
                <div className="stage-meta">
                  <span>{deals.length} deals</span>
                  <span>${(totalValue / 1000).toFixed(0)}K</span>
                </div>
              </div>
              <div className="deal-cards">
                {deals.map(deal => (
                  <div
                    key={deal.id}
                    className={`deal-card ${selectedDeal?.id === deal.id ? 'selected' : ''}`}
                    onClick={() => handleSelectDeal(deal)}
                  >
                    <div className="deal-name">{deal.name}</div>
                    <div className="deal-company">{deal.company}</div>
                    <div className="deal-amount">${(deal.amount / 1000).toFixed(0)}K</div>
                    <div className="deal-probability">{deal.probability}% probability</div>
                    <div className="deal-date">Close: {deal.closeDate}</div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

      {selectedDeal && (
        <div className="detail-panel">
          <h3>Deal Details</h3>
          <div className="detail-grid">
            <div><strong>Name:</strong> {selectedDeal.name}</div>
            <div><strong>Company:</strong> {selectedDeal.company}</div>
            <div><strong>Amount:</strong> ${selectedDeal.amount.toLocaleString()}</div>
            <div><strong>Stage:</strong> {selectedDeal.stage}</div>
            <div><strong>Probability:</strong> {selectedDeal.probability}%</div>
            <div><strong>Close Date:</strong> {selectedDeal.closeDate}</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;
