"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { ReviewForm } from "@/components/review-form"
import { Star, Shield, ThumbsUp, ThumbsDown, ArrowLeft } from "lucide-react"
import Link from "next/link"
import Image from "next/image"

// Mock data - same as facility page
const mockFacility = {
  id: 1,
  name: "Sunrise Senior Living",
  rating: 4.8,
  reviewCount: 127,
  reviews: [
    {
      id: 1,
      author: "Sarah M.",
      rating: 5,
      date: "2024-01-10",
      title: "Excellent care for my mother",
      content:
        "The staff at Sunrise is incredibly caring and professional. My mother has been here for 8 months and has thrived. The activities keep her engaged and the meals are delicious.",
      helpful: 12,
      verified: true,
      relationship: "Adult Child",
      stayDuration: "6 months - 1 year",
      photos: ["/placeholder.svg?height=200&width=300&text=Dining+Room"],
    },
    {
      id: 2,
      author: "Robert K.",
      rating: 4,
      date: "2024-01-05",
      title: "Great community atmosphere",
      content:
        "Dad loves the social activities and has made many friends. The facility is clean and well-maintained. Only minor issue is parking can be limited during events.",
      helpful: 8,
      verified: true,
      relationship: "Adult Child",
      stayDuration: "1-2 years",
    },
    {
      id: 3,
      author: "Jennifer L.",
      rating: 5,
      date: "2023-12-28",
      title: "Peace of mind for our family",
      content:
        "Knowing mom is safe and well-cared for gives us such peace of mind. The communication from staff is excellent and they truly treat residents like family.",
      helpful: 15,
      verified: true,
      relationship: "Adult Child",
      stayDuration: "More than 5 years",
    },
  ],
}

