"use client";

import { useState } from "react";
import { ReviewCard } from "./review-card";
import { RatingSummary } from "./rating-summary";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";

interface Review {
  id: string;
  rating: number;
  comment: string | null;
  createdAt: Date | string;
  user: {
    id?: string;
    name: string | null;
    image: string | null;
  };
}

interface ReviewListProps {
  reviews: Review[];
  avgRating: number;
  reviewCount: number;
}

type SortOption = "recent" | "highest" | "lowest";

export function ReviewList({ reviews, avgRating, reviewCount }: ReviewListProps) {
  const [sortBy, setSortBy] = useState<SortOption>("recent");
  const [filterRating, setFilterRating] = useState<number | null>(null);
  const [displayCount, setDisplayCount] = useState(10);

  // Filter reviews by rating
  const filteredReviews = filterRating
    ? reviews.filter((review) => review.rating === filterRating)
    : reviews;

  // Sort reviews
  const sortedReviews = [...filteredReviews].sort((a, b) => {
    switch (sortBy) {
      case "highest":
        return b.rating - a.rating;
      case "lowest":
        return a.rating - b.rating;
      case "recent":
      default:
        const dateA = typeof a.createdAt === 'string' ? new Date(a.createdAt) : a.createdAt;
        const dateB = typeof b.createdAt === 'string' ? new Date(b.createdAt) : b.createdAt;
        return dateB.getTime() - dateA.getTime();
    }
  });

  // Paginate reviews
  const displayedReviews = sortedReviews.slice(0, displayCount);
  const hasMore = sortedReviews.length > displayCount;

  if (reviewCount === 0) {
    return (
      <div className="text-center py-12 bg-muted/30 rounded-lg">
        <p className="text-muted-foreground">No reviews yet</p>
        <p className="text-sm text-muted-foreground mt-1">
          Be the first to review this tour!
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Rating Summary */}
      <RatingSummary
        avgRating={avgRating}
        reviewCount={reviewCount}
        reviews={reviews}
        onFilterByRating={setFilterRating}
        selectedRating={filterRating}
      />

      {/* Sort Controls */}
      <div className="flex items-center justify-between">
        <h3 className="font-semibold">
          {filteredReviews.length} {filteredReviews.length === 1 ? "Review" : "Reviews"}
        </h3>
        <Select value={sortBy} onValueChange={(value) => setSortBy(value as SortOption)}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Sort by" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="recent">Most Recent</SelectItem>
            <SelectItem value="highest">Highest Rating</SelectItem>
            <SelectItem value="lowest">Lowest Rating</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Review Cards */}
      <div className="space-y-4">
        {displayedReviews.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            No {filterRating}-star reviews found
          </div>
        ) : (
          displayedReviews.map((review) => (
            <ReviewCard key={review.id} review={review} />
          ))
        )}
      </div>

      {/* Load More Button */}
      {hasMore && (
        <div className="text-center">
          <Button
            variant="outline"
            onClick={() => setDisplayCount((prev) => prev + 10)}
          >
            Load More Reviews
          </Button>
        </div>
      )}
    </div>
  );
}
