import React, { useState } from 'react';
import { useForm, usePage } from '@inertiajs/react';
import { Star, Loader2 } from "lucide-react";
import { Button } from "@/Components/ui/button";
import { Textarea } from "@/Components/ui/textarea";
import { toast } from 'sonner';
import { useTranslation } from '@/hooks/useTranslation';

export default function ReviewForm({ productId, onSuccess }) {
    const { auth } = usePage().props;
    const { t } = useTranslation();
    const { data, setData, post, processing, reset } = useForm({ rating: 0, comment: '' });
    const [hoverRating, setHoverRating] = useState(0);

    const submitReview = (e) => {
        e.preventDefault();
        if (data.rating === 0) return toast.error(t("Please select a star rating."));
        
        post(route('marketplace.reviews.store', productId), {
            preserveScroll: true,
            onSuccess: (page) => {
                if (page.props.errors && page.props.errors.error) {
                    toast.error(t(page.props.errors.error));
                } else {
                    toast.success(t("Review submitted successfully!"));
                    reset();
                    onSuccess();
                }
            },
            onError: (errors) => {
                toast.error(t(errors.error || "Failed to submit review."));
            }
        });
    };

    if (!auth.user) {
        return <p className="text-sm text-muted-foreground">{t('Please log in to leave a review.')}</p>;
    }

    return (
        <form onSubmit={submitReview} className="space-y-4 border rounded-xl p-5 bg-card shadow-sm">
            <h4 className="font-bold text-lg">{t('Write a Review')}</h4>
            <div className="flex items-center gap-1">
                {[1, 2, 3, 4, 5].map((star) => (
                    <button
                        type="button"
                        key={star}
                        className="focus:outline-none transition-transform hover:scale-110"
                        onMouseEnter={() => setHoverRating(star)}
                        onMouseLeave={() => setHoverRating(0)}
                        onClick={() => setData('rating', star)}
                    >
                        <Star className={`w-8 h-8 ${star <= (hoverRating || data.rating) ? 'fill-amber-500 text-amber-500' : 'text-muted-foreground/30'}`} />
                    </button>
                ))}
            </div>
            <Textarea 
                placeholder={t("What did you like or dislike? How was the quality?")}
                value={data.comment}
                onChange={e => setData('comment', e.target.value)}
                className="resize-none h-24"
            />
            <Button type="submit" disabled={processing || data.rating === 0} className="w-full sm:w-auto px-8">
                {processing ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null} 
                {t('Submit Review')}
            </Button>
        </form>
    );
}