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="bg-card border border-border 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-border px-6 py-4">
          <div>
            <h2 className="text-lg font-semibold text-foreground">Rate Your Experience</h2>
            <p className="mt-1 text-sm text-muted-foreground">
              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-muted-foreground hover:bg-accent hover:text-foreground 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-border bg-[#0a0a0a] p-4">
                  {/* Step Title */}
                  <h3 className="font-medium text-foreground">{step.title}</h3>
                  <p className="mt-1 text-sm text-muted-foreground capitalize">{step.step_type}</p>

                  {/* Star Rating */}
                  <div className="mt-3">
                    <label className="mb-1 block text-sm font-medium text-foreground">
                      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-foreground">
                      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-border text-muted-foreground hover:bg-accent hover:text-foreground',
                          '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-border text-muted-foreground hover:bg-accent hover:text-foreground',
                          '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-foreground">
                      Review <span className="text-muted-foreground">(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-border bg-card px-3 py-2 text-sm text-foreground',
                        'placeholder:text-muted-foreground',
                        'focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20',
                        'disabled:opacity-50'
                      )}
                    />
                    <p className="mt-1 text-xs text-muted-foreground text-right">
                      {rating?.review?.length || 0}/500
                    </p>
                  </div>
                </div>
              )
            })}
          </div>
        </div>

        {/* Footer */}
        <div className="flex justify-end gap-2 border-t border-border px-6 py-4">
          <button
            type="button"
            onClick={onClose}
            disabled={isSaving}
            className={cn(
              'rounded-md border border-border px-4 py-2 text-sm font-medium text-muted-foreground',
              'hover:bg-accent hover:text-foreground disabled:opacity-50'
            )}
          >
            Skip
          </button>
          <button
            type="button"
            onClick={handleSubmit}
            disabled={isSaving}
            className={cn(
              'rounded-md bg-gradient-brand px-4 py-2 text-sm font-medium text-white shadow-lg shadow-primary/20',
              'hover:opacity-90 disabled:opacity-50'
            )}
          >
            {isSaving ? 'Submitting...' : 'Submit Ratings'}
          </button>
        </div>
      </div>
    </div>
  )
}
