import React, { useState, useEffect } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { forumAPI } from '../services/api';
import { ForumPost } from '../types';
import ForumPostListItem from '../components/ForumPostListItem';
import AuthButton from '../components/AuthButton';

const ForumPosts: React.FC = () => {
  const { user } = useAuth();
  const isAdmin = user?.role === 'admin';
  const [searchParams, setSearchParams] = useSearchParams();
  const [posts, setPosts] = useState<ForumPost[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalPosts, setTotalPosts] = useState(0);

  // Initialize filter from URL param or default to 'active'
  const initialFilter = searchParams.get('filter') || 'active';

  const [filters, setFilters] = useState({
    search: '',
    category: '',
    tag: '',
    status: '',
    sort: 'recent',
    deletionFilter: initialFilter // all, active, deleted
  });

  const categories = [
    { value: '', label: 'All Categories' },
    { value: 'item_request', label: 'Item Requests' },
    { value: 'technical_support', label: 'Technical Support' },
    { value: 'community_resources', label: 'Community Resources' },
    { value: 'general_discussion', label: 'General Discussion' },
  ];

  useEffect(() => {
    fetchPosts();
  }, [currentPage, filters]);

  const fetchPosts = async () => {
    try {
      setLoading(true);
      const params: any = {
        page: currentPage,
        limit: 20,
        sort: filters.sort
      };

      if (filters.search) params.search = filters.search;
      if (filters.category) params.category = filters.category;
      if (filters.tag) params.tag = filters.tag;
      if (filters.status) params.status = filters.status;

      const response = await forumAPI.getPosts(params);

      setPosts(response.data.posts);
      setTotalPages(response.data.totalPages);
      setTotalPosts(response.data.totalPosts);
    } catch (err: any) {
      setError(err.response?.data?.error || 'Failed to fetch forum posts');
    } finally {
      setLoading(false);
    }
  };

  const handleFilterChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFilters(prev => ({ ...prev, [name]: value }));
    setCurrentPage(1);

    // Update URL param when deletion filter changes
    if (name === 'deletionFilter' && isAdmin) {
      setSearchParams({ filter: value });
    }
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    fetchPosts();
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const handleCategoryClick = (category: string) => {
    setFilters(prev => ({ ...prev, category }));
    setCurrentPage(1);
  };

  // Filter posts based on deletion status (admin only)
  const filteredPosts = isAdmin ? posts.filter(post => {
    if (filters.deletionFilter === 'active') {
      return !post.isDeleted; // Show active posts regardless of deleted comments
    } else if (filters.deletionFilter === 'deleted') {
      return post.isDeleted || post.hasDeletedComments; // Show deleted posts OR posts with deleted comments
    }
    return true; // 'all' shows everything
  }) : posts;

  return (
    <div className="container mt-4">
      <div className="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h1>Community Forum</h1>
          <p className="text-muted">Discuss, share, and connect with the community</p>
        </div>
        {user && (
          <Link to="/forum/create" className="btn btn-primary">
            <i className="bi bi-plus-circle me-2"></i>
            Create Post
          </Link>
        )}
      </div>

      {/* Category Tabs */}
      <ul className="nav nav-tabs mb-4">
        {categories.map((cat) => (
          <li key={cat.value} className="nav-item">
            <button
              className={`nav-link ${filters.category === cat.value ? 'active' : ''}`}
              onClick={() => handleCategoryClick(cat.value)}
            >
              {cat.label}
            </button>
          </li>
        ))}
      </ul>

      {/* Filters */}
      <div className="row mb-4">
        <div className={isAdmin ? "col-md-5" : "col-md-6"}>
          <form onSubmit={handleSearch}>
            <div className="input-group">
              <input
                type="text"
                className="form-control"
                placeholder="Search posts..."
                name="search"
                value={filters.search}
                onChange={handleFilterChange}
              />
              <button className="btn btn-outline-secondary" type="submit">
                <i className="bi bi-search"></i>
              </button>
            </div>
          </form>
        </div>
        {isAdmin && (
          <div className="col-md-2">
            <select
              className="form-select"
              name="deletionFilter"
              value={filters.deletionFilter}
              onChange={handleFilterChange}
            >
              <option value="active">Active</option>
              <option value="all">All</option>
              <option value="deleted">Deleted</option>
            </select>
          </div>
        )}
        <div className={isAdmin ? "col-md-2" : "col-md-3"}>
          <select
            className="form-select"
            name="status"
            value={filters.status}
            onChange={handleFilterChange}
          >
            <option value="">All Status</option>
            <option value="open">Open</option>
            <option value="answered">Answered</option>
            <option value="closed">Closed</option>
          </select>
        </div>
        <div className={isAdmin ? "col-md-3" : "col-md-3"}>
          <select
            className="form-select"
            name="sort"
            value={filters.sort}
            onChange={handleFilterChange}
          >
            <option value="recent">Most Recent</option>
            <option value="comments">Most Commented</option>
          </select>
        </div>
      </div>

      {error && (
        <div className="alert alert-danger" role="alert">
          {error}
        </div>
      )}

      {loading ? (
        <div className="text-center py-4">
          <div className="spinner-border" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
        </div>
      ) : (
        <>
          <div className="d-flex justify-content-between align-items-center mb-3">
            <p className="text-muted mb-0">
              Showing {filteredPosts.length} of {totalPosts} posts
            </p>
          </div>

          {filteredPosts.length === 0 ? (
            <div className="text-center py-5">
              <i className="bi bi-inbox display-1 text-muted"></i>
              <h3 className="mt-3">No posts found</h3>
              <p className="text-muted">
                {filters.search || filters.category || filters.tag
                  ? "Try adjusting your search terms or filters."
                  : "Be the first to start a discussion!"
                }
              </p>
              {user && !filters.search && !filters.category && (
                <Link to="/forum/create" className="btn btn-primary">
                  Create First Post
                </Link>
              )}
            </div>
          ) : (
            <>
              <div className="list-group list-group-flush mb-4">
                {filteredPosts.map((post) => (
                  <ForumPostListItem key={post.id} post={post} filter={isAdmin ? filters.deletionFilter : undefined} />
                ))}
              </div>

              {totalPages > 1 && (
                <nav className="mt-4" aria-label="Page navigation">
                  <ul className="pagination justify-content-center">
                    <li className={`page-item ${currentPage === 1 ? 'disabled' : ''}`}>
                      <button
                        className="page-link"
                        onClick={() => handlePageChange(currentPage - 1)}
                        disabled={currentPage === 1}
                      >
                        Previous
                      </button>
                    </li>

                    {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                      const page = i + Math.max(1, currentPage - 2);
                      if (page > totalPages) return null;

                      return (
                        <li key={page} className={`page-item ${currentPage === page ? 'active' : ''}`}>
                          <button
                            className="page-link"
                            onClick={() => handlePageChange(page)}
                          >
                            {page}
                          </button>
                        </li>
                      );
                    })}

                    <li className={`page-item ${currentPage === totalPages ? 'disabled' : ''}`}>
                      <button
                        className="page-link"
                        onClick={() => handlePageChange(currentPage + 1)}
                        disabled={currentPage === totalPages}
                      >
                        Next
                      </button>
                    </li>
                  </ul>
                </nav>
              )}
            </>
          )}
        </>
      )}

      {!user && (
        <div className="mt-4">
          <div className="alert alert-info" role="alert">
            <i className="bi bi-info-circle me-2"></i>
            <AuthButton mode="login" className="alert-link" asLink>Log in</AuthButton> to create posts and join the discussion.
          </div>
        </div>
      )}
    </div>
  );
};

export default ForumPosts;
