import { useState, useEffect } from 'react'
import { ThumbsUp, ThumbsDown } from 'lucide-react'
import { analyticsApi } from '@/api'
import { cn } from '@/lib/utils'

interface StepFeedbackProps {
  stepId: string
  sessionId: string
}

const HINT_KEY = 'rf-step-feedback-hint-dismissed'

export function StepFeedback({ stepId, sessionId }: StepFeedbackProps) {
  const [feedback, setFeedback] = useState<boolean | null>(null)
  const [submitting, setSubmitting] = useState(false)
  const [showHint, setShowHint] = useState(false)

  useEffect(() => {
    if (!localStorage.getItem(HINT_KEY)) {
      setShowHint(true)
    }
  }, [])

  const handleFeedback = async (wasHelpful: boolean) => {
    if (submitting) return
    setSubmitting(true)
    try {
      const newValue = feedback === wasHelpful ? null : wasHelpful
      if (newValue !== null) {
        await analyticsApi.submitStepFeedback(stepId, sessionId, newValue)
      }
      setFeedback(newValue)
      if (showHint) {
        setShowHint(false)
        localStorage.setItem(HINT_KEY, '1')
      }
    } catch {
      // Silently fail — feedback is non-critical
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="flex items-center gap-2">
      {showHint && (
        <span className="text-xs text-muted-foreground">Was this step helpful?</span>
      )}
      <button
        onClick={() => handleFeedback(true)}
        disabled={submitting}
        className={cn(
          'rounded-md p-1.5 transition-colors',
          feedback === true
            ? 'text-emerald-400 bg-emerald-400/10'
            : 'text-muted-foreground hover:text-emerald-400 hover:bg-accent'
        )}
        title="Helpful"
      >
        <ThumbsUp size={14} />
      </button>
      <button
        onClick={() => handleFeedback(false)}
        disabled={submitting}
        className={cn(
          'rounded-md p-1.5 transition-colors',
          feedback === false
            ? 'text-red-400 bg-red-400/10'
            : 'text-muted-foreground hover:text-red-400 hover:bg-accent'
        )}
        title="Not helpful"
      >
        <ThumbsDown size={14} />
      </button>
    </div>
  )
}
