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

interface Email {
  id: string;
  subject: string;
  campaign: string;
  sent: number;
  delivered: number;
  opens: number;
  clicks: number;
  bounces: number;
  sentDate: string;
}

const mockEmails: Email[] = [
  { id: '1', subject: 'Monthly Newsletter', campaign: 'Newsletter', sent: 10000, delivered: 9800, opens: 3920, clicks: 784, bounces: 200, sentDate: '2024-02-10' },
  { id: '2', subject: 'Product Launch', campaign: 'Product', sent: 5000, delivered: 4950, opens: 2475, clicks: 990, bounces: 50, sentDate: '2024-02-12' },
  { id: '3', subject: 'Customer Survey', campaign: 'Engagement', sent: 8000, delivered: 7920, opens: 3168, clicks: 950, bounces: 80, sentDate: '2024-02-11' },
  { id: '4', subject: 'Flash Sale Alert', campaign: 'Promotion', sent: 15000, delivered: 14850, opens: 7425, clicks: 2227, bounces: 150, sentDate: '2024-02-13' },
  { id: '5', subject: 'Webinar Invitation', campaign: 'Events', sent: 3000, delivered: 2970, opens: 1485, clicks: 445, bounces: 30, sentDate: '2024-02-09' },
];

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

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredEmails = useMemo(() => {
    if (!debouncedSearch) return mockEmails;
    const term = debouncedSearch.toLowerCase();
    return mockEmails.filter(e =>
      e.subject.toLowerCase().includes(term) ||
      e.campaign.toLowerCase().includes(term)
    );
  }, [debouncedSearch]);

  const stats = useMemo(() => {
    const totalSent = mockEmails.reduce((sum, e) => sum + e.sent, 0);
    const totalOpens = mockEmails.reduce((sum, e) => sum + e.opens, 0);
    const totalClicks = mockEmails.reduce((sum, e) => sum + e.clicks, 0);
    const totalDelivered = mockEmails.reduce((sum, e) => sum + e.delivered, 0);
    return {
      totalSent,
      openRate: ((totalOpens / totalDelivered) * 100).toFixed(1),
      clickRate: ((totalClicks / totalDelivered) * 100).toFixed(1),
      deliveryRate: ((totalDelivered / totalSent) * 100).toFixed(1),
    };
  }, []);

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

  const handleSelectEmail = (email: Email) => {
    setSelectedEmail(email);
    addToast(`Viewing ${email.subject}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Email Dashboard</h1>
        <p>Track marketing email performance and engagement</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Sent</div>
          <div className="stat-value">{(stats.totalSent / 1000).toFixed(0)}K</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Delivery Rate</div>
          <div className="stat-value">{stats.deliveryRate}%</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Open Rate</div>
          <div className="stat-value">{stats.openRate}%</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Click Rate</div>
          <div className="stat-value">{stats.clickRate}%</div>
        </div>
      </div>

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

      {filteredEmails.length === 0 ? (
        <div className="empty-state">
          <h3>No emails found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Subject</th>
                <th>Campaign</th>
                <th>Sent</th>
                <th>Delivered</th>
                <th>Opens</th>
                <th>Clicks</th>
                <th>Open Rate</th>
                <th>Click Rate</th>
              </tr>
            </thead>
            <tbody>
              {filteredEmails.map(email => (
                <tr
                  key={email.id}
                  onClick={() => handleSelectEmail(email)}
                  className={selectedEmail?.id === email.id ? 'selected' : ''}
                >
                  <td>{email.subject}</td>
                  <td>{email.campaign}</td>
                  <td>{email.sent.toLocaleString()}</td>
                  <td>{email.delivered.toLocaleString()}</td>
                  <td>{email.opens.toLocaleString()}</td>
                  <td>{email.clicks.toLocaleString()}</td>
                  <td>{((email.opens / email.delivered) * 100).toFixed(1)}%</td>
                  <td>{((email.clicks / email.delivered) * 100).toFixed(1)}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedEmail && (
        <div className="detail-panel">
          <h3>Email Details</h3>
          <div className="detail-grid">
            <div><strong>Subject:</strong> {selectedEmail.subject}</div>
            <div><strong>Campaign:</strong> {selectedEmail.campaign}</div>
            <div><strong>Sent:</strong> {selectedEmail.sent.toLocaleString()}</div>
            <div><strong>Delivered:</strong> {selectedEmail.delivered.toLocaleString()}</div>
            <div><strong>Opens:</strong> {selectedEmail.opens.toLocaleString()}</div>
            <div><strong>Clicks:</strong> {selectedEmail.clicks.toLocaleString()}</div>
            <div><strong>Bounces:</strong> {selectedEmail.bounces.toLocaleString()}</div>
            <div><strong>Sent Date:</strong> {selectedEmail.sentDate}</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;
