import React, { useState, useEffect } from 'react';
import { usePaginatedData } from '../../hooks/usePaginatedData';
import { useApiDelete } from '../../hooks/useApiMutation';
import { useBatchSelection } from '../../hooks/useBatchSelection';
import { useToast } from '../../hooks/useToast';
import { DataTable, Column } from '../common/DataTable';
import { ToastContainer } from '../common/ToastContainer';
import { exportToCSV, getExportFilename } from '../../utils/export';
import './ArticleListExample.css';

interface Article {
  id: number;
  title: string;
  published: boolean;
  created_at: string;
  author?: {
    name: string;
  };
}

/**
 * Complete example showing how to use all the new utility hooks and components
 * This demonstrates:
 * - usePaginatedData for fetching with pagination, search, sort, filters
 * - useBatchSelection for selecting multiple items
 * - useApiDelete for deleting items
 * - useToast for notifications
 * - DataTable for displaying data
 * - Export utilities
 */
export const ArticleListExample: React.FC = () => {
  // Data fetching with pagination, search, sort, filters
  const {
    data: articles,
    meta,
    loading,
    error,
    setPage,
    setSearch,
    setSort,
    setFilters,
    refresh,
  } = usePaginatedData<Article>('/articles', {
    page_size: 20,
  });

  // Batch selection
  const selection = useBatchSelection<Article>(articles, 'id');

  // Update selection when articles change
  useEffect(() => {
    selection.setItems(articles);
  }, [articles]);

  // Toast notifications
  const toast = useToast();

  // Delete mutation
  const deleteArticle = useApiDelete<void, { id: number }>((data) => `/articles/${data.id}`);

  // Local state
  const [searchTerm, setSearchTerm] = useState('');
  const [publishedFilter, setPublishedFilter] = useState<string>('all');

  // Handle search input
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchTerm(value);
    // Debounce search
    const timeoutId = setTimeout(() => {
      setSearch(value);
    }, 500);
    return () => clearTimeout(timeoutId);
  };

  // Handle filter change
  const handleFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value;
    setPublishedFilter(value);
    if (value === 'all') {
      setFilters({});
    } else {
      setFilters({ published: value === 'published' });
    }
  };

  // Handle sort
  const handleSort = (field: string) => {
    // Toggle sort order
    setSort(field, 'desc'); // You'd want to track current order and toggle
  };

  // Handle delete
  const handleDelete = async (id: number) => {
    if (!window.confirm('Are you sure you want to delete this article?')) return;

    const result = await deleteArticle.mutate({ id });
    if (result !== null) {
      toast.success('Article deleted successfully');
      refresh();
    } else {
      toast.error(deleteArticle.error || 'Failed to delete article');
    }
  };

  // Handle batch delete
  const handleBatchDelete = async () => {
    const count = selection.selectedIds.size;
    if (!window.confirm(`Are you sure you want to delete ${count} articles?`)) return;

    // In real implementation, you'd call a batch delete API
    toast.info(`Would delete ${count} articles`);
    selection.deselectAll();
  };

  // Handle export
  const handleExport = () => {
    const filename = getExportFilename('articles', 'csv');
    const exportData = articles.map((article) => ({
      ID: article.id,
      Title: article.title,
      Published: article.published ? 'Yes' : 'No',
      Author: article.author?.name || 'Unknown',
      'Created At': new Date(article.created_at).toLocaleString(),
    }));
    exportToCSV(exportData, filename);
    toast.success('Articles exported successfully');
  };

  // Table columns configuration
  const columns: Column<Article>[] = [
    {
      key: 'id',
      label: 'ID',
      sortable: true,
      width: '80px',
    },
    {
      key: 'title',
      label: 'Title',
      sortable: true,
      render: (article) => (
        <div className="article-title">
          <strong>{article.title}</strong>
          {!article.published && <span className="badge badge-draft">Draft</span>}
        </div>
      ),
    },
    {
      key: 'author',
      label: 'Author',
      render: (article) => article.author?.name || 'Unknown',
    },
    {
      key: 'created_at',
      label: 'Created',
      sortable: true,
      render: (article) => new Date(article.created_at).toLocaleDateString(),
    },
  ];

  return (
    <div className="article-list-example">
      <ToastContainer toasts={toast.toasts} onDismiss={toast.dismiss} />

      <div className="page-header">
        <h1>Articles</h1>
        <button className="btn btn-primary" onClick={refresh}>
          Refresh
        </button>
      </div>

      {/* Filters and Search */}
      <div className="filters-bar">
        <div className="search-box">
          <input
            type="text"
            placeholder="Search articles..."
            value={searchTerm}
            onChange={handleSearchChange}
            className="search-input"
          />
        </div>

        <select
          value={publishedFilter}
          onChange={handleFilterChange}
          className="filter-select"
        >
          <option value="all">All Articles</option>
          <option value="published">Published</option>
          <option value="draft">Drafts</option>
        </select>

        <button
          className="btn btn-secondary"
          onClick={handleExport}
          disabled={articles.length === 0}
        >
          Export CSV
        </button>
      </div>

      {/* Batch Actions */}
      {selection.selectedIds.size > 0 && (
        <div className="batch-actions">
          <span className="selected-count">
            {selection.selectedIds.size} article(s) selected
          </span>
          <button className="btn btn-danger" onClick={handleBatchDelete}>
            Delete Selected
          </button>
          <button className="btn btn-ghost" onClick={selection.deselectAll}>
            Clear Selection
          </button>
        </div>
      )}

      {/* Error Message */}
      {error && (
        <div className="error-message">
          <p>Error: {error}</p>
          <button onClick={refresh}>Retry</button>
        </div>
      )}

      {/* Data Table */}
      <DataTable
        data={articles}
        columns={columns}
        loading={loading}
        emptyMessage="No articles found"
        selectable
        selectedIds={selection.selectedIds}
        onToggleSelect={selection.toggle}
        onToggleSelectAll={selection.toggleAll}
        isAllSelected={selection.isAllSelected}
        isSomeSelected={selection.isSomeSelected}
        onSort={handleSort}
        actions={(article) => (
          <div className="table-actions">
            <button
              className="btn-icon"
              onClick={() => console.log('Edit', article.id)}
              title="Edit"
            >
              ✏️
            </button>
            <button
              className="btn-icon"
              onClick={() => handleDelete(article.id)}
              title="Delete"
            >
              🗑️
            </button>
          </div>
        )}
      />

      {/* Pagination */}
      {meta && meta.total_pages > 1 && (
        <div className="pagination">
          <button
            className="btn btn-sm"
            onClick={() => setPage(meta.page - 1)}
            disabled={!meta.has_prev}
          >
            Previous
          </button>
          <span className="pagination-info">
            Page {meta.page} of {meta.total_pages} ({meta.total} total)
          </span>
          <button
            className="btn btn-sm"
            onClick={() => setPage(meta.page + 1)}
            disabled={!meta.has_next}
          >
            Next
          </button>
        </div>
      )}
    </div>
  );
};
