import React, { useState } from 'react';
import { 
  Box, 
  Typography, 
  Rating, 
  Avatar, 
  Button, 
  TextField, 
  Paper,
  Divider,
  Card,
  CardContent,
  FormControlLabel,
  Checkbox,
  Alert,
  CircularProgress
} from '@mui/material';
import { format } from 'date-fns';
import CommentIcon from '@mui/icons-material/Comment';
import VerifiedIcon from '@mui/icons-material/Verified';
import { useProductReviews, useCanReviewProduct, useAddProductReview } from '@hooks/productReviewHooks';
import { useAuth } from '@hooks/reduxHooks';

/**
 * Component for displaying product reviews and allowing users to submit new reviews
 */
const ProductReviews = ({ productId }) => {
  const { isAuthenticated } = useAuth();
  const [replyTo, setReplyTo] = useState(null);
  const [showReviewForm, setShowReviewForm] = useState(false);
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    rating: 0
  });
  
  // Fetch reviews for this product
  const { data: reviews, isLoading: reviewsLoading } = useProductReviews(productId);
  
  // Check if user can submit a review
  const { data: reviewPermission, isLoading: permissionLoading } = useCanReviewProduct(productId);
  
  // Add review mutation
  const addReview = useAddProductReview();
  
  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return '';
    return format(new Date(dateString), 'MMMM d, yyyy');
  };
  
  // Handle form changes
  const handleFormChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };
  
  // Handle rating change
  const handleRatingChange = (event, newValue) => {
    setFormData(prev => ({ ...prev, rating: newValue }));
  };
  
  // Handle submit review
  const handleSubmitReview = (e) => {
    e.preventDefault();
    
    if (!formData.title) {
      return; // Title is required
    }
    
    if (!replyTo && (!formData.rating || formData.rating < 1)) {
      return; // Rating is required for top-level reviews
    }
    
    const reviewData = {
      title: formData.title,
      content: formData.content,
      rating: replyTo ? undefined : formData.rating,
      parentId: replyTo ? replyTo.id : undefined
    };
    
    addReview.mutate({ 
      productId, 
      reviewData 
    }, {
      onSuccess: () => {
        // Reset form
        setFormData({
          title: '',
          content: '',
          rating: 0
        });
        setReplyTo(null);
        setShowReviewForm(false);
      }
    });
  };
  
  // Render a single review
  const renderReview = (review, isReply = false) => (
    <Card 
      key={review.id} 
      variant={isReply ? "outlined" : "elevation"} 
      sx={{ 
        mb: 2, 
        ml: isReply ? 4 : 0,
        bgcolor: isReply ? 'background.paper' : undefined
      }}
    >
      <CardContent>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <Avatar sx={{ mr: 1 }}>
              {review.first_name ? review.first_name[0] : '?'}
            </Avatar>
            <Box>
              <Typography variant="subtitle1">
                {review.first_name} {review.last_name}
              </Typography>
              <Typography variant="caption" color="text.secondary">
                {formatDate(review.created_at)}
              </Typography>
            </Box>
          </Box>
          
          {review.is_verified_purchase && (
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <VerifiedIcon color="primary" fontSize="small" sx={{ mr: 0.5 }} />
              <Typography variant="caption" color="primary">
                Verified Purchase
              </Typography>
            </Box>
          )}
        </Box>
        
        {!isReply && review.rating && (
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
            <Rating value={review.rating} readOnly precision={0.5} />
            <Typography variant="body2" sx={{ ml: 1 }}>
              ({review.rating}/5)
            </Typography>
          </Box>
        )}
        
        <Typography variant="h6" gutterBottom>{review.title}</Typography>
        
        {review.content && (
          <Typography variant="body2" paragraph>
            {review.content}
          </Typography>
        )}
        
        {isAuthenticated && (
          <Button 
            size="small" 
            startIcon={<CommentIcon />}
            onClick={() => {
              setReplyTo(review);
              setShowReviewForm(true);
              // Scroll to form
              document.getElementById('review-form')?.scrollIntoView({ 
                behavior: 'smooth', 
                block: 'center' 
              });
            }}
          >
            Reply
          </Button>
        )}
      </CardContent>
      
      {/* Render replies */}
      {review.replies && review.replies.length > 0 && (
        <Box sx={{ px: 2, pb: 2 }}>
          {review.replies.map(reply => renderReview(reply, true))}
        </Box>
      )}
    </Card>
  );
  
  return (
    <Box sx={{ mt: 4 }}>
      <Typography variant="h5" component="h2" gutterBottom>
        Customer Reviews
        {reviews && reviews.length > 0 && (
          <Typography component="span" variant="body2" color="text.secondary" sx={{ ml: 1 }}>
            ({reviews.length})
          </Typography>
        )}
      </Typography>
      
      <Divider sx={{ mb: 3 }} />
      
      {/* Write a review button */}
      {isAuthenticated && !permissionLoading && reviewPermission && (
        <Box sx={{ mb: 3 }}>
          {!showReviewForm ? (
            <Button 
              variant="contained" 
              onClick={() => {
                setReplyTo(null);
                setShowReviewForm(true);
              }}
              disabled={!reviewPermission?.canReview}
            >
              Write a Review
            </Button>
          ) : (
            <Button 
              variant="outlined" 
              onClick={() => {
                setReplyTo(null);
                setShowReviewForm(false);
              }}
            >
              Cancel
            </Button>
          )}
          
          {!reviewPermission?.canReview && !reviewPermission?.isAdmin && (
            <Alert severity="info" sx={{ mt: 2 }}>
              {reviewPermission?.reason || 'You need to purchase this product before you can review it.'}
            </Alert>
          )}
        </Box>
      )}
      
      {/* Review form */}
      {showReviewForm && isAuthenticated && reviewPermission && (reviewPermission.canReview || replyTo) && (
        <Paper id="review-form" sx={{ p: 3, mb: 4 }}>
          <Typography variant="h6" gutterBottom>
            {replyTo ? `Reply to ${replyTo.first_name}'s Review` : 'Write a Review'}
          </Typography>
          
          {replyTo && (
            <Alert severity="info" sx={{ mb: 2 }}>
              Replying to: "{replyTo.title}"
              <Button 
                size="small" 
                onClick={() => setReplyTo(null)} 
                sx={{ ml: 2 }}
              >
                Cancel Reply
              </Button>
            </Alert>
          )}
          
          <form onSubmit={handleSubmitReview}>
            <TextField
              fullWidth
              required
              label="Review Title"
              name="title"
              value={formData.title}
              onChange={handleFormChange}
              margin="normal"
            />
            
            {!replyTo && (
              <Box sx={{ my: 2 }}>
                <Typography component="legend">Rating *</Typography>
                <Rating
                  name="rating"
                  value={formData.rating}
                  onChange={handleRatingChange}
                  precision={0.5}
                  size="large"
                />
                {formData.rating === 0 && (
                  <Typography variant="caption" color="error">
                    Please select a rating
                  </Typography>
                )}
              </Box>
            )}
            
            <TextField
              fullWidth
              multiline
              rows={4}
              label="Review"
              name="content"
              value={formData.content}
              onChange={handleFormChange}
              margin="normal"
              placeholder={replyTo ? "Write your reply..." : "Share your experience with this product..."}
            />
            
            <Box sx={{ mt: 3, display: 'flex', justifyContent: 'flex-end' }}>
              <Button
                type="submit"
                variant="contained"
                disabled={
                  addReview.isLoading || 
                  !formData.title || 
                  (!replyTo && formData.rating < 1)
                }
              >
                {addReview.isLoading ? (
                  <CircularProgress size={24} />
                ) : (
                  replyTo ? 'Post Reply' : 'Submit Review'
                )}
              </Button>
            </Box>
          </form>
        </Paper>
      )}
      
      {/* Reviews list */}
      {reviewsLoading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
          <CircularProgress />
        </Box>
      ) : reviews && reviews.length > 0 ? (
        <Box>
          {reviews.map(review => renderReview(review))}
        </Box>
      ) : (
        <Alert severity="info">
          This product doesn't have any reviews yet. Be the first to review it!
        </Alert>
      )}
    </Box>
  );
};

export default ProductReviews;