"use client"

import type React from "react"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Star, X, Camera, Upload, Image as ImageIcon, Trash2, Plus, Check } from "lucide-react"

interface ReviewFormProps {
  facilityName: string
  onClose: () => void
  onSubmit: (review: any) => void
}

export function ReviewForm({ facilityName, onClose, onSubmit }: ReviewFormProps) {
  const [rating, setRating] = useState(0)
  const [hoverRating, setHoverRating] = useState(0)
  const [title, setTitle] = useState("")
  const [content, setContent] = useState("")
  const [photos, setPhotos] = useState<File[]>([])
  const [relationship, setRelationship] = useState("")
  const [stayDuration, setStayDuration] = useState("")
  const [careQualityRating, setCareQualityRating] = useState(0)
  const [staffRating, setStaffRating] = useState(0)
  const [facilitiesRating, setFacilitiesRating] = useState(0)
  const [valueRating, setValueRating] = useState(0)
  const [wouldRecommend, setWouldRecommend] = useState<boolean | null>(null)
  const [uploadProgress, setUploadProgress] = useState<{ [key: string]: number }>({})

  const handlePhotoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || [])
    setPhotos((prev) => [...prev, ...files].slice(0, 5)) // Max 5 photos
  }

  const removePhoto = (index: number) => {
    setPhotos((prev) => prev.filter((_, i) => i !== index))
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const review = {
      rating,
      title,
      content,
      photos,
      relationship,
      stayDuration,
      careQualityRating,
      staffRating,
      facilitiesRating,
      valueRating,
      wouldRecommend,
      date: new Date().toISOString(),
    }
    onSubmit(review)
    onClose()
  }

  const StarRating = ({ value, onChange, label, hoverValue, onHover, onLeave }: {
    value: number
    onChange: (rating: number) => void
    label: string
    hoverValue?: number
    onHover?: (rating: number) => void
    onLeave?: () => void
  }) => (
    <div className="space-y-2">
      <Label className="font-body font-medium">{label}</Label>
      <div className="flex items-center gap-2">
        {[1, 2, 3, 4, 5].map((star) => (
          <button
            key={star}
            type="button"
            className="p-1 hover:scale-110 transition-transform"
            onMouseEnter={() => onHover?.(star)}
            onMouseLeave={() => onLeave?.()}
            onClick={() => onChange(star)}
          >
            <Star
              className={`h-6 w-6 transition-colors ${
                star <= (hoverValue || value) ? "fill-yellow-400 text-yellow-400" : "text-gray-300"
              }`}
            />
          </button>
        ))}
        <span className="ml-2 text-sm text-gray-600 min-w-[80px]">
          {(hoverValue || value) > 0 && (
            <>
              {hoverValue || value} star{(hoverValue || value) !== 1 ? "s" : ""} -{" "}
              {(hoverValue || value) === 5
                ? "Excellent"
                : (hoverValue || value) === 4
                  ? "Very Good"
                  : (hoverValue || value) === 3
                    ? "Good"
                    : (hoverValue || value) === 2
                      ? "Fair"
                      : "Poor"}
            </>
          )}
        </span>
      </div>
    </div>
  )

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
      <Card className="w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="font-heading text-xl">Write a Review for {facilityName}</CardTitle>
            <Button variant="ghost" size="sm" onClick={onClose}>
              <X className="h-4 w-4" />
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-8">
            {/* Overall Rating */}
            <StarRating
              value={rating}
              onChange={setRating}
              label="Overall Rating *"
              hoverValue={hoverRating}
              onHover={setHoverRating}
              onLeave={() => setHoverRating(0)}
            />

            {/* Detailed Ratings */}
            <div className="bg-blue-50 p-6 rounded-lg space-y-4">
              <h3 className="font-body font-semibold text-lg text-blue-900 mb-4">Detailed Ratings</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <StarRating
                  value={careQualityRating}
                  onChange={setCareQualityRating}
                  label="Care Quality"
                />
                <StarRating
                  value={staffRating}
                  onChange={setStaffRating}
                  label="Staff Friendliness"
                />
                <StarRating
                  value={facilitiesRating}
                  onChange={setFacilitiesRating}
                  label="Facilities & Amenities"
                />
                <StarRating
                  value={valueRating}
                  onChange={setValueRating}
                  label="Value for Money"
                />
              </div>
            </div>

            {/* Recommendation */}
            <div>
              <Label className="font-body font-medium mb-3 block">Would you recommend this facility? *</Label>
              <div className="flex gap-4">
                <button
                  type="button"
                  onClick={() => setWouldRecommend(true)}
                  className={`flex-1 p-4 border-2 rounded-lg transition-all ${
                    wouldRecommend === true
                      ? "border-green-500 bg-green-50 text-green-700"
                      : "border-gray-200 hover:border-green-300"
                  }`}
                >
                  <div className="flex items-center justify-center gap-2">
                    <Check className="h-5 w-5" />
                    <span className="font-medium">Yes, I'd recommend</span>
                  </div>
                </button>
                <button
                  type="button"
                  onClick={() => setWouldRecommend(false)}
                  className={`flex-1 p-4 border-2 rounded-lg transition-all ${
                    wouldRecommend === false
                      ? "border-red-500 bg-red-50 text-red-700"
                      : "border-gray-200 hover:border-red-300"
                  }`}
                >
                  <div className="flex items-center justify-center gap-2">
                    <X className="h-5 w-5" />
                    <span className="font-medium">No, I wouldn't recommend</span>
                  </div>
                </button>
              </div>
            </div>

            {/* Relationship */}
            <div>
              <Label className="font-body font-medium mb-2 block">Your Relationship *</Label>
              <select
                value={relationship}
                onChange={(e) => setRelationship(e.target.value)}
                className="w-full p-2 border rounded-lg font-body"
                required
              >
                <option value="">Select your relationship</option>
                <option value="adult-child">Adult Child</option>
                <option value="spouse">Spouse/Partner</option>
                <option value="resident">Current/Former Resident</option>
                <option value="family-member">Other Family Member</option>
                <option value="friend">Friend</option>
              </select>
            </div>

            {/* Stay Duration */}
            <div>
              <Label className="font-body font-medium mb-2 block">Length of Stay</Label>
              <select
                value={stayDuration}
                onChange={(e) => setStayDuration(e.target.value)}
                className="w-full p-2 border rounded-lg font-body"
              >
                <option value="">Select duration</option>
                <option value="less-than-6-months">Less than 6 months</option>
                <option value="6-months-1-year">6 months - 1 year</option>
                <option value="1-2-years">1-2 years</option>
                <option value="2-5-years">2-5 years</option>
                <option value="more-than-5-years">More than 5 years</option>
              </select>
            </div>

            {/* Review Title */}
            <div>
              <Label className="font-body font-medium mb-2 block">Review Title *</Label>
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="Summarize your experience"
                className="w-full p-2 border rounded-lg font-body"
                required
                maxLength={100}
              />
              <p className="text-xs text-gray-500 mt-1">{title.length}/100 characters</p>
            </div>

            {/* Review Content */}
            <div>
              <Label className="font-body font-medium mb-2 block">Your Review *</Label>
              <Textarea
                value={content}
                onChange={(e) => setContent(e.target.value)}
                placeholder="Share details about your experience with this facility..."
                className="w-full min-h-32 font-body"
                required
                maxLength={2000}
              />
              <p className="text-xs text-gray-500 mt-1">{content.length}/2000 characters</p>
            </div>

            {/* Enhanced Photo Upload */}
            <div>
              <Label className="font-body font-medium mb-3 block">Add Photos (Optional)</Label>
              <div className="space-y-4">
                <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 hover:border-blue-400 transition-colors">
                  <div className="text-center">
                    <div className="bg-blue-50 rounded-full w-16 h-16 flex items-center justify-center mx-auto mb-4">
                      <Upload className="h-8 w-8 text-blue-600" />
                    </div>
                    <label className="cursor-pointer">
                      <span className="font-body text-lg font-medium text-gray-900 hover:text-blue-600">
                        Click to upload photos
                      </span>
                      <input 
                        type="file" 
                        multiple 
                        accept="image/*" 
                        onChange={handlePhotoUpload} 
                        className="hidden" 
                      />
                    </label>
                    <p className="font-body text-sm text-gray-500 mt-2">
                      PNG, JPG, GIF up to 10MB each (max 5 photos)
                    </p>
                  </div>
                </div>

                {photos.length > 0 && (
                  <div className="space-y-3">
                    <h4 className="font-body font-medium text-gray-900">Uploaded Photos ({photos.length}/5)</h4>
                    <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                      {photos.map((photo, index) => (
                        <div key={index} className="relative group">
                          <div className="aspect-square bg-gray-100 rounded-lg overflow-hidden">
                            <img
                              src={URL.createObjectURL(photo) || "/placeholder.svg"}
                              alt={`Upload ${index + 1}`}
                              className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
                            />
                          </div>
                          <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg flex items-center justify-center">
                            <button
                              type="button"
                              onClick={() => removePhoto(index)}
                              className="bg-red-500 hover:bg-red-600 text-white rounded-full p-2 transition-colors"
                            >
                              <Trash2 className="h-4 w-4" />
                            </button>
                          </div>
                          <div className="absolute top-2 left-2 bg-white/90 rounded-full px-2 py-1">
                            <span className="text-xs font-medium">{index + 1}</span>
                          </div>
                        </div>
                      ))}
                      
                      {photos.length < 5 && (
                        <label className="aspect-square border-2 border-dashed border-gray-300 rounded-lg flex items-center justify-center cursor-pointer hover:border-blue-400 hover:bg-blue-50 transition-colors">
                          <div className="text-center">
                            <Plus className="h-8 w-8 text-gray-400 mx-auto mb-2" />
                            <span className="text-sm text-gray-500">Add Photo</span>
                          </div>
                          <input 
                            type="file" 
                            accept="image/*" 
                            onChange={handlePhotoUpload} 
                            className="hidden" 
                          />
                        </label>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Guidelines */}
            <div className="bg-blue-50 p-4 rounded-lg">
              <h4 className="font-body font-medium text-blue-900 mb-2">Review Guidelines</h4>
              <ul className="font-body text-sm text-blue-800 space-y-1">
                <li>• Be honest and specific about your experience</li>
                <li>• Focus on care quality, staff, facilities, and services</li>
                <li>• Avoid personal information about residents or staff</li>
                <li>• Reviews are moderated and may take 24-48 hours to appear</li>
              </ul>
            </div>

            {/* Submit Buttons */}
            <div className="flex gap-3 pt-4">
              <Button
                type="submit"
                disabled={!rating || !title || !content || !relationship || wouldRecommend === null}
                className="flex-1 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 font-body text-white"
              >
                <Check className="h-4 w-4 mr-2" />
                Submit Review
              </Button>
              <Button type="button" variant="outline" onClick={onClose} className="font-body bg-transparent">
                <X className="h-4 w-4 mr-2" />
                Cancel
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}
