
'use client';

import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Star } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useToast } from '@/hooks/use-toast';
import { Input } from '@/components/ui/input';
import { useFirestore, useUser, useDoc, useMemoFirebase } from '@/firebase';
import { addDocumentNonBlocking } from '@/firebase/non-blocking-updates';
import { collection, serverTimestamp, doc } from 'firebase/firestore';
import type { User } from '@/lib/types';

export default function ReviewForm({ businessId }: { businessId: string }) {
  const [rating, setRating] = useState(0);
  const [hoverRating, setHoverRating] = useState(0);
  const { toast } = useToast();
  const { user, isUserLoading } = useUser();
  const firestore = useFirestore();

  const userDocRef = useMemoFirebase(() => user ? doc(firestore, 'users', user.uid) : null, [user, firestore]);
  const { data: currentUser, isLoading: isCurrentUserLoading } = useDoc<User>(userDocRef);

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!user || !firestore || !currentUser) {
        toast({
            variant: "destructive",
            title: "Authentication Error",
            description: "You must be logged in to leave a review.",
        });
        return;
    }
    if (rating === 0) {
        toast({
            variant: "destructive",
            title: "Rating Missing",
            description: "Please select a star rating.",
        });
        return;
    }

    const formData = new FormData(e.currentTarget);
    const comment = formData.get('comment') as string;

    const reviewData = {
        businessId,
        userId: user.uid,
        userName: currentUser.name,
        userAvatar: currentUser.avatarUrl,
        rating: rating,
        comment: comment,
        createdAt: serverTimestamp(),
    };
    
    const reviewsRef = collection(firestore, 'businesses', businessId, 'reviews');
    addDocumentNonBlocking(reviewsRef, reviewData);

    toast({
        title: "Review Submitted!",
        description: "Thank you for your feedback.",
    });

    (e.target as HTMLFormElement).reset();
    setRating(0);
  };


  return (
    <Card className="sticky top-24">
      <CardHeader>
        <CardTitle className="text-2xl text-primary">Leave a Review</CardTitle>
        <CardDescription>Share your experience with the community.</CardDescription>
      </CardHeader>
      <CardContent>
        {isUserLoading || isCurrentUserLoading ? (
            <p>Loading...</p>
        ) : !user ? (
            <div className='text-center'>
                <p className='text-muted-foreground'>You must be logged in to leave a review.</p>
                <Button asChild className='mt-4'>
                    <a href="/login">Login</a>
                </Button>
            </div>
        ) : (
            <form onSubmit={handleSubmit} className="space-y-6">
            <div className="space-y-2">
                <label className="font-medium text-sm">Your Name</label>
                <Input value={currentUser?.name || 'Anonymous'} disabled />
            </div>
            <div className="space-y-2">
                <label className="font-medium text-sm">Your Rating</label>
                <div className="flex items-center gap-1">
                {[...Array(5)].map((_, index) => {
                    const starValue = index + 1;
                    return (
                    <button
                        type="button"
                        key={starValue}
                        onMouseEnter={() => setHoverRating(starValue)}
                        onMouseLeave={() => setHoverRating(0)}
                        onClick={() => setRating(starValue)}
                        aria-label={`Rate ${starValue} stars`}
                    >
                        <Star
                        className={cn(
                            'h-8 w-8 cursor-pointer transition-colors',
                            starValue <= (hoverRating || rating)
                            ? 'text-yellow-400 fill-yellow-400'
                            : 'text-muted-foreground/50'
                        )}
                        />
                    </button>
                    );
                })}
                </div>
                <input type="hidden" name="rating" value={rating} />
            </div>
            <div className="space-y-2">
                <label htmlFor="comment" className="font-medium text-sm">Your Comment</label>
                <Textarea id="comment" name="comment" placeholder="Tell us about your experience..." required minLength={10} />
            </div>
            <Button type="submit" className="w-full bg-accent hover:bg-accent/90" disabled={rating === 0}>
                Submit Review
            </Button>
            </form>
        )}
      </CardContent>
    </Card>
  );
}
