import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Grid, 
  Card, 
  CardMedia, 
  CardContent, 
  CardActions,
  Button,
  TextField,
  InputAdornment,
  IconButton,
  Drawer,
  List,
  ListItem,
  ListItemText,
  Divider,
  Chip,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  CircularProgress,
  Pagination
} from '@mui/material';
import { useTheme } from '@mui/material/styles';
import SearchIcon from '@mui/icons-material/Search';
import FilterListIcon from '@mui/icons-material/FilterList';
import SortIcon from '@mui/icons-material/Sort';
import CloseIcon from '@mui/icons-material/Close';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import { Link as RouterLink, useNavigate, useLocation } from 'react-router-dom';
import { useProducts, useCategories, useTags, useAddToCart } from '@hooks/apiHooks';
import ProductRatingDisplay from '@components/ProductRatingDisplay';
import { useAuth } from '@hooks/reduxHooks';
import imageUtils from '@utils/imageUtils';
import useBrandingSettings from '@hooks/brandingHooks';

const ProductsPage = () => {
  const theme = useTheme();
  const navigate = useNavigate();
  const location = useLocation();
  const { isAuthenticated, user } = useAuth();
  const { data: brandingSettings } = useBrandingSettings();
  
  // Parse query params
  const queryParams = new URLSearchParams(location.search);
  
  // State for filters and search
  const [filters, setFilters] = useState({
    category: queryParams.get('category') || '',
    tag: queryParams.get('tag') || '',
    search: queryParams.get('search') || '',
    sort: queryParams.get('sort') || 'name',
    order: queryParams.get('order') || 'asc'
  });
  
  // State for filter drawer
  const [drawerOpen, setDrawerOpen] = useState(false);
  
  // Pagination
  const [page, setPage] = useState(1);
  const itemsPerPage = 12;
  
  // Data fetching with React Query
  const { data: products, isLoading, error } = useProducts(filters);
  const { data: categories } = useCategories();
  const { data: tags } = useTags();
  const addToCart = useAddToCart();
  
  // 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.sort !== 'name') params.set('sort', filters.sort);
    if (filters.order !== 'asc') params.set('order', filters.order);
    
    navigate(`/products${params.toString() ? `?${params.toString()}` : ''}`, { replace: true });
  }, [filters, navigate]);
  
  // Handle search input
  const handleSearchChange = (e) => {
    setFilters({ ...filters, search: e.target.value });
  };
  
  // Handle search submit
  const handleSearchSubmit = (e) => {
    e.preventDefault();
    // Reset pagination when searching
    setPage(1);
  };
  
  // Handle filter changes
  const handleFilterChange = (e) => {
    const { name, value } = e.target;
    setFilters({ ...filters, [name]: value });
    setPage(1); // Reset pagination when changing filters
  };
  
  // Handle sort change
  const handleSortChange = (e) => {
    const { name, value } = e.target;
    setFilters({ ...filters, [name]: value });
  };
  
  // Clear all filters
  const clearFilters = () => {
    setFilters({
      category: '',
      tag: '',
      search: '',
      sort: 'name',
      order: 'asc'
    });
    setPage(1);
  };
  
  // Add to cart
  const handleAddToCart = (productId) => {
    if (!isAuthenticated) {
      navigate('/auth/login', { state: { from: location } });
      return;
    }
    
    addToCart.mutate({
      userId: user,
      productId,
      quantity: 1
    });
  };
  
  // Calculate pagination
  const paginatedProducts = products ? 
    products.slice((page - 1) * itemsPerPage, page * itemsPerPage) : 
    [];
  
  return (
    <Box>
      <Typography variant="h4" component="h1" gutterBottom>
        {brandingSettings?.product_title || `Products`}
      </Typography>
      
      {/* Search and filter bar */}
      <Box sx={{ 
        display: 'flex', 
        justifyContent: 'space-between',
        alignItems: 'center',
        flexWrap: 'wrap',
        mb: 3,
        gap: 2
      }}>
        {/* Search */}
        <Box component="form" onSubmit={handleSearchSubmit} sx={{ flexGrow: 1, maxWidth: 500 }}>
          <TextField
            fullWidth
            size="small"
            placeholder={`Search ${(brandingSettings?.product_title || `Products`).toLowerCase()}...`}
            value={filters.search}
            onChange={handleSearchChange}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon />
                </InputAdornment>
              )
            }}
          />
        </Box>
        
        {/* Filter button (mobile) */}
        <Box sx={{ display: { xs: 'block', md: 'none' } }}>
          <Button 
            startIcon={<FilterListIcon />}
            variant="outlined"
            onClick={() => setDrawerOpen(true)}
          >
            Filters
          </Button>
        </Box>
        
        {/* Sort options (desktop) */}
        <Box sx={{ display: { xs: 'none', md: 'flex' }, alignItems: 'center', gap: 2 }}>
          <SortIcon color="action" />
          <FormControl size="small" sx={{ minWidth: 120 }}>
            <InputLabel id="sort-label">Sort by</InputLabel>
            <Select
              labelId="sort-label"
              id="sort"
              name="sort"
              value={filters.sort}
              label="Sort by"
              onChange={handleSortChange}
            >
              <MenuItem value="name">Name</MenuItem>
              <MenuItem value="price">Price</MenuItem>
              <MenuItem value="created_at">Newest</MenuItem>
            </Select>
          </FormControl>
          
          <FormControl size="small" sx={{ minWidth: 100 }}>
            <InputLabel id="order-label">Order</InputLabel>
            <Select
              labelId="order-label"
              id="order"
              name="order"
              value={filters.order}
              label="Order"
              onChange={handleSortChange}
            >
              <MenuItem value="asc">Ascending</MenuItem>
              <MenuItem value="desc">Descending</MenuItem>
            </Select>
          </FormControl>
        </Box>
      </Box>
      
      {/* Active filters display */}
      {(filters.category || filters.tag || filters.search) && (
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 3 }}>
          {filters.category && (
            <Chip 
              label={`Category: ${filters.category}`} 
              onDelete={() => setFilters({ ...filters, category: '' })}
            />
          )}
          
          {filters.tag && (
            <Chip 
              label={`Tag: ${filters.tag}`} 
              onDelete={() => setFilters({ ...filters, tag: '' })}
            />
          )}
          
          {filters.search && (
            <Chip 
              label={`Search: ${filters.search}`} 
              onDelete={() => setFilters({ ...filters, search: '' })}
            />
          )}
          
          <Button 
            size="small" 
            onClick={clearFilters}
            sx={{ ml: 1 }}
          >
            Clear All
          </Button>
        </Box>
      )}
      
      {/* Main content area */}
      <Box sx={{ display: 'flex' }}>
        {/* Filter sidebar (desktop) */}
        <Box 
          sx={{ 
            width: 240, 
            flexShrink: 0, 
            mr: 3, 
            display: { xs: 'none', md: 'block' } 
          }}
        >
          <Typography variant="h6" gutterBottom>
            Categories
          </Typography>
          
          <List disablePadding>
            <ListItem 
              button 
              selected={filters.category === ''}
              onClick={() => setFilters({ ...filters, category: '' })}
            >
              <ListItemText primary="All Categories" />
            </ListItem>
            
            {categories?.map((category) => (
              <ListItem 
                button 
                key={category.id}
                selected={filters.category === category.name}
                onClick={() => setFilters({ ...filters, category: category.name })}
              >
                <ListItemText primary={category.name} />
              </ListItem>
            ))}
          </List>
          
          <Divider sx={{ my: 2 }} />
          
          <Typography variant="h6" gutterBottom>
            Popular Tags
          </Typography>
          
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
            {tags?.map((tag) => (
              <Chip 
                key={tag.id}
                label={tag.name}
                onClick={() => setFilters({ ...filters, tag: tag.name })}
                color={filters.tag === tag.name ? 'primary' : 'default'}
                clickable
                size="small"
                sx={{ mb: 1 }}
              />
            ))}
          </Box>
        </Box>
        
        {/* Product grid */}
        <Box sx={{ flexGrow: 1 }}>
          {isLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}>
              <CircularProgress />
            </Box>
          ) : error ? (
            <Typography color="error" sx={{ my: 4 }}>
              Error loading products. Please try again.
            </Typography>
          ) : paginatedProducts?.length === 0 ? (
            <Typography sx={{ my: 4 }}>
              No products found with the selected filters.
            </Typography>
          ) : (
            <>
              <Grid container spacing={3}>
                {paginatedProducts.map((product) => (
                  <Grid item xs={12} sm={6} md={4} key={product.id}>
                    <Card 
                      sx={{
                        height: '100%',
                        display: 'flex',
                        flexDirection: 'column',
                        transition: '0.3s',
                        '&:hover': {
                          transform: 'translateY(-5px)',
                          boxShadow: (theme) => theme.shadows[8],
                        },
                      }}
                    >
                      <CardMedia
                        component="img"
                        height="200"
                        image={imageUtils.getImageUrl((product.images && product.images.length > 0) 
                          ? product.images.find(img => img.isPrimary)?.path || product.images[0].path 
                          : '/images/placeholder.jpg')}
                        alt={product.name}
                        sx={{ objectFit: 'cover' }}
                        onClick={() => navigate(`/products/${product.id}`)}
                        style={{ cursor: 'pointer' }}
                      />
                      
                      <CardContent sx={{ flexGrow: 1 }}>
                        <Typography 
                          variant="h6" 
                          component={RouterLink} 
                          to={`/products/${product.id}`}
                          sx={{ 
                            textDecoration: 'none', 
                            color: 'inherit',
                            '&:hover': { color: 'primary.main' }
                          }}
                        >
                          {product.name}
                        </Typography>
                        <ProductRatingDisplay 
                          rating={product.average_rating} 
                          reviewCount={product.review_count} 
                        />
                        <Typography 
                          variant="body2" 
                          color="text.secondary" 
                          sx={{ 
                            mt: 1,
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            display: '-webkit-box',
                            WebkitLineClamp: 3,
                            WebkitBoxOrient: 'vertical',
                          }}
                        >
                          {product.description}
                        </Typography>
                        
                        <Box sx={{ display: 'flex', mt: 2, mb: 1 }}>
                          {product.tags && product.tags.slice(0, 3).map((tag, index) => (
                            <Chip 
                              key={index}
                              label={tag}
                              size="small"
                              sx={{ mr: 0.5, mb: 0.5 }}
                              onClick={(e) => {
                                e.preventDefault();
                                setFilters({ ...filters, tag });
                              }}
                            />
                          ))}
                        </Box>
                        
                        <Typography 
                          variant="h6" 
                          color="primary" 
                          sx={{ mt: 1 }}
                        >
                          ${parseFloat(product.price).toFixed(2)}
                        </Typography>
                      </CardContent>
                      
                      <CardActions sx={{ p: 2, pt: 0 }}>
                        <Button 
                          variant="contained" 
                          size="small"
                          startIcon={<ShoppingCartIcon />}
                          onClick={() => handleAddToCart(product.id)}
                          disabled={addToCart.isLoading}
                        >
                          Add to Cart
                        </Button>
                        
                        <Button
                          variant="outlined"
                          size="small"
                          component={RouterLink}
                          to={`/products/${product.id}`}
                          sx={{ ml: 'auto' }}
                        >
                          Details
                        </Button>
                      </CardActions>
                    </Card>
                  </Grid>
                ))}
              </Grid>
              
              {/* Pagination */}
              {products && products.length > itemsPerPage && (
                <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
                  <Pagination 
                    count={Math.ceil(products.length / itemsPerPage)} 
                    page={page}
                    onChange={(e, value) => setPage(value)}
                    color="primary"
                  />
                </Box>
              )}
            </>
          )}
        </Box>
      </Box>
      
      {/* Filter drawer (mobile) */}
      <Drawer
        anchor="right"
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
      >
        <Box sx={{ width: 280, p: 2 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
            <Typography variant="h6">Filters</Typography>
            <IconButton onClick={() => setDrawerOpen(false)}>
              <CloseIcon />
            </IconButton>
          </Box>
          
          <Divider sx={{ mb: 2 }} />
          
          <Typography variant="subtitle1" gutterBottom>
            Sort by
          </Typography>
          
          <FormControl fullWidth size="small" sx={{ mb: 2 }}>
            <InputLabel id="mobile-sort-label">Sort</InputLabel>
            <Select
              labelId="mobile-sort-label"
              id="mobile-sort"
              name="sort"
              value={filters.sort}
              label="Sort"
              onChange={handleSortChange}
            >
              <MenuItem value="name">Name</MenuItem>
              <MenuItem value="price">Price</MenuItem>
              <MenuItem value="created_at">Newest</MenuItem>
            </Select>
          </FormControl>
          
          <FormControl fullWidth size="small" sx={{ mb: 3 }}>
            <InputLabel id="mobile-order-label">Order</InputLabel>
            <Select
              labelId="mobile-order-label"
              id="mobile-order"
              name="order"
              value={filters.order}
              label="Order"
              onChange={handleSortChange}
            >
              <MenuItem value="asc">Ascending</MenuItem>
              <MenuItem value="desc">Descending</MenuItem>
            </Select>
          </FormControl>
          
          <Typography variant="subtitle1" gutterBottom>
            Categories
          </Typography>
          
          <FormControl fullWidth size="small" sx={{ mb: 3 }}>
            <InputLabel id="category-label">Category</InputLabel>
            <Select
              labelId="category-label"
              id="category"
              name="category"
              value={filters.category}
              label="Category"
              onChange={handleFilterChange}
            >
              <MenuItem value="">All Categories</MenuItem>
              {categories?.map((category) => (
                <MenuItem key={category.id} value={category.name}>
                  {category.name}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
          
          <Typography variant="subtitle1" gutterBottom>
            Popular Tags
          </Typography>
          
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 3 }}>
            {tags?.slice(0, 10).map((tag) => (
              <Chip 
                key={tag.id}
                label={tag.name}
                onClick={() => {
                  setFilters({ ...filters, tag: tag.name });
                  setDrawerOpen(false);
                }}
                color={filters.tag === tag.name ? 'primary' : 'default'}
                clickable
                size="small"
              />
            ))}
          </Box>
          
          <Button 
            variant="outlined" 
            fullWidth 
            onClick={() => {
              clearFilters();
              setDrawerOpen(false);
            }}
          >
            Clear All Filters
          </Button>
        </Box>
      </Drawer>
    </Box>
  );
};

export default ProductsPage;