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

interface BlogPost {
  id: string;
  title: string;
  author: string;
  status: 'draft' | 'published' | 'scheduled';
  views: number;
  publishDate: string;
  category: string;
}

const mockPosts: BlogPost[] = [
  { id: '1', title: 'Getting Started with HubSpot', author: 'Sarah Johnson', status: 'published', views: 5420, publishDate: '2024-02-10', category: 'Tutorial' },
  { id: '2', title: '10 Marketing Tips for 2024', author: 'Mike Chen', status: 'published', views: 8750, publishDate: '2024-02-12', category: 'Marketing' },
  { id: '3', title: 'Understanding CRM Analytics', author: 'Tom Brown', status: 'draft', views: 0, publishDate: '2024-02-20', category: 'Analytics' },
  { id: '4', title: 'Sales Pipeline Best Practices', author: 'Sarah Johnson', status: 'scheduled', views: 0, publishDate: '2024-02-15', category: 'Sales' },
  { id: '5', title: 'Email Marketing ROI Guide', author: 'Mike Chen', status: 'published', views: 6230, publishDate: '2024-02-11', category: 'Marketing' },
];

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

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredPosts = useMemo(() => {
    if (!debouncedSearch) return mockPosts;
    const term = debouncedSearch.toLowerCase();
    return mockPosts.filter(p => p.title.toLowerCase().includes(term) || p.author.toLowerCase().includes(term));
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockPosts.length,
    published: mockPosts.filter(p => p.status === 'published').length,
    drafts: mockPosts.filter(p => p.status === 'draft').length,
    totalViews: mockPosts.reduce((sum, p) => sum + p.views, 0),
  }), []);

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

  const handleSelectPost = (post: BlogPost) => {
    setSelectedPost(post);
    addToast(`Viewing ${post.title}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Blog Manager</h1>
        <p>Blog posts, drafts, published, scheduling</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Posts</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Published</div>
          <div className="stat-value">{stats.published}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Drafts</div>
          <div className="stat-value">{stats.drafts}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Views</div>
          <div className="stat-value">{(stats.totalViews / 1000).toFixed(1)}K</div>
        </div>
      </div>

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

      {filteredPosts.length === 0 ? (
        <div className="empty-state">
          <h3>No posts found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Title</th>
                <th>Author</th>
                <th>Category</th>
                <th>Status</th>
                <th>Views</th>
                <th>Publish Date</th>
              </tr>
            </thead>
            <tbody>
              {filteredPosts.map(post => (
                <tr
                  key={post.id}
                  onClick={() => handleSelectPost(post)}
                  className={selectedPost?.id === post.id ? 'selected' : ''}
                >
                  <td>{post.title}</td>
                  <td>{post.author}</td>
                  <td>{post.category}</td>
                  <td>
                    <span className={`status-badge status-${post.status}`}>
                      {post.status}
                    </span>
                  </td>
                  <td>{post.views.toLocaleString()}</td>
                  <td>{post.publishDate}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedPost && (
        <div className="detail-panel">
          <h3>Post Details</h3>
          <div className="detail-grid">
            <div><strong>Title:</strong> {selectedPost.title}</div>
            <div><strong>Author:</strong> {selectedPost.author}</div>
            <div><strong>Category:</strong> {selectedPost.category}</div>
            <div><strong>Status:</strong> {selectedPost.status}</div>
            <div><strong>Views:</strong> {selectedPost.views.toLocaleString()}</div>
            <div><strong>Publish Date:</strong> {selectedPost.publishDate}</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;
