import { useState } from 'react';
import { useUserReviews } from '@/hooks/reviews/useUserReviews';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Star, Calendar, MapPin, Edit, Trash2, ThumbsUp } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { StarRating } from '@/components/reviews/StarRating';
import { Button } from '@/components/ui/button';
import { Link } from 'react-router-dom';
import { toast } from 'sonner';
import { getErrorMessage } from '@/lib/errorHandler';

interface ReviewWithEntity {
  id: string;
  rating: number;
  title: string | null;
  content: string | null;
  visit_date: string | null;
  wait_time_minutes: number | null;
  helpful_votes: number;
  moderation_status: string;
  created_at: string;
  parks?: {
    id: string;
    name: string;
    slug: string;
  } | null;
  rides?: {
    id: string;
    name: string;
    slug: string;
    parks?: {
      name: string;
      slug: string;
    } | null;
  } | null;
}

interface UserReviewsListProps {
  userId: string;
  reviewCount: number;
}

export function UserReviewsList({ userId, reviewCount }: UserReviewsListProps) {
  const [filter, setFilter] = useState<'all' | 'parks' | 'rides'>('all');
  const [sortBy, setSortBy] = useState<'date' | 'rating'>('date');

  // Use cached user reviews hook
  const { data: reviews = [], isLoading: loading } = useUserReviews(userId, filter, sortBy);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'approved':
        return <Badge variant="default">Approved</Badge>;
      case 'pending':
        return <Badge variant="secondary">Pending Review</Badge>;
      case 'rejected':
        return <Badge variant="destructive">Rejected</Badge>;
      default:
        return null;
    }
  };

  if (loading) {
    return (
      <div className="space-y-4">
        {Array.from({ length: 3 }, (_, i) => (
          <Card key={i} className="animate-pulse">
            <CardContent className="p-6">
              <div className="space-y-3">
                <div className="h-4 bg-muted rounded w-1/4"></div>
                <div className="h-4 bg-muted rounded w-1/6"></div>
                <div className="h-20 bg-muted rounded"></div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  if (reviewCount === 0) {
    return (
      <Card>
        <CardContent className="py-12">
          <div className="text-center">
            <Star className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
            <h3 className="text-xl font-semibold mb-2">No Reviews Yet</h3>
            <p className="text-muted-foreground mb-4">
              Start sharing your park and ride experiences
            </p>
            <div className="flex gap-2 justify-center">
              <Button asChild>
                <Link to="/parks">Browse Parks</Link>
              </Button>
              <Button variant="outline" asChild>
                <Link to="/rides">Browse Rides</Link>
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  const stats = {
    total: reviews.length,
    parks: reviews.filter(r => r.parks).length,
    rides: reviews.filter(r => r.rides).length,
    avgRating: reviews.length > 0 
      ? (reviews.reduce((sum, r) => sum + r.rating, 0) / reviews.length).toFixed(1)
      : '0'
  };

  return (
    <div className="space-y-6">
      {/* Statistics */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="pt-6">
            <div className="text-2xl font-bold">{stats.total}</div>
            <div className="text-sm text-muted-foreground">Total Reviews</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <div className="text-2xl font-bold">{stats.parks}</div>
            <div className="text-sm text-muted-foreground">Park Reviews</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <div className="text-2xl font-bold">{stats.rides}</div>
            <div className="text-sm text-muted-foreground">Ride Reviews</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <div className="text-2xl font-bold flex items-center gap-1">
              <Star className="w-5 h-5 fill-primary text-primary" />
              {stats.avgRating}
            </div>
            <div className="text-sm text-muted-foreground">Avg Rating</div>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <div className="flex gap-4">
        <Select value={filter} onValueChange={(value) => setFilter(value as typeof filter)}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Filter by type" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Reviews</SelectItem>
            <SelectItem value="parks">Parks Only</SelectItem>
            <SelectItem value="rides">Rides Only</SelectItem>
          </SelectContent>
        </Select>

        <Select value={sortBy} onValueChange={(value) => setSortBy(value as typeof sortBy)}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Sort by" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="date">Most Recent</SelectItem>
            <SelectItem value="rating">Highest Rated</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Reviews List */}
      <div className="space-y-4">
        {reviews.map((review) => {
          const entityName = review.parks?.name || review.rides?.name || 'Unknown';
          const entitySlug = review.parks?.slug || review.rides?.slug || '';
          const entityType = review.parks ? 'park' : 'ride';
          const entityPath = review.parks 
            ? `/parks/${entitySlug}` 
            : review.rides 
              ? `/parks/${review.rides.parks?.slug}/rides/${entitySlug}`
              : '#';

          return (
            <Card key={review.id}>
              <CardContent className="p-6">
                <div className="space-y-3">
                  {/* Header */}
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <Link 
                          to={entityPath}
                          className="font-semibold hover:underline"
                        >
                          {entityName}
                        </Link>
                        <Badge variant="outline">
                          {entityType === 'park' ? 'Park' : 'Ride'}
                        </Badge>
                        {getStatusBadge(review.moderation_status)}
                      </div>
                      {review.rides?.parks && (
                        <Link 
                          to={`/parks/${review.rides.parks.slug}`}
                          className="text-sm text-muted-foreground hover:underline"
                        >
                          at {review.rides.parks.name}
                        </Link>
                      )}
                    </div>
                    <div className="flex items-center gap-1">
                      <StarRating rating={review.rating} size="sm" />
                      <span className="ml-1 text-sm font-medium">
                        {review.rating}
                      </span>
                    </div>
                  </div>

                  {/* Title */}
                  {review.title && (
                    <h4 className="font-medium">{review.title}</h4>
                  )}

                  {/* Content */}
                  {review.content && (
                    <p className="text-muted-foreground leading-relaxed">
                      {review.content}
                    </p>
                  )}

                  {/* Metadata */}
                  <div className="flex items-center gap-4 text-sm text-muted-foreground">
                    <div className="flex items-center gap-1">
                      <Calendar className="w-3 h-3" />
                      {formatDate(review.created_at)}
                    </div>
                    {review.visit_date && (
                      <div className="flex items-center gap-1">
                        <MapPin className="w-3 h-3" />
                        Visited {formatDate(review.visit_date)}
                      </div>
                    )}
                    {review.wait_time_minutes && (
                      <span>Wait: {review.wait_time_minutes} min</span>
                    )}
                    <div className="flex items-center gap-1">
                      <ThumbsUp className="w-3 h-3" />
                      {review.helpful_votes} helpful
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>
    </div>
  );
}
