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

interface Report {
  id: string;
  name: string;
  type: 'sales' | 'marketing' | 'service' | 'custom';
  dataSource: string;
  lastRun: string;
  frequency: 'daily' | 'weekly' | 'monthly' | 'on-demand';
  recipients: number;
}

const mockReports: Report[] = [
  { id: '1', name: 'Monthly Sales Performance', type: 'sales', dataSource: 'Deals', lastRun: '2024-02-13 08:00', frequency: 'monthly', recipients: 5 },
  { id: '2', name: 'Email Campaign Analytics', type: 'marketing', dataSource: 'Emails', lastRun: '2024-02-13 09:00', frequency: 'weekly', recipients: 8 },
  { id: '3', name: 'Support Ticket Trends', type: 'service', dataSource: 'Tickets', lastRun: '2024-02-13 10:00', frequency: 'daily', recipients: 4 },
  { id: '4', name: 'Lead Conversion Funnel', type: 'marketing', dataSource: 'Contacts', lastRun: '2024-02-12 16:00', frequency: 'weekly', recipients: 6 },
  { id: '5', name: 'Custom Revenue Dashboard', type: 'custom', dataSource: 'Multiple', lastRun: '2024-02-13 07:00', frequency: 'on-demand', recipients: 3 },
];

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

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredReports = useMemo(() => {
    if (!debouncedSearch) return mockReports;
    const term = debouncedSearch.toLowerCase();
    return mockReports.filter(r => r.name.toLowerCase().includes(term));
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockReports.length,
    sales: mockReports.filter(r => r.type === 'sales').length,
    marketing: mockReports.filter(r => r.type === 'marketing').length,
    custom: mockReports.filter(r => r.type === 'custom').length,
  }), []);

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

  const handleSelectReport = (report: Report) => {
    setSelectedReport(report);
    addToast(`Viewing ${report.name}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Reporting Center</h1>
        <p>Custom reports, filters, data visualization</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Reports</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Sales Reports</div>
          <div className="stat-value">{stats.sales}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Marketing Reports</div>
          <div className="stat-value">{stats.marketing}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Custom Reports</div>
          <div className="stat-value">{stats.custom}</div>
        </div>
      </div>

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

      {filteredReports.length === 0 ? (
        <div className="empty-state">
          <h3>No reports found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Type</th>
                <th>Data Source</th>
                <th>Frequency</th>
                <th>Recipients</th>
                <th>Last Run</th>
              </tr>
            </thead>
            <tbody>
              {filteredReports.map(report => (
                <tr
                  key={report.id}
                  onClick={() => handleSelectReport(report)}
                  className={selectedReport?.id === report.id ? 'selected' : ''}
                >
                  <td>{report.name}</td>
                  <td>
                    <span className={`status-badge status-${report.type}`}>
                      {report.type}
                    </span>
                  </td>
                  <td>{report.dataSource}</td>
                  <td>{report.frequency}</td>
                  <td>{report.recipients}</td>
                  <td>{report.lastRun}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedReport && (
        <div className="detail-panel">
          <h3>Report Details</h3>
          <div className="detail-grid">
            <div><strong>Name:</strong> {selectedReport.name}</div>
            <div><strong>Type:</strong> {selectedReport.type}</div>
            <div><strong>Data Source:</strong> {selectedReport.dataSource}</div>
            <div><strong>Frequency:</strong> {selectedReport.frequency}</div>
            <div><strong>Recipients:</strong> {selectedReport.recipients}</div>
            <div><strong>Last Run:</strong> {selectedReport.lastRun}</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;
