import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Grid, 
  Card, 
  CardMedia, 
  CardContent, 
  CardActions,
  Button,
  Chip,
  TextField,
  InputAdornment,
  IconButton,
  Divider,
  Pagination,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  CircularProgress,
  Alert,
  Container
} from '@mui/material';
import { useNavigate, useLocation, Link as RouterLink } from 'react-router-dom';
import SearchIcon from '@mui/icons-material/Search';
import ClearIcon from '@mui/icons-material/Clear';
import { useBlogPosts, useBlogCategories } from '@hooks/blogHooks';
import { format } from 'date-fns';
import imageUtils from '@utils/imageUtils';

const BlogPage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  
  // State for filters and search
  const [filters, setFilters] = useState({
    category: searchParams.get('category') || '',
    tag: searchParams.get('tag') || '',
    search: searchParams.get('search') || '',
    page: parseInt(searchParams.get('page') || '1'),
  });
  
  // Fetch blog posts
  const { data, isLoading, error } = useBlogPosts(filters);
  const { data: categories } = useBlogCategories();
  
  // Update URL when filters change
  useEffect(() => {
    const params = new URLSearchParams();
    
    if (filters.category) params.set('category', filters.category);
    if (filters.tag) params.set('tag', filters.tag);
    if (filters.search) params.set('search', filters.search);
    if (filters.page > 1) params.set('page', filters.page.toString());
    
    navigate(`/blog${params.toString() ? `?${params.toString()}` : ''}`, { replace: true });
  }, [filters, navigate]);
  
  // Handle search input
  const handleSearchChange = (e) => {
    setFilters({ ...filters, search: e.target.value, page: 1 });
  };
  
  // Clear search
  const handleClearSearch = () => {
    setFilters({ ...filters, search: '', page: 1 });
  };
  
  // Handle category change
  const handleCategoryChange = (e) => {
    setFilters({ ...filters, category: e.target.value, page: 1 });
  };
  
  // Handle tag click
  const handleTagClick = (tag) => {
    setFilters({ ...filters, tag, page: 1 });
  };
  
  // Clear tag filter
  const handleClearTag = () => {
    setFilters({ ...filters, tag: '', page: 1 });
  };
  
  // Handle pagination
  const handlePageChange = (event, value) => {
    setFilters({ ...filters, page: value });
    // Scroll to top when page changes
    window.scrollTo(0, 0);
  };
  
  // Format date for display
  const formatPublishedDate = (dateString) => {
    if (!dateString) return '';
    return format(new Date(dateString), 'MMMM d, yyyy');
  };
  
  // Loading state
  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', my: 8 }}>
        <CircularProgress />
      </Box>
    );
  }
  
  // Error state
  if (error) {
    return (
      <Alert severity="error" sx={{ my: 4 }}>
        Error loading blog posts: {error.message}
      </Alert>
    );
  }
  
  // Empty state
  const posts = data?.posts || [];
  const pagination = data?.pagination || { page: 1, pages: 1, total: 0 };
  
  return (
    <Container maxWidth="lg">
      <Box sx={{ py: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          Our Blog
        </Typography>
        <Typography variant="subtitle1" color="text.secondary" paragraph>
          Discover insights about our natural collections, sourcing adventures, and unique specimens
        </Typography>
        
        {/* Filters and Search */}
        <Grid container spacing={2} sx={{ mb: 4, mt: 2 }}>
          {/* Category filter */}
          <Grid item xs={12} md={4}>
            <FormControl fullWidth variant="outlined">
              <InputLabel id="category-filter-label">Filter by Category</InputLabel>
              <Select
                labelId="category-filter-label"
                value={filters.category}
                onChange={handleCategoryChange}
                label="Filter by Category"
              >
                <MenuItem value="">All Categories</MenuItem>
                {categories?.map((category) => (
                  <MenuItem key={category.id} value={category.name}>
                    {category.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>
          
          {/* Tag filter */}
          <Grid item xs={12} md={8}>
            {filters.tag && (
              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <Typography variant="body2" sx={{ mr: 1 }}>
                  Filtered by tag:
                </Typography>
                <Chip 
                  label={filters.tag} 
                  onDelete={handleClearTag} 
                  color="primary" 
                  size="small"
                />
              </Box>
            )}
          </Grid>
          
          {/* Search */}
          <Grid item xs={12}>
            <TextField
              fullWidth
              placeholder="Search blog posts..."
              value={filters.search}
              onChange={handleSearchChange}
              variant="outlined"
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
                endAdornment: filters.search && (
                  <InputAdornment position="end">
                    <IconButton size="small" onClick={handleClearSearch}>
                      <ClearIcon />
                    </IconButton>
                  </InputAdornment>
                )
              }}
            />
          </Grid>
        </Grid>
        
        {/* No results message */}
        {posts.length === 0 && (
          <Box sx={{ textAlign: 'center', my: 8 }}>
            <Typography variant="h6" gutterBottom>
              No blog posts found
            </Typography>
            <Typography variant="body1" color="text.secondary">
              {filters.search || filters.category || filters.tag 
                ? 'Try adjusting your filters or search terms'
                : 'Check back soon for new content'}
            </Typography>
          </Box>
        )}
        
        {/* Blog post grid */}
        <Grid container spacing={4}>
          {posts.map((post) => (
            <Grid item xs={12} sm={6} md={4} key={post.id}>
              <Card sx={{ 
                height: '100%', 
                display: 'flex', 
                flexDirection: 'column',
                transition: 'transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out',
                '&:hover': {
                  transform: 'translateY(-5px)',
                  boxShadow: 6
                }
              }}>
                {/* Featured image */}
                <CardMedia
                  component="img"
                  height="200"
                  image={post.featured_image_path 
                    ? imageUtils.getImageUrl(post.featured_image_path) 
                    : '/images/placeholder.jpg'}
                  alt={post.title}
                />
                
                <CardContent sx={{ flexGrow: 1 }}>
                  {/* Category */}
                  {post.category_name && (
                    <Chip 
                      label={post.category_name} 
                      size="small" 
                      color="primary" 
                      sx={{ mb: 1 }}
                    />
                  )}
                  
                  {/* Title */}
                  <Typography variant="h5" component="h2" gutterBottom>
                    {post.title}
                  </Typography>
                  
                  {/* Published date */}
                  <Typography variant="caption" color="text.secondary" display="block" gutterBottom>
                    {formatPublishedDate(post.published_at)}
                  </Typography>
                  
                  {/* Excerpt */}
                  <Typography variant="body2" color="text.secondary" paragraph>
                    {post.excerpt || (post.content && post.content.substring(0, 150) + '...')}
                  </Typography>
                  
                  {/* Tags */}
                  <Box sx={{ mt: 2, mb: 1 }}>
                    {post.tags && post.tags.filter(Boolean).map((tag, index) => (
                      <Chip
                        key={index}
                        label={tag}
                        size="small"
                        onClick={() => handleTagClick(tag)}
                        sx={{ mr: 0.5, mb: 0.5 }}
                      />
                    ))}
                  </Box>
                </CardContent>
                
                <CardActions>
                  <Button 
                    size="small" 
                    component={RouterLink} 
                    to={`/blog/${post.slug}`}
                  >
                    Read More
                  </Button>
                  <Box sx={{ ml: 'auto' }}>
                    <Chip 
                      label={`${post.comment_count || 0} comments`} 
                      size="small" 
                      variant="outlined"
                    />
                  </Box>
                </CardActions>
              </Card>
            </Grid>
          ))}
        </Grid>
        
        {/* Pagination */}
        {pagination.pages > 1 && (
          <Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}>
            <Pagination 
              count={pagination.pages} 
              page={pagination.page} 
              onChange={handlePageChange}
              color="primary"
              siblingCount={1}
            />
          </Box>
        )}
      </Box>
    </Container>
  );
};

export default BlogPage;