
'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { Star, Send, Loader2 } from 'lucide-react';
import { Card, CardContent, CardDescription, 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 { toast } from 'sonner';

interface ReviewFormProps {
  contractId: string;
  contractorId: string;
  contractorName: string;
  onSuccess?: () => void;
}

export function ReviewForm({
  contractId,
  contractorId,
  contractorName,
  onSuccess,
}: ReviewFormProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState<{
    overallRating: number;
    qualityRating: number;
    timelinessRating: number;
    communicationRating: number;
    valueRating: number;
    title: string;
    comment: string;
  }>({
    overallRating: 0,
    qualityRating: 0,
    timelinessRating: 0,
    communicationRating: 0,
    valueRating: 0,
    title: '',
    comment: '',
  });

  const ratingCategories = [
    { key: 'overallRating', label: 'Overall Experience' },
    { key: 'qualityRating', label: 'Work Quality' },
    { key: 'timelinessRating', label: 'Timeliness' },
    { key: 'communicationRating', label: 'Communication' },
    { key: 'valueRating', label: 'Value for Money' },
  ];

  const handleStarClick = (category: string, rating: number) => {
    setFormData((prev) => ({ ...prev, [category]: rating }));
  };

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

    if (formData.overallRating === 0) {
      toast.error('Please provide an overall rating');
      return;
    }

    if (!formData.comment.trim()) {
      toast.error('Please write a review comment');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch('/api/reviews', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          contractId,
          contractorId,
          ...formData,
        }),
      });

      if (response.ok) {
        toast.success('Review submitted successfully!');
        onSuccess?.();
        router.refresh();
      } else {
        const data = await response.json();
        toast.error(data.error || 'Failed to submit review');
      }
    } catch (error) {
      toast.error('An error occurred while submitting your review');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>Rate Your Experience</CardTitle>
        <CardDescription>
          Share your feedback for {contractorName}
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Rating Categories */}
          {ratingCategories.map((category) => {
            const currentValue = formData[category.key as keyof typeof formData];
            const numValue = typeof currentValue === 'number' ? currentValue : 0;
            
            return (
              <div key={category.key} className="space-y-2">
                <Label>{category.label}</Label>
                <div className="flex gap-2">
                  {[1, 2, 3, 4, 5].map((rating) => {
                    const isSelected = numValue >= rating;
                    return (
                      <motion.button
                        key={rating}
                        type="button"
                        whileHover={{ scale: 1.1 }}
                        whileTap={{ scale: 0.9 }}
                        onClick={() => handleStarClick(category.key, rating)}
                        className="focus:outline-none"
                      >
                        <Star
                          className={`w-8 h-8 transition-colors ${
                            isSelected
                              ? 'text-amber-500 fill-amber-500'
                              : 'text-gray-300'
                          }`}
                        />
                      </motion.button>
                    );
                  })}
                  <span className="ml-2 text-sm text-muted-foreground">
                    {numValue > 0
                      ? `${numValue}.0`
                      : 'Not rated'}
                  </span>
                </div>
              </div>
            );
          })}

          {/* Review Title */}
          <div className="space-y-2">
            <Label htmlFor="title">Review Title (Optional)</Label>
            <Input
              id="title"
              placeholder="Summarize your experience"
              value={formData.title}
              onChange={(e) => setFormData((prev) => ({ ...prev, title: e.target.value }))}
            />
          </div>

          {/* Review Comment */}
          <div className="space-y-2">
            <Label htmlFor="comment">Your Review *</Label>
            <Textarea
              id="comment"
              placeholder="Tell us about your experience with this contractor..."
              rows={5}
              value={formData.comment}
              onChange={(e) =>
                setFormData((prev) => ({ ...prev, comment: e.target.value }))
              }
              required
            />
          </div>

          {/* Submit Button */}
          <Button type="submit" disabled={loading} className="w-full">
            {loading ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Submitting...
              </>
            ) : (
              <>
                <Send className="w-4 h-4 mr-2" />
                Submit Review
              </>
            )}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}
