"use client"

import { useState } from "react"
import { Button } from "./ui/button"
import { Textarea } from "./ui/textarea"
import { Label } from "./ui/label"
import { LogIn, 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 { isLoggedIn } = useAuth()
  const {email} = useAuth();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    const reviewData = {
      username: {email}=useAuth(), // Здесь можно подтянуть имя из Auth-контекста
      rating,
      comment,
    }

    try {
   
      const response = await fetch(`http://localhost:8080/product/1`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(reviewData),
      })

      if (!response.ok) {
        throw new Error("Ошибка при отправке отзыва")
      }

      console.log("Отзыв успешно отправлен!")
      setRating(0)
      setComment("")
    } catch (error) {
      console.error("Ошибка:", error)
    }
  }

  if (!isLoggedIn) {
    return (
      <p className="text-gray-600">
        Чтобы оставить отзыв, пожалуйста, <Link href="/login" 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>
      </div>
      <div>
        <Label htmlFor="comment">Комментарий</Label>
        <Textarea
          id="comment"
          value={comment}
          onChange={(e) => setComment(e.target.value)}
          rows={4}
          placeholder="Напишите ваш отзыв здесь..."
        />
      </div>
      <Button type="submit" disabled={rating === 0 || comment.trim() === ""}>
        Отправить отзыв
      </Button>
    </form>
  )
}
