import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Star, Send } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { supabase } from '@/integrations/supabase/client';
import { toast } from '@/hooks/use-toast';
import { PhotoUpload } from '@/components/upload/PhotoUpload';

const reviewSchema = z.object({
  rating: z.number().min(1).max(5),
  title: z.string().optional(),
  content: z.string().min(10, 'Review must be at least 10 characters long'),
  visit_date: z.string().optional(),
  wait_time_minutes: z.number().optional(),
  photos: z.array(z.string()).optional()
});

type ReviewFormData = z.infer<typeof reviewSchema>;

interface ReviewFormProps {
  entityType: 'park' | 'ride';
  entityId: string;
  entityName: string;
  onReviewSubmitted: () => void;
}

export function ReviewForm({ entityType, entityId, entityName, onReviewSubmitted }: ReviewFormProps) {
  const { user } = useAuth();
  const [rating, setRating] = useState(0);
  const [submitting, setSubmitting] = useState(false);
  const [photos, setPhotos] = useState<string[]>([]);

  const {
    register,
    handleSubmit,
    reset,
    setValue,
    formState: { errors }
  } = useForm<ReviewFormData>({
    resolver: zodResolver(reviewSchema)
  });

  const handleRatingClick = (selectedRating: number) => {
    setRating(selectedRating);
    setValue('rating', selectedRating);
  };

  const onSubmit = async (data: ReviewFormData) => {
    if (!user) {
      toast({
        title: "Authentication Required",
        description: "Please sign in to submit a review.",
        variant: "destructive"
      });
      return;
    }

    setSubmitting(true);
    try {
      const reviewData = {
        user_id: user.id,
        rating: data.rating,
        title: data.title || null,
        content: data.content,
        visit_date: data.visit_date || null,
        wait_time_minutes: data.wait_time_minutes || null,
        photos: photos.length > 0 ? photos : null,
        moderation_status: 'pending' as const,
        ...(entityType === 'park' ? { park_id: entityId } : { ride_id: entityId })
      };

      const { error } = await supabase
        .from('reviews')
        .insert([reviewData]);

      if (error) throw error;

      toast({
        title: "Review Submitted!",
        description: "Thank you for your review. It will be published after moderation."
      });

      reset();
      setRating(0);
      setPhotos([]);
      onReviewSubmitted();
    } catch (error) {
      console.error('Error submitting review:', error);
      toast({
        title: "Error",
        description: "Failed to submit review. Please try again.",
        variant: "destructive"
      });
    } finally {
      setSubmitting(false);
    }
  };

  if (!user) {
    return (
      <Card>
        <CardContent className="p-6 text-center">
          <Star className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
          <h3 className="text-lg font-semibold mb-2">Share Your Experience</h3>
          <p className="text-muted-foreground mb-4">
            Sign in to write a review for {entityName}
          </p>
          <Button onClick={() => window.location.href = '/auth'}>
            Sign In to Review
          </Button>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Write a Review for {entityName}</CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          {/* Rating */}
          <div className="space-y-2">
            <Label>Rating *</Label>
            <div className="flex items-center gap-1">
              {Array.from({ length: 5 }, (_, i) => (
                <button
                  key={i}
                  type="button"
                  onClick={() => handleRatingClick(i + 1)}
                  className="text-2xl hover:scale-110 transition-transform"
                >
                  <Star
                    className={`w-8 h-8 ${
                      i < rating 
                        ? 'fill-yellow-400 text-yellow-400' 
                        : 'text-muted-foreground hover:text-yellow-400'
                    }`}
                  />
                </button>
              ))}
              {rating > 0 && (
                <span className="ml-2 text-sm text-muted-foreground">
                  {rating} star{rating !== 1 ? 's' : ''}
                </span>
              )}
            </div>
            {errors.rating && (
              <p className="text-sm text-destructive">Please select a rating</p>
            )}
          </div>

          {/* Title */}
          <div className="space-y-2">
            <Label htmlFor="title">Review Title</Label>
            <Input
              id="title"
              placeholder="Give your review a title"
              {...register('title')}
            />
          </div>

          {/* Content */}
          <div className="space-y-2">
            <Label htmlFor="content">Your Review *</Label>
            <Textarea
              id="content"
              placeholder="Share your experience..."
              rows={4}
              {...register('content')}
            />
            {errors.content && (
              <p className="text-sm text-destructive">{errors.content.message}</p>
            )}
          </div>

          {/* Visit Date */}
          <div className="space-y-2">
            <Label htmlFor="visit_date">Visit Date</Label>
            <Input
              id="visit_date"
              type="date"
              {...register('visit_date')}
            />
          </div>

          {/* Wait Time (for rides) */}
          {entityType === 'ride' && (
            <div className="space-y-2">
              <Label htmlFor="wait_time">Wait Time (minutes)</Label>
              <Input
                id="wait_time"
                type="number"
                min="0"
                placeholder="How long did you wait?"
                {...register('wait_time_minutes', { valueAsNumber: true })}
              />
            </div>
          )}

          {/* Photo Upload */}
          <div className="space-y-2">
            <Label>Photos (Optional)</Label>
            <PhotoUpload
              maxFiles={5}
              onUploadComplete={setPhotos}
              onError={(error) => {
                toast({
                  title: "Upload Error",
                  description: error,
                  variant: "destructive"
                });
              }}
              variant="compact"
              className="max-w-full"
            />
            <p className="text-xs text-muted-foreground">
              Add up to 5 photos to share your experience
            </p>
          </div>

          <Button type="submit" disabled={submitting} className="w-full">
            <Send className="w-4 h-4 mr-2" />
            {submitting ? 'Submitting...' : 'Submit Review'}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}