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

interface Quote {
  id: string;
  quoteName: string;
  company: string;
  amount: number;
  status: 'draft' | 'sent' | 'accepted' | 'declined';
  validUntil: string;
  createdDate: string;
  lineItems: number;
}

const mockQuotes: Quote[] = [
  { id: '1', quoteName: 'Enterprise Package Q1', company: 'Acme Corp', amount: 125000, status: 'sent', validUntil: '2024-02-28', createdDate: '2024-02-10', lineItems: 5 },
  { id: '2', quoteName: 'Professional License', company: 'TechCo', amount: 45000, status: 'accepted', validUntil: '2024-02-25', createdDate: '2024-02-08', lineItems: 3 },
  { id: '3', quoteName: 'Starter Package', company: 'StartupXYZ', amount: 12000, status: 'draft', validUntil: '2024-03-15', createdDate: '2024-02-12', lineItems: 2 },
  { id: '4', quoteName: 'Custom Implementation', company: 'BigCorp', amount: 250000, status: 'sent', validUntil: '2024-03-01', createdDate: '2024-02-11', lineItems: 8 },
  { id: '5', quoteName: 'Annual Renewal', company: 'MediumBiz', amount: 78000, status: 'accepted', validUntil: '2024-02-20', createdDate: '2024-02-05', lineItems: 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 [selectedQuote, setSelectedQuote] = useState<Quote | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredQuotes = useMemo(() => {
    if (!debouncedSearch) return mockQuotes;
    const term = debouncedSearch.toLowerCase();
    return mockQuotes.filter(q => q.quoteName.toLowerCase().includes(term) || q.company.toLowerCase().includes(term));
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockQuotes.length,
    totalValue: mockQuotes.reduce((sum, q) => sum + q.amount, 0),
    accepted: mockQuotes.filter(q => q.status === 'accepted').length,
    sent: mockQuotes.filter(q => q.status === 'sent').length,
  }), []);

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

  const handleSelectQuote = (quote: Quote) => {
    setSelectedQuote(quote);
    addToast(`Viewing ${quote.quoteName}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Quote Builder</h1>
        <p>Quotes overview, status, amounts</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Quotes</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Value</div>
          <div className="stat-value">${(stats.totalValue / 1000).toFixed(0)}K</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Accepted</div>
          <div className="stat-value">{stats.accepted}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Sent</div>
          <div className="stat-value">{stats.sent}</div>
        </div>
      </div>

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

      {filteredQuotes.length === 0 ? (
        <div className="empty-state">
          <h3>No quotes found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Quote Name</th>
                <th>Company</th>
                <th>Amount</th>
                <th>Status</th>
                <th>Valid Until</th>
                <th>Created</th>
              </tr>
            </thead>
            <tbody>
              {filteredQuotes.map(quote => (
                <tr
                  key={quote.id}
                  onClick={() => handleSelectQuote(quote)}
                  className={selectedQuote?.id === quote.id ? 'selected' : ''}
                >
                  <td>{quote.quoteName}</td>
                  <td>{quote.company}</td>
                  <td>${(quote.amount / 1000).toFixed(0)}K</td>
                  <td>
                    <span className={`status-badge status-${quote.status}`}>
                      {quote.status}
                    </span>
                  </td>
                  <td>{quote.validUntil}</td>
                  <td>{quote.createdDate}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedQuote && (
        <div className="detail-panel">
          <h3>Quote Details</h3>
          <div className="detail-grid">
            <div><strong>Quote Name:</strong> {selectedQuote.quoteName}</div>
            <div><strong>Company:</strong> {selectedQuote.company}</div>
            <div><strong>Amount:</strong> ${selectedQuote.amount.toLocaleString()}</div>
            <div><strong>Status:</strong> {selectedQuote.status}</div>
            <div><strong>Line Items:</strong> {selectedQuote.lineItems}</div>
            <div><strong>Valid Until:</strong> {selectedQuote.validUntil}</div>
            <div><strong>Created:</strong> {selectedQuote.createdDate}</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;
