134 lines
4.0 KiB
TypeScript
134 lines
4.0 KiB
TypeScript
"use client"
|
||
|
||
import type React from "react"
|
||
import { useState } from "react"
|
||
import { Button } from "./ui/button"
|
||
import { Textarea } from "./ui/textarea"
|
||
import { Label } from "./ui/label"
|
||
import { Star } from 'lucide-react'
|
||
import { useAuth } from "@/contexts/auth-context"
|
||
import Link from "next/link"
|
||
|
||
interface ReviewFormProps {
|
||
productId: number
|
||
}
|
||
|
||
export function ReviewForm({ productId }: ReviewFormProps) {
|
||
const [rating, setRating] = useState(0)
|
||
const [comment, setComment] = useState("")
|
||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||
const { isLoggedIn, user } = useAuth()
|
||
|
||
const handleSubmit = async (e: React.FormEvent) => {
|
||
e.preventDefault()
|
||
setIsSubmitting(true)
|
||
|
||
try {
|
||
// Добавляем console.log для отладки
|
||
console.log('Submitting review with data:', {
|
||
productId,
|
||
rating,
|
||
comment,
|
||
username: user?.name || 'Anonymous'
|
||
});
|
||
|
||
const reviewData = {
|
||
product_id: productId,
|
||
username: user?.name || "Anonymous",
|
||
rating: rating,
|
||
comment: comment
|
||
}
|
||
|
||
const response = await fetch(`http://localhost:8080/product/${productId}/reviews`, {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
},
|
||
body: JSON.stringify(reviewData)
|
||
})
|
||
|
||
// Добавляем console.log для отладки ответа
|
||
console.log('Response status:', response.status);
|
||
const responseData = await response.json();
|
||
console.log('Response data:', responseData);
|
||
|
||
if (!response.ok) {
|
||
throw new Error(`HTTP error! status: ${response.status}`);
|
||
}
|
||
|
||
// Очищаем форму после успешной отправки
|
||
setRating(0)
|
||
setComment("")
|
||
alert("Отзыв успешно добавлен!")
|
||
|
||
// Перезагружаем страницу для отображения нового отзыва
|
||
window.location.reload()
|
||
} catch (error) {
|
||
console.error("Error submitting review:", error)
|
||
alert("Произошла ошибка при отправке отзыва. Пожалуйста, попробуйте еще раз.")
|
||
} finally {
|
||
setIsSubmitting(false)
|
||
}
|
||
}
|
||
|
||
if (!isLoggedIn) {
|
||
return (
|
||
<p className="text-gray-600">
|
||
Чтобы оставить отзыв, пожалуйста,{" "}
|
||
<Link href="/profile" className="text-blue-600 hover:underline">
|
||
войдите в систему
|
||
</Link>
|
||
.
|
||
</p>
|
||
)
|
||
}
|
||
|
||
return (
|
||
<form onSubmit={handleSubmit} className="space-y-4">
|
||
<div>
|
||
<Label htmlFor="rating">Рейтинг</Label>
|
||
<div className="flex items-center gap-1">
|
||
{[1, 2, 3, 4, 5].map((star) => (
|
||
<button
|
||
key={star}
|
||
type="button"
|
||
onClick={() => setRating(star)}
|
||
className="focus:outline-none"
|
||
>
|
||
<Star
|
||
className={`h-6 w-6 ${
|
||
star <= rating ? "text-yellow-400 fill-yellow-400" : "text-gray-300"
|
||
}`}
|
||
/>
|
||
</button>
|
||
))}
|
||
</div>
|
||
{/* Добавляем скрытое поле для отображения выбранного рейтинга */}
|
||
<input
|
||
type="hidden"
|
||
name="rating"
|
||
value={rating}
|
||
required
|
||
/>
|
||
</div>
|
||
<div>
|
||
<Label htmlFor="comment">Комментарий</Label>
|
||
<Textarea
|
||
id="comment"
|
||
value={comment}
|
||
onChange={(e) => setComment(e.target.value)}
|
||
rows={4}
|
||
placeholder="Напишите ваш отзыв здесь..."
|
||
required
|
||
/>
|
||
</div>
|
||
<Button
|
||
type="submit"
|
||
disabled={isSubmitting || rating === 0 || comment.trim() === ""}
|
||
>
|
||
{isSubmitting ? "Отправка..." : "Отправить отзыв"}
|
||
</Button>
|
||
</form>
|
||
)
|
||
}
|