import { useState } from 'react'
import { X, ThumbsUp, ThumbsDown } from 'lucide-react'
import { StarRating } from '@/components/common/StarRating'
import { cn } from '@/lib/utils'
import type { Step } from '@/types'

interface StepRatingData {
  rating: number
  helpful: boolean | null
  review: string
}

interface StepRatingModalProps {
  isOpen: boolean
  onClose: () => void
  onSubmit: (ratings: Map<string, StepRatingData>) => Promise<void>
  librarySteps: Step[]
  isSaving?: boolean
}

export function StepRatingModal({
  isOpen,
  onClose,
  onSubmit,
  librarySteps,
  isSaving = false
}: StepRatingModalProps) {
  // Store ratings for each step
  const [ratings, setRatings] = useState<Map<string, StepRatingData>>(new Map())

  if (!isOpen) return null

  const handleRatingChange = (stepId: string, rating: number) => {
    setRatings(prev => {
      const updated = new Map(prev)
      const existing = updated.get(stepId) || { rating: 0, helpful: null, review: '' }
      updated.set(stepId, { ...existing, rating })
      return updated
    })
  }

  const handleHelpfulChange = (stepId: string, helpful: boolean) => {
    setRatings(prev => {
      const updated = new Map(prev)
      const existing = updated.get(stepId) || { rating: 0, helpful: null, review: '' }
      // Toggle: if clicking same button, set to null
      const newHelpful = existing.helpful === helpful ? null : helpful
      updated.set(stepId, { ...existing, helpful: newHelpful })
      return updated
    })
  }

  const handleReviewChange = (stepId: string, review: string) => {
    setRatings(prev => {
      const updated = new Map(prev)
      const existing = updated.get(stepId) || { rating: 0, helpful: null, review: '' }
      updated.set(stepId, { ...existing, review })
      return updated
    })
  }

  const handleSubmit = async () => {
    // Filter out steps with no rating
    const ratingsToSubmit = new Map(
      Array.from(ratings.entries()).filter(([, data]) => data.rating > 0)
    )

    if (ratingsToSubmit.size === 0) {
      // No ratings to submit, just close
      onClose()
      return
    }

    await onSubmit(ratingsToSubmit)
  }

  const getRating = (stepId: string) => ratings.get(stepId)

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm p-4">
      <div className="glass-card w-full max-w-2xl max-h-[90vh] flex flex-col rounded-2xl shadow-lg">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-white/[0.06] px-6 py-4">
          <div>
            <h2 className="text-lg font-semibold text-white">Rate Your Experience</h2>
            <p className="mt-1 text-sm text-white/70">
              Help others by rating the steps you used ({librarySteps.length} step{librarySteps.length !== 1 ? 's' : ''})
            </p>
          </div>
          <button
            onClick={onClose}
            disabled={isSaving}
            className="rounded-full p-1 text-white/40 hover:bg-white/10 hover:text-white disabled:opacity-50"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Steps List */}
        <div className="flex-1 overflow-y-auto px-6 py-4">
          <div className="space-y-6">
            {librarySteps.map((step) => {
              const rating = getRating(step.id)
              return (
                <div key={step.id} className="rounded-lg border border-white/[0.06] bg-[#0a0a0a] p-4">
                  {/* Step Title */}
                  <h3 className="font-medium text-white">{step.title}</h3>
                  <p className="mt-1 text-sm text-white/40 capitalize">{step.step_type}</p>

                  {/* Star Rating */}
                  <div className="mt-3">
                    <label className="mb-1 block text-sm font-medium text-white">
                      Rating
                    </label>
                    <StarRating
                      value={rating?.rating || 0}
                      onChange={(value) => handleRatingChange(step.id, value)}
                      size="lg"
                    />
                  </div>

                  {/* Was this helpful? */}
                  <div className="mt-3">
                    <label className="mb-2 block text-sm font-medium text-white">
                      Was this helpful?
                    </label>
                    <div className="flex gap-2">
                      <button
                        type="button"
                        onClick={() => handleHelpfulChange(step.id, true)}
                        disabled={isSaving}
                        className={cn(
                          'flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium transition-colors',
                          rating?.helpful === true
                            ? 'border-emerald-400/20 bg-emerald-400/10 text-emerald-400'
                            : 'border-white/10 text-white/60 hover:bg-white/10 hover:text-white',
                          'disabled:opacity-50'
                        )}
                      >
                        <ThumbsUp className="h-4 w-4" />
                        Yes
                      </button>
                      <button
                        type="button"
                        onClick={() => handleHelpfulChange(step.id, false)}
                        disabled={isSaving}
                        className={cn(
                          'flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium transition-colors',
                          rating?.helpful === false
                            ? 'border-red-400/20 bg-red-400/10 text-red-400'
                            : 'border-white/10 text-white/60 hover:bg-white/10 hover:text-white',
                          'disabled:opacity-50'
                        )}
                      >
                        <ThumbsDown className="h-4 w-4" />
                        No
                      </button>
                    </div>
                  </div>

                  {/* Optional Review */}
                  <div className="mt-3">
                    <label htmlFor={`review-${step.id}`} className="mb-1 block text-sm font-medium text-white">
                      Review <span className="text-white/40">(optional)</span>
                    </label>
                    <textarea
                      id={`review-${step.id}`}
                      value={rating?.review || ''}
                      onChange={(e) => handleReviewChange(step.id, e.target.value)}
                      disabled={isSaving}
                      maxLength={500}
                      rows={2}
                      placeholder="Share your experience with this step..."
                      className={cn(
                        'w-full rounded-md border border-white/10 bg-black/50 px-3 py-2 text-sm text-white',
                        'placeholder:text-white/40',
                        'focus:border-white/30 focus:outline-none focus:ring-1 focus:ring-white/20',
                        'disabled:opacity-50'
                      )}
                    />
                    <p className="mt-1 text-xs text-white/40 text-right">
                      {rating?.review?.length || 0}/500
                    </p>
                  </div>
                </div>
              )
            })}
          </div>
        </div>

        {/* Footer */}
        <div className="flex justify-end gap-2 border-t border-white/[0.06] px-6 py-4">
          <button
            type="button"
            onClick={onClose}
            disabled={isSaving}
            className={cn(
              'rounded-md border border-white/10 px-4 py-2 text-sm font-medium text-white/60',
              'hover:bg-white/10 hover:text-white disabled:opacity-50'
            )}
          >
            Skip
          </button>
          <button
            type="button"
            onClick={handleSubmit}
            disabled={isSaving}
            className={cn(
              'rounded-md bg-white px-4 py-2 text-sm font-medium text-black',
              'hover:bg-white/90 disabled:opacity-50'
            )}
          >
            {isSaving ? 'Submitting...' : 'Submit Ratings'}
          </button>
        </div>
      </div>
    </div>
  )
}
