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

interface Pipeline {
  id: string;
  name: string;
  type: 'deal' | 'ticket';
  stages: string[];
  activeDeals: number;
  createdDate: string;
}

const mockPipelines: Pipeline[] = [
  { id: '1', name: 'Sales Pipeline', type: 'deal', stages: ['Prospecting', 'Qualified', 'Proposal', 'Negotiation', 'Closed Won'], activeDeals: 15, createdDate: '2024-01-01' },
  { id: '2', name: 'Enterprise Pipeline', type: 'deal', stages: ['Discovery', 'Technical Eval', 'Business Case', 'Procurement', 'Closed'], activeDeals: 8, createdDate: '2024-01-15' },
  { id: '3', name: 'Support Pipeline', type: 'ticket', stages: ['New', 'In Progress', 'Waiting', 'Resolved'], activeDeals: 23, createdDate: '2024-02-01' },
  { id: '4', name: 'Success Pipeline', type: 'ticket', stages: ['Onboarding', 'Training', 'Active', 'Renewal'], activeDeals: 12, createdDate: '2024-02-05' },
];

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 [typeFilter, setTypeFilter] = useState<string>('all');
  const [selectedPipeline, setSelectedPipeline] = useState<Pipeline | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredPipelines = useMemo(() => {
    let filtered = mockPipelines;
    
    if (debouncedSearch) {
      const term = debouncedSearch.toLowerCase();
      filtered = filtered.filter(p =>
        p.name.toLowerCase().includes(term)
      );
    }
    
    if (typeFilter !== 'all') {
      filtered = filtered.filter(p => p.type === typeFilter);
    }
    
    return filtered;
  }, [debouncedSearch, typeFilter]);

  const stats = useMemo(() => ({
    total: mockPipelines.length,
    dealPipelines: mockPipelines.filter(p => p.type === 'deal').length,
    ticketPipelines: mockPipelines.filter(p => p.type === 'ticket').length,
    totalActive: mockPipelines.reduce((sum, p) => sum + p.activeDeals, 0),
  }), []);

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

  const handleSelectPipeline = (pipeline: Pipeline) => {
    setSelectedPipeline(pipeline);
    addToast(`Viewing ${pipeline.name}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Pipeline Settings</h1>
        <p>Configure deal and ticket pipeline stages</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Pipelines</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Deal Pipelines</div>
          <div className="stat-value">{stats.dealPipelines}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Ticket Pipelines</div>
          <div className="stat-value">{stats.ticketPipelines}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active Items</div>
          <div className="stat-value">{stats.totalActive}</div>
        </div>
      </div>

      <div className="filter-bar">
        <input
          type="text"
          placeholder="Search pipelines..."
          value={searchTerm}
          onChange={handleSearch}
          className="search-input"
        />
        <select
          value={typeFilter}
          onChange={(e) => setTypeFilter(e.target.value)}
          className="filter-select"
        >
          <option value="all">All Types</option>
          <option value="deal">Deal Pipelines</option>
          <option value="ticket">Ticket Pipelines</option>
        </select>
        {isPending && <span className="search-loading">Filtering...</span>}
      </div>

      {filteredPipelines.length === 0 ? (
        <div className="empty-state">
          <h3>No pipelines found</h3>
          <p>Try adjusting your filters</p>
        </div>
      ) : (
        <div className="data-grid">
          {filteredPipelines.map(pipeline => (
            <div
              key={pipeline.id}
              className={`pipeline-card ${selectedPipeline?.id === pipeline.id ? 'selected' : ''}`}
              onClick={() => handleSelectPipeline(pipeline)}
            >
              <div className="pipeline-header">
                <h3>{pipeline.name}</h3>
                <span className={`type-badge type-${pipeline.type}`}>
                  {pipeline.type}
                </span>
              </div>
              <div className="pipeline-stats">
                <span>{pipeline.activeDeals} active</span>
                <span>{pipeline.stages.length} stages</span>
              </div>
              <div className="stages-preview">
                {pipeline.stages.map((stage, idx) => (
                  <div key={idx} className="stage-badge">{stage}</div>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

      {selectedPipeline && (
        <div className="detail-panel">
          <h3>Pipeline Details</h3>
          <div className="detail-grid">
            <div><strong>Name:</strong> {selectedPipeline.name}</div>
            <div><strong>Type:</strong> {selectedPipeline.type}</div>
            <div><strong>Active Items:</strong> {selectedPipeline.activeDeals}</div>
            <div><strong>Created:</strong> {selectedPipeline.createdDate}</div>
          </div>
          <h4 style={{ marginTop: '1rem', marginBottom: '0.5rem' }}>Stages</h4>
          <div className="stages-list">
            {selectedPipeline.stages.map((stage, idx) => (
              <div key={idx} className="stage-item">
                {idx + 1}. {stage}
              </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;
