import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { reviewService, ReviewStats, type Review, type ReviewReply } from '@/services/reviewService';
import { useToast } from '@/hooks/use-toast';
import { 
  Star, 
  ThumbsUp, 
  MessageCircle,
  Share2,
  Camera,
  Send,
  Heart,
  Reply,
  Image,
  Smile
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Progress } from '@/components/ui/progress';
import { ReviewReplyDialog } from '@/components/dashboard/ReviewReplyDialog';
import { ReviewPhotoUpload } from '@/components/dashboard/ReviewPhotoUpload';

const Reviews = () => {
  const { user } = useAuth();
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [replyingToReview, setReplyingToReview] = useState<string | null>(null);
  const [replyContent, setReplyContent] = useState('');
  const [showPhotoUpload, setShowPhotoUpload] = useState(false);
  const [selectedReviewForReply, setSelectedReviewForReply] = useState<Review | null>(null);
  const [reviews, setReviews] = useState<Review[]>([]);
  const [ratingStats, setRatingStats] = useState<ReviewStats>({
    average: 0,
    totalRatings: 0,
    totalReviews: 0,
    breakdown: {}
  });

  useEffect(() => {
    loadReviews();
    loadStats();
  }, []);

  const loadReviews = async () => {
    try {
      setLoading(true);
      const data = await reviewService.getReviews();
      setReviews(data);
    } catch (error) {
      console.error('Error loading reviews:', error);
      toast({
        title: 'Error',
        description: 'Failed to load reviews',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const loadStats = async () => {
    try {
      const stats = await reviewService.getReviewStats();
      setRatingStats(stats);
    } catch (error) {
      console.error('Error loading stats:', error);
    }
  };

  const renderStars = (rating: number, size = 16) => {
    const stars = [];
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 !== 0;

    for (let i = 0; i < fullStars; i++) {
      stars.push(
        <Star 
          key={i} 
          size={size} 
          className="text-yellow-400 fill-yellow-400" 
        />
      );
    }

    if (hasHalfStar) {
      stars.push(
        <Star 
          key="half" 
          size={size} 
          className="text-yellow-400 fill-yellow-400 opacity-50" 
        />
      );
    }

    const remainingStars = 5 - Math.ceil(rating);
    for (let i = 0; i < remainingStars; i++) {
      stars.push(
        <Star 
          key={`empty-${i}`} 
          size={size} 
          className="text-muted-foreground" 
        />
      );
    }

    return stars;
  };

  const handleHelpfulClick = async (reviewId: string) => {
    try {
      await reviewService.markAsHelpful(reviewId);
      setReviews(prevReviews => 
        prevReviews.map(review => 
          review.id === reviewId 
            ? { 
                ...review, 
                isHelpful: !review.isHelpful,
                helpful: review.isHelpful ? review.helpful - 1 : review.helpful + 1
              }
            : review
        )
      );
    } catch (error) {
      console.error('Error marking review as helpful:', error);
      toast({
        title: 'Error',
        description: 'Failed to mark review as helpful',
        variant: 'destructive',
      });
    }
  };

  const handleReplySubmit = async (reviewId: string, content: string, images: string[] = []) => {
    try {
      const newReply = await reviewService.createReply(reviewId, content, images);
      
      setReviews(prevReviews =>
        prevReviews.map(review =>
          review.id === reviewId
            ? { ...review, replies: [...review.replies, newReply] }
            : review
        )
      );

      toast({
        title: 'Success',
        description: 'Reply posted successfully',
      });

      setReplyingToReview(null);
      setReplyContent('');
    } catch (error) {
      console.error('Error posting reply:', error);
      toast({
        title: 'Error',
        description: 'Failed to post reply',
        variant: 'destructive',
      });
    }
  };

  const openReplyDialog = (review: Review) => {
    setSelectedReviewForReply(review);
  };

  return (
    <div className="mobile-safe-top p-4 lg:p-6 space-y-4 lg:space-y-6">
      {/* Mobile Header */}
      <div className="mobile-header">
        <h1 className="mobile-title">Visitor Reviews</h1>
        <p className="text-muted-foreground text-sm">Manage and respond to customer reviews</p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 lg:gap-6">
        {/* Reviews Summary */}
        <div className="lg:col-span-1">
          <div className="mobile-card">
            <div className="p-4 lg:p-6 space-y-4 lg:space-y-6">
              {/* Average Rating */}
              <div className="text-center">
                <h3 className="text-sm font-medium text-muted-foreground mb-2">Average user rating</h3>
                <div className="relative inline-block">
                  <div className="w-16 h-16 lg:w-20 lg:h-20 border-4 border-primary rounded-full flex items-center justify-center mb-3">
                    <span className="text-xl lg:text-2xl font-bold text-primary">{ratingStats.average}</span>
                  </div>
                  <div className="absolute -top-1 -right-1">
                    <Star className="w-5 h-5 lg:w-6 lg:h-6 text-primary fill-primary" />
                  </div>
                </div>
                <p className="text-xs lg:text-sm text-muted-foreground">
                  {ratingStats.totalRatings.toLocaleString()} Ratings & {ratingStats.totalReviews} Reviews
                </p>
              </div>

              {/* Rating Breakdown */}
              <div>
                <h3 className="text-sm font-medium mb-4">Rating breakdown</h3>
                <div className="space-y-3">
                  {Object.entries(ratingStats.breakdown)
                    .reverse()
                    .map(([rating, data]) => (
                    <div key={rating} className="flex items-center gap-3">
                      <span className="text-sm font-medium w-2">{rating}</span>
                      <div className="flex-1">
                        <Progress 
                          value={data.percentage} 
                          className="h-2"
                        />
                      </div>
                      <div className="flex items-center gap-1">
                        <Badge variant="secondary" className="text-xs px-2 py-0.5">
                          {data.count}
                        </Badge>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Reviews List */}
        <div className="lg:col-span-2">
          <div className="mobile-card">
            <div className="p-4 lg:p-6">
              <div className="space-y-4 lg:space-y-6">
                {reviews.map((review) => (
                  <div key={review.id} className="border-b border-border pb-4 lg:pb-6 last:border-b-0 last:pb-0">
                    <div className="flex gap-3 lg:gap-4">
                      <Avatar className="h-10 w-10 lg:h-12 lg:w-12 flex-shrink-0">
                        <AvatarImage src={review.userAvatar} alt={review.userName} />
                        <AvatarFallback>{review.userName.charAt(0)}</AvatarFallback>
                      </Avatar>
                      
                      <div className="flex-1 space-y-2 lg:space-y-3 min-w-0">
                        {/* Review Header */}
                        <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between space-y-2 lg:space-y-0">
                          <div>
                            <h4 className="font-medium text-sm lg:text-base">- {review.userName}</h4>
                            <p className="text-xs lg:text-sm text-muted-foreground">{review.createdAt}</p>
                          </div>
                          <div className="flex items-center gap-2">
                            <div className="flex items-center">
                              {renderStars(review.rating, 14)}
                            </div>
                            <span className="text-xs lg:text-sm font-medium">{review.rating}/5</span>
                          </div>
                        </div>

                        {/* Review Content */}
                        <p className="text-muted-foreground leading-relaxed text-sm lg:text-base">{review.comment}</p>

                        {/* Review Images */}
                        {review.images.length > 0 && (
                          <div className="flex gap-2 flex-wrap">
                            {review.images.map((image, index) => (
                              <div key={index} className="relative group cursor-pointer">
                                <img 
                                  src={image}
                                  alt={`Review image ${index + 1}`}
                                  className="w-16 h-16 lg:w-20 lg:h-20 rounded-lg object-cover transition-transform group-hover:scale-105"
                                />
                                <div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 rounded-lg transition-colors" />
                              </div>
                            ))}
                          </div>
                        )}

                        {/* Review Actions */}
                        <div className="flex flex-wrap items-center gap-2 pt-2">
                          <Button
                            variant={review.isHelpful ? "default" : "outline"}
                            size="sm"
                            onClick={() => handleHelpfulClick(review.id)}
                            className="h-8 text-xs lg:text-sm"
                          >
                            <ThumbsUp className="h-3 w-3 lg:h-4 lg:w-4 mr-1" />
                            <span className="hidden sm:inline">Helpful</span> {review.helpful}
                          </Button>
                          
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => openReplyDialog(review)}
                            className="h-8 text-xs lg:text-sm"
                          >
                            <MessageCircle className="h-3 w-3 lg:h-4 lg:w-4 mr-1" />
                            Reply
                          </Button>
                          
                          <Button variant="outline" size="sm" className="h-8 text-xs lg:text-sm">
                            <Share2 className="h-3 w-3 lg:h-4 lg:w-4 mr-1" />
                            Share
                          </Button>
                        </div>

                        {/* Replies */}
                        {review.replies.length > 0 && (
                          <div className="ml-2 lg:ml-4 space-y-3 lg:space-y-4 pt-3 lg:pt-4 border-l-2 border-muted pl-3 lg:pl-4">
                            {review.replies.map((reply) => (
                              <div key={reply.id} className="flex gap-2 lg:gap-3">
                                <Avatar className="h-6 w-6 lg:h-8 lg:w-8 flex-shrink-0">
                                  <AvatarImage src={reply.authorAvatar} alt={reply.authorName} />
                                  <AvatarFallback className="text-xs">{reply.authorName.charAt(0)}</AvatarFallback>
                                </Avatar>
                                <div className="flex-1 min-w-0">
                                  <div className="bg-muted rounded-lg p-2 lg:p-3">
                                    <div className="flex flex-col lg:flex-row lg:items-center gap-1 lg:gap-2 mb-1">
                                      <span className="text-xs lg:text-sm font-medium">{reply.authorName}</span>
                                      <span className="text-xs text-muted-foreground">{reply.createdAt}</span>
                                    </div>
                                    <p className="text-xs lg:text-sm">{reply.content}</p>
                                  </div>
                                  {reply.images && reply.images.length > 0 && (
                                    <div className="flex gap-1 mt-2">
                                      {reply.images.map((image, idx) => (
                                        <img 
                                          key={idx}
                                          src={image}
                                          alt={`Reply image ${idx + 1}`}
                                          className="w-12 h-12 lg:w-16 lg:h-16 rounded object-cover"
                                        />
                                      ))}
                                    </div>
                                  )}
                                </div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Reply Dialog */}
      {selectedReviewForReply && (
        <ReviewReplyDialog
          review={selectedReviewForReply}
          onReply={handleReplySubmit}
          onClose={() => setSelectedReviewForReply(null)}
        />
      )}
    </div>
  );
};

export default Reviews;