import React, { useState } from 'react';
import {
  Box, 
  Typography, 
  Paper, 
  Tabs, 
  Tab, 
  Card, 
  CardContent, 
  CardActions, 
  Button, 
  Divider, 
  Chip, 
  CircularProgress, 
  Alert, 
  Dialog, 
  DialogTitle, 
  DialogContent, 
  DialogContentText, 
  DialogActions,
  TextField,
  InputAdornment,
  IconButton,
  Tooltip,
  Rating
} from '@mui/material';
import {
  Check as ApproveIcon,
  Delete as DeleteIcon,
  Search as SearchIcon,
  Clear as ClearIcon,
  Visibility as ViewIcon,
  Refresh as RefreshIcon
} from '@mui/icons-material';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import { usePendingReviews, useApproveReview, useDeleteReview } from '@hooks/productReviewHooks';
import { format } from 'date-fns';
import { useQueryClient } from '@tanstack/react-query';

const AdminProductReviewsPage = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [activeTab, setActiveTab] = useState(0);
  const [searchTerm, setSearchTerm] = useState('');
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [reviewToDelete, setReviewToDelete] = useState(null);
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Fetch pending reviews
  const { data: pendingReviews, isLoading, error } = usePendingReviews();
  const approveReview = useApproveReview();
  const deleteReview = useDeleteReview();

  // Filter reviews by search term
  const filteredReviews = pendingReviews ? pendingReviews.filter(review => 
    review.title?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    review.content?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    review.first_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    review.last_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    review.email?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    review.product_name?.toLowerCase().includes(searchTerm.toLowerCase())
  ) : [];

  // Handle tab change
  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };

  // Handle search input change
  const handleSearchChange = (e) => {
    setSearchTerm(e.target.value);
  };

  // Clear search
  const handleClearSearch = () => {
    setSearchTerm('');
  };

  // Handle refresh
  const handleRefresh = async () => {
    setIsRefreshing(true);
    try {
      await queryClient.invalidateQueries(['pending-reviews']);
      // Optional timeout to ensure the refresh button animation is visible
      setTimeout(() => {
        setIsRefreshing(false);
      }, 500);
    } catch (error) {
      console.error('Error refreshing reviews:', error);
      setIsRefreshing(false);
    }
  };

  // Handle view product
  const handleViewProduct = (productId) => {
    window.open(`/products/${productId}`, '_blank');
  };

  // Handle approve review
  const handleApproveReview = async (id) => {
    try {
      await approveReview.mutateAsync(id);
    } catch (error) {
      console.error('Error approving review:', error);
    }
  };

  // Handle delete dialog open
  const handleDeleteClick = (review) => {
    setReviewToDelete(review);
    setDeleteDialogOpen(true);
  };

  // Handle delete confirmation
  const handleConfirmDelete = async () => {
    if (reviewToDelete) {
      await deleteReview.mutateAsync(reviewToDelete.id);
      setDeleteDialogOpen(false);
      setReviewToDelete(null);
    }
  };

  // Handle delete cancellation
  const handleCancelDelete = () => {
    setDeleteDialogOpen(false);
    setReviewToDelete(null);
  };

  // Format date
  const formatDate = (dateString) => {
    return format(new Date(dateString), 'MMM d, yyyy h:mm a');
  };

  // Loading state
  if (isLoading && !isRefreshing) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  // Error state
  if (error) {
    return (
      <Alert severity="error" sx={{ my: 2 }}>
        Error loading reviews: {error.message}
      </Alert>
    );
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h4" component="h1">
          Product Reviews
        </Typography>
        <Tooltip title="Refresh reviews">
          <IconButton 
            onClick={handleRefresh}
            color="primary"
            disabled={isRefreshing}
          >
            {isRefreshing ? (
              <CircularProgress size={24} />
            ) : (
              <RefreshIcon />
            )}
          </IconButton>
        </Tooltip>
      </Box>
      
      <Tabs
        value={activeTab}
        onChange={handleTabChange}
        indicatorColor="primary"
        textColor="primary"
        variant="fullWidth"
        sx={{ mb: 3 }}
      >
        <Tab label={`Pending Approval (${pendingReviews?.length || 0})`} />
        <Tab label="All Reviews" />
      </Tabs>
      
      {/* Search Box */}
      <Paper sx={{ p: 2, mb: 3 }}>
        <TextField
          fullWidth
          placeholder="Search reviews by content, author, or product..."
          value={searchTerm}
          onChange={handleSearchChange}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
            endAdornment: searchTerm && (
              <InputAdornment position="end">
                <IconButton size="small" onClick={handleClearSearch}>
                  <ClearIcon />
                </IconButton>
              </InputAdornment>
            )
          }}
        />
      </Paper>
      
      {/* Reviews List */}
      {filteredReviews.length === 0 ? (
        <Paper sx={{ p: 4, textAlign: 'center' }}>
          <Typography variant="h6" gutterBottom>
            No pending reviews found
          </Typography>
          <Typography variant="body2" color="text.secondary">
            {searchTerm ? 'Try adjusting your search terms' : 'All reviews have been approved'}
          </Typography>
          <Button 
            startIcon={<RefreshIcon />}
            variant="outlined"
            onClick={handleRefresh}
            sx={{ mt: 2 }}
            disabled={isRefreshing}
          >
            Refresh
          </Button>
        </Paper>
      ) : (
        <Box>
          {filteredReviews.map(review => (
            <Card key={review.id} sx={{ mb: 2 }}>
              <CardContent>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
                  <Box>
                    <Typography variant="subtitle1">
                      {review.first_name} {review.last_name} ({review.email})
                    </Typography>
                    <Chip 
                      label={formatDate(review.created_at)} 
                      variant="outlined" 
                      size="small" 
                    />
                    {review.is_verified_purchase && (
                      <Chip 
                        label="Verified Purchase" 
                        color="success" 
                        size="small" 
                        sx={{ ml: 1 }}
                      />
                    )}
                  </Box>
                  <Box>
                    <Chip 
                      label={`Product: ${review.product_name}`} 
                      color="primary" 
                      variant="outlined"
                    />
                  </Box>
                </Box>
                
                <Divider sx={{ mb: 2 }} />
                
                <Typography variant="h6">{review.title}</Typography>
                
                {review.rating && (
                  <Box sx={{ display: 'flex', alignItems: 'center', my: 1 }}>
                    <Rating value={review.rating} readOnly precision={0.5} />
                    <Typography variant="body2" sx={{ ml: 1 }}>
                      ({review.rating}/5)
                    </Typography>
                  </Box>
                )}
                
                <Typography variant="body2" paragraph>
                  {review.content || <em>No content provided</em>}
                </Typography>
                
                {review.parent_id && (
                  <Alert severity="info" sx={{ mt: 1 }}>
                    This is a reply to another review
                  </Alert>
                )}
              </CardContent>
              
              <CardActions sx={{ justifyContent: 'flex-end' }}>
                <Button 
                  startIcon={<ViewIcon />}
                  onClick={() => handleViewProduct(review.product_id)}
                >
                  View Product
                </Button>
                <Button 
                  startIcon={<ApproveIcon />}
                  color="success"
                  onClick={() => handleApproveReview(review.id)}
                  disabled={approveReview.isLoading}
                >
                  Approve
                </Button>
                <Button 
                  startIcon={<DeleteIcon />}
                  color="error"
                  onClick={() => handleDeleteClick(review)}
                  disabled={deleteReview.isLoading}
                >
                  Delete
                </Button>
              </CardActions>
            </Card>
          ))}
        </Box>
      )}
      
      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteDialogOpen}
        onClose={handleCancelDelete}
        aria-labelledby="delete-dialog-title"
        aria-describedby="delete-dialog-description"
      >
        <DialogTitle id="delete-dialog-title">
          Confirm Delete
        </DialogTitle>
        <DialogContent>
          <DialogContentText id="delete-dialog-description">
            Are you sure you want to delete this review? This action cannot be undone.
          </DialogContentText>
          
          {reviewToDelete && (
            <Paper variant="outlined" sx={{ p: 2, mt: 2, bgcolor: 'background.paper' }}>
              <Typography variant="subtitle1">
                Review by {reviewToDelete.first_name} {reviewToDelete.last_name}:
              </Typography>
              <Typography variant="h6" gutterBottom>
                {reviewToDelete.title}
              </Typography>
              {reviewToDelete.rating && (
                <Rating value={reviewToDelete.rating} readOnly size="small" />
              )}
              <Typography variant="body2" sx={{ mt: 1 }}>
                {reviewToDelete.content || <em>No content provided</em>}
              </Typography>
            </Paper>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCancelDelete}>Cancel</Button>
          <Button 
            onClick={handleConfirmDelete} 
            color="error" 
            variant="contained"
            autoFocus
            disabled={deleteReview.isLoading}
          >
            {deleteReview.isLoading ? (
              <CircularProgress size={24} sx={{ mr: 1 }} />
            ) : null}
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default AdminProductReviewsPage;