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 { DatePicker } from '@/components/ui/date-picker';
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';
import { StarRating } from './StarRating';
import { toDateOnly, parseDateOnly } from '@/lib/dateUtils';
import { getErrorMessage } from '@/lib/errorHandler';
import { logger } from '@/lib/logger';
const reviewSchema = z.object({
  rating: z.number().min(0.5).max(5).multipleOf(0.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().positive().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,
    watch,
    formState: {
      errors
    }
  } = useForm<ReviewFormData>({
    resolver: zodResolver(reviewSchema)
  });
  const handleRatingChange = (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 {
      // Insert review first
      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,
        moderation_status: 'pending' as const,
        ...(entityType === 'park' ? {
          park_id: entityId
        } : {
          ride_id: entityId
        })
      };
      
      const { data: review, error: reviewError } = await supabase
        .from('reviews')
        .insert([reviewData])
        .select()
        .single();
      
      if (reviewError) throw reviewError;
      
      // Insert photos into review_photos table if any
      if (photos.length > 0 && review) {
        const photoRecords = photos.map((url, index) => ({
          review_id: review.id,
          cloudflare_image_id: url.split('/').slice(-2, -1)[0] || '', // Extract ID from URL
          cloudflare_image_url: url,
          order_index: index,
        }));
        
        const { error: photosError } = await supabase
          .from('review_photos')
          .insert(photoRecords);
        
        if (photosError) {
          logger.error('Failed to insert review photos', { error: getErrorMessage(photosError) });
          // Don't throw - review is already created
        }
      }
      
      toast({
        title: "Review Submitted!",
        description: "Thank you for your review. It will be published after moderation."
      });
      reset();
      setRating(0);
      setPhotos([]);
      onReviewSubmitted();
    } catch (error: unknown) {
      toast({
        title: "Error",
        description: getErrorMessage(error),
        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>
            <StarRating rating={rating} onChange={handleRatingChange} interactive={true} showLabel={true} size="lg" />
            {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>Visit Date</Label>
            <DatePicker
              date={watch('visit_date') ? parseDateOnly(watch('visit_date') || '') : undefined}
              onSelect={(date) => setValue('visit_date', date ? toDateOnly(date) : '')}
              placeholder="When did you visit?"
              disableFuture={true}
              fromYear={1950}
            />
            <p className="text-xs text-muted-foreground">
              Select the date of your visit to help others understand when this experience occurred.
            </p>
          </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,
            setValueAs: (v) => v === '' || isNaN(v) ? undefined : v
          })} />
            </div>}

          {/* Photo Upload */}
          

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