"use client";

import * as React from "react";
import { ReviewRow, RatingSummary } from "@/types/database";
import { RatingSummaryCard } from "@/components/reviews/rating-summary-card";
import { ReviewCard } from "@/components/reviews/review-card";
import { WriteReviewModal } from "@/components/reviews/write-review-modal";
import { Button } from "@/components/ui/button";
import { MessageSquare, Star, Filter, ShieldCheck } from "lucide-react";
import { getReviewsAction } from "@/app/actions/review.actions";

interface ReviewListSectionProps {
  targetType: "AGENT" | "AGENCY" | "PROPERTY";
  targetId: string;
  targetName: string;
  initialSummary: RatingSummary;
  initialReviews: ReviewRow[];
  currentUserId?: string | null;
  isTargetAgent?: boolean;
}

export function ReviewListSection({
  targetType,
  targetId,
  targetName,
  initialSummary,
  initialReviews,
  currentUserId,
  isTargetAgent,
}: ReviewListSectionProps) {
  const [reviews, setReviews] = React.useState<ReviewRow[]>(initialReviews);
  const [summary, setSummary] = React.useState<RatingSummary>(initialSummary);
  const [sortBy, setSortBy] = React.useState<"NEWEST" | "HIGHEST_RATING" | "LOWEST_RATING" | "MOST_HELPFUL">("NEWEST");
  const [filterVerifiedOnly, setFilterVerifiedOnly] = React.useState(false);
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(false);

  const handleSortChange = async (newSort: "NEWEST" | "HIGHEST_RATING" | "LOWEST_RATING" | "MOST_HELPFUL") => {
    setSortBy(newSort);
    setIsLoading(true);
    const res = await getReviewsAction(targetType, targetId, { sortBy: newSort });
    if (res.success) {
      setReviews(res.reviews);
    }
    setIsLoading(false);
  };

  const handleNewReviewSuccess = (newReview: ReviewRow) => {
    setReviews((prev) => [newReview, ...prev]);
    setSummary((prev) => ({
      ...prev,
      totalReviews: prev.totalReviews + 1,
    }));
  };

  const displayedReviews = filterVerifiedOnly
    ? reviews.filter(
        (r) =>
          r.verification_tier === "VERIFIED_BUYER_DEAL" ||
          r.verification_tier === "VERIFIED_INSPECTION"
      )
    : reviews;

  return (
    <section className="space-y-8" id="reviews-section">
      {/* 1. Summary Card */}
      <RatingSummaryCard
        summary={summary}
        targetName={targetName}
        onWriteReviewClick={() => setIsModalOpen(true)}
      />

      {/* 2. Reviews Controls Bar */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-2 border-b border-border">
        <div className="flex items-center gap-2">
          <h3 className="font-bold text-lg text-foreground flex items-center gap-2">
            <span>Client Reviews</span>
            <span className="text-xs font-semibold px-2 py-0.5 rounded-full bg-muted text-muted-foreground">
              {displayedReviews.length}
            </span>
          </h3>
        </div>

        {/* Filters & Sorting */}
        <div className="flex items-center gap-2 flex-wrap">
          {/* Filter Verified Toggle */}
          <button
            type="button"
            onClick={() => setFilterVerifiedOnly(!filterVerifiedOnly)}
            className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors cursor-pointer ${
              filterVerifiedOnly
                ? "bg-amber-500/15 border-amber-500/30 text-amber-700 dark:text-amber-300 font-bold"
                : "border-border text-muted-foreground hover:text-foreground hover:bg-muted/50"
            }`}
          >
            <ShieldCheck className="size-3.5" />
            <span>Verified Deals Only</span>
          </button>

          {/* Sort Tabs */}
          <div className="flex items-center gap-1 bg-muted/60 p-1 rounded-xl border border-border">
            {(
              [
                { id: "NEWEST", label: "Newest" },
                { id: "HIGHEST_RATING", label: "Highest ★" },
                { id: "MOST_HELPFUL", label: "Most Helpful" },
              ] as const
            ).map((tab) => (
              <button
                key={tab.id}
                type="button"
                onClick={() => handleSortChange(tab.id)}
                className={`px-2.5 py-1 rounded-lg text-xs font-semibold transition-all cursor-pointer ${
                  sortBy === tab.id
                    ? "bg-card text-foreground shadow-xs"
                    : "text-muted-foreground hover:text-foreground"
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* 3. Review Cards List */}
      {isLoading ? (
        <div className="py-12 text-center text-xs text-muted-foreground">
          Loading reviews...
        </div>
      ) : displayedReviews.length > 0 ? (
        <div className="space-y-4">
          {displayedReviews.map((review) => (
            <ReviewCard
              key={review.id}
              review={review}
              currentUserId={currentUserId}
              isTargetAgent={isTargetAgent}
            />
          ))}
        </div>
      ) : (
        <div className="rounded-2xl border border-dashed border-border p-12 text-center space-y-3 bg-muted/20">
          <MessageSquare className="size-8 text-muted-foreground mx-auto" />
          <h4 className="font-semibold text-sm text-foreground">No Reviews Found</h4>
          <p className="text-xs text-muted-foreground max-w-sm mx-auto">
            {filterVerifiedOnly
              ? "No verified deal reviews match this filter yet."
              : `Be the first to review your experience with ${targetName}!`}
          </p>
          <Button
            onClick={() => setIsModalOpen(true)}
            size="sm"
            className="bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-semibold rounded-xl"
          >
            Write a Review
          </Button>
        </div>
      )}

      {/* Write Review Modal */}
      <WriteReviewModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        targetType={targetType}
        targetId={targetId}
        targetName={targetName}
        onSuccess={handleNewReviewSuccess}
      />
    </section>
  );
}
