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

interface Report {
  id: string;
  name: string;
  folder: string;
  type: 'Tabular' | 'Summary' | 'Matrix';
  lastRun: string;
  records: number;
}

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;
};

const useToast = () => {
  const [toasts, setToasts] = useState<Array<{ id: number; message: string }>>([]);
  const show = (message: string) => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  };
  return { toasts, show };
};

const mockReports: Report[] = [
  { id: 'r001', name: 'Sales Pipeline Report', folder: 'Sales Reports', type: 'Summary', lastRun: '2025-02-13', records: 245 },
  { id: 'r002', name: 'Open Opportunities', folder: 'Sales Reports', type: 'Tabular', lastRun: '2025-02-12', records: 89 },
  { id: 'r003', name: 'Case Status Overview', folder: 'Service Reports', type: 'Matrix', lastRun: '2025-02-11', records: 342 },
  { id: 'r004', name: 'Lead Source Analysis', folder: 'Marketing Reports', type: 'Summary', lastRun: '2025-02-10', records: 567 },
  { id: 'r005', name: 'Account Revenue by Industry', folder: 'Executive Reports', type: 'Matrix', lastRun: '2025-02-09', records: 128 },
];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [typeFilter, setTypeFilter] = useState<string>('All');
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();
  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredReports = useMemo(() => {
    return mockReports.filter(report => {
      const matchesSearch = report.name.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
                           report.folder.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesType = typeFilter === 'All' || report.type === typeFilter;
      return matchesSearch && matchesType;
    });
  }, [debouncedSearch, typeFilter]);

  const stats = useMemo(() => ({
    total: mockReports.length,
    tabular: mockReports.filter(r => r.type === 'Tabular').length,
    summary: mockReports.filter(r => r.type === 'Summary').length,
    matrix: mockReports.filter(r => r.type === 'Matrix').length,
  }), []);

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

  const handleRunReport = (report: Report) => {
    show(`Running report: ${report.name}`);
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Report Viewer</h1>
        <p>Run and view reports, filters, tabular data</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">Tabular</div>
          <div className="stat-value">{stats.tabular}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Summary</div>
          <div className="stat-value">{stats.summary}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Matrix</div>
          <div className="stat-value">{stats.matrix}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search reports by name or folder..."
          value={searchQuery}
          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="Tabular">Tabular</option>
          <option value="Summary">Summary</option>
          <option value="Matrix">Matrix</option>
        </select>
      </div>

      {filteredReports.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📊</div>
          <h3>No reports found</h3>
          <p>Try adjusting your filters</p>
        </div>
      ) : (
        <div className="data-grid">
          <table>
            <thead>
              <tr>
                <th>Report Name</th>
                <th>Folder</th>
                <th>Type</th>
                <th>Last Run</th>
                <th>Records</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody className={isPending ? 'loading' : ''}>
              {filteredReports.map(report => (
                <tr key={report.id}>
                  <td><strong>{report.name}</strong></td>
                  <td>{report.folder}</td>
                  <td><span className={`type-badge type-${report.type.toLowerCase()}`}>{report.type}</span></td>
                  <td>{report.lastRun}</td>
                  <td>{report.records.toLocaleString()}</td>
                  <td>
                    <button 
                      className="btn-primary"
                      onClick={() => handleRunReport(report)}
                    >
                      Run
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <div className="toast-container">
        {toasts.map(toast => (
          <div key={toast.id} className="toast">{toast.message}</div>
        ))}
      </div>
    </div>
  );
};

export default App;