export default function FacilityReviewsPage({ params }: { params: { id: string } }) {
  const [showReviewForm, setShowReviewForm] = useState(false)
  const [reviewFilter, setReviewFilter] = useState("all")
  const [reviewSort, setReviewSort] = useState("newest")
  const [helpfulVotes, setHelpfulVotes] = useState<{
    [key: number]: { helpful: number; unhelpful: number; userVote?: "helpful" | "unhelpful" }
  }>({})

  const handleReviewSubmit = (review: any) => {
    console.log("[v0] Review submitted:", review)
  }

  const handleHelpfulVote = (reviewId: number, voteType: "helpful" | "unhelpful") => {
    setHelpfulVotes((prev) => {
      const current = prev[reviewId] || { helpful: 0, unhelpful: 0 }
      const newVote = { ...current }

      if (current.userVote === "helpful") newVote.helpful--
      if (current.userVote === "unhelpful") newVote.unhelpful--

      if (current.userVote !== voteType) {
        if (voteType === "helpful") newVote.helpful++
        if (voteType === "unhelpful") newVote.unhelpful++
        newVote.userVote = voteType
      } else {
        newVote.userVote = undefined
      }

      return { ...prev, [reviewId]: newVote }
    })
  }

  const filteredReviews = mockFacility.reviews
    .filter((review) => {
      if (reviewFilter === "all") return true
      if (reviewFilter === "5-star") return review.rating === 5
      if (reviewFilter === "4-star") return review.rating === 4
      if (reviewFilter === "3-star") return review.rating === 3
      if (reviewFilter === "2-star") return review.rating === 2
      if (reviewFilter === "1-star") return review.rating === 1
      return true
    })
    .sort((a, b) => {
      if (reviewSort === "newest") return new Date(b.date).getTime() - new Date(a.date).getTime()
      if (reviewSort === "oldest") return new Date(a.date).getTime() - new Date(b.date).getTime()
      if (reviewSort === "highest") return b.rating - a.rating
      if (reviewSort === "lowest") return a.rating - b.rating
      return 0
    })

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <header className="border-b border-border bg-white sticky top-0 z-50">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Link
                href={`/facility/${params.id}`}
                className="flex items-center text-muted-foreground hover:text-foreground"
              >
                <ArrowLeft className="h-5 w-5 mr-2" />
                <span className="font-body">Back to Facility</span>
              </Link>
              <Link href="/" className="flex items-center space-x-2">
                <Image
                  src="/images/geezer-guide-logo.png"
                  alt="Geezer Guide"
                  width={120}
                  height={60}
                  className="h-10 w-auto"
                />
              </Link>
            </div>
            <Button onClick={() => setShowReviewForm(true)} className="bg-primary hover:bg-primary/90 font-body">
              Write a Review
            </Button>
          </div>
        </div>
      </header>

      <div className="container mx-auto px-4 py-6">
        <div className="mb-6">
          <h1 className="font-heading text-3xl text-foreground mb-2">Reviews for {mockFacility.name}</h1>
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2">
              <Star className="h-6 w-6 fill-yellow-400 text-yellow-400" />
              <span className="font-heading text-2xl">{mockFacility.rating}</span>
            </div>
            <span className="font-body text-muted-foreground">
              Based on {mockFacility.reviewCount} verified reviews
            </span>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          {/* Sidebar with filters and stats */}
          <div className="lg:col-span-1">
            <Card className="sticky top-24">
              <CardHeader>
                <CardTitle className="font-heading text-lg">Filter & Sort</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <label className="font-body font-medium text-sm mb-2 block">Filter by Rating</label>
                  <select
                    value={reviewFilter}
                    onChange={(e) => setReviewFilter(e.target.value)}
                    className="w-full p-2 border rounded-lg font-body text-sm"
                  >
                    <option value="all">All Reviews</option>
                    <option value="5-star">5 Stars</option>
                    <option value="4-star">4 Stars</option>
                    <option value="3-star">3 Stars</option>
                    <option value="2-star">2 Stars</option>
                    <option value="1-star">1 Star</option>
                  </select>
                </div>

                <div>
                  <label className="font-body font-medium text-sm mb-2 block">Sort by</label>
                  <select
                    value={reviewSort}
                    onChange={(e) => setReviewSort(e.target.value)}
                    className="w-full p-2 border rounded-lg font-body text-sm"
                  >
                    <option value="newest">Newest First</option>
                    <option value="oldest">Oldest First</option>
                    <option value="highest">Highest Rating</option>
                    <option value="lowest">Lowest Rating</option>
                  </select>
                </div>

                {/* Rating breakdown */}
                <div className="pt-4 border-t">
                  <h4 className="font-body font-medium text-sm mb-3">Rating Breakdown</h4>
                  <div className="space-y-2">
                    {[5, 4, 3, 2, 1].map((rating) => {
                      const count = mockFacility.reviews.filter((r) => r.rating === rating).length
                      const percentage = (count / mockFacility.reviews.length) * 100
                      return (
                        <div key={rating} className="flex items-center gap-2 text-sm">
                          <span className="w-8">{rating}★</span>
                          <div className="flex-1 bg-gray-200 rounded-full h-2">
                            <div className="bg-yellow-400 h-2 rounded-full" style={{ width: `${percentage}%` }} />
                          </div>
                          <span className="w-8 text-gray-600">{count}</span>
                        </div>
                      )
                    })}
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Reviews list */}
          <div className="lg:col-span-3 space-y-6">
            {filteredReviews.map((review) => {
              const votes = helpfulVotes[review.id] || { helpful: review.helpful, unhelpful: 0 }
              return (
                <Card key={review.id}>
                  <CardContent className="p-6">
                    <div className="flex items-start justify-between mb-4">
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <span className="font-body font-semibold">{review.author}</span>
                          {review.verified && (
                            <Badge variant="secondary" className="text-xs font-body">
                              <Shield className="h-3 w-3 mr-1" />
                              Verified
                            </Badge>
                          )}
                        </div>
                        <div className="flex items-center gap-2 mb-2">
                          <div className="flex">
                            {[...Array(5)].map((_, i) => (
                              <Star
                                key={i}
                                className={`h-4 w-4 ${
                                  i < review.rating ? "fill-yellow-400 text-yellow-400" : "text-gray-300"
                                }`}
                              />
                            ))}
                          </div>
                          <span className="font-body text-sm text-muted-foreground">
                            {new Date(review.date).toLocaleDateString('en-US')}
                          </span>
                        </div>
                        <div className="flex gap-4 text-xs text-muted-foreground">
                          <span>Relationship: {review.relationship}</span>
                          {review.stayDuration && <span>Stay: {review.stayDuration}</span>}
                        </div>
                      </div>
                    </div>

                    <h4 className="font-body font-semibold mb-3 text-lg">{review.title}</h4>
                    <p className="font-body text-muted-foreground leading-relaxed mb-4">{review.content}</p>

                    {/* Photos if available */}
                    {review.photos && review.photos.length > 0 && (
                      <div className="mb-4">
                        <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                          {review.photos.map((photo, index) => (
                            <Image
                              key={index}
                              src={photo || "/placeholder.svg"}
                              alt={`Review photo ${index + 1}`}
                              width={200}
                              height={150}
                              className="rounded-lg object-cover"
                            />
                          ))}
                        </div>
                      </div>
                    )}

                    {/* Voting buttons */}
                    <div className="flex items-center gap-4 text-sm pt-4 border-t">
                      <span className="font-body text-muted-foreground">Was this review helpful?</span>
                      <button
                        onClick={() => handleHelpfulVote(review.id, "helpful")}
                        className={`flex items-center gap-1 px-3 py-1 rounded hover:bg-gray-100 ${
                          votes.userVote === "helpful" ? "text-green-600 bg-green-50" : "text-gray-600"
                        }`}
                      >
                        <ThumbsUp className="h-4 w-4" />
                        <span className="font-body">Yes ({votes.helpful})</span>
                      </button>
                      <button
                        onClick={() => handleHelpfulVote(review.id, "unhelpful")}
                        className={`flex items-center gap-1 px-3 py-1 rounded hover:bg-gray-100 ${
                          votes.userVote === "unhelpful" ? "text-red-600 bg-red-50" : "text-gray-600"
                        }`}
                      >
                        <ThumbsDown className="h-4 w-4" />
                        <span className="font-body">No ({votes.unhelpful})</span>
                      </button>
                    </div>
                  </CardContent>
                </Card>
              )
            })}

            {filteredReviews.length === 0 && (
              <Card>
                <CardContent className="p-6 text-center">
                  <p className="font-body text-muted-foreground mb-4">No reviews match your current filter.</p>
                  <Button onClick={() => setReviewFilter("all")} variant="outline" className="font-body">
                    Show All Reviews
                  </Button>
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      </div>

      {showReviewForm && (
        <ReviewForm
          facilityName={mockFacility.name}
          onClose={() => setShowReviewForm(false)}
          onSubmit={handleReviewSubmit}
        />
      )}
    </div>
  )
}
