"use client"

import { cn } from "@mdxui/primitives/lib/utils"
import { Button } from "@mdxui/primitives/button"
import { Textarea } from "@mdxui/primitives/textarea"
import { Label } from "@mdxui/primitives/label"
import { Tooltip, TooltipContent, TooltipTrigger } from "@mdxui/primitives/tooltip"
import {
  MdOutlineSentimentVeryDissatisfied,
  MdOutlineSentimentDissatisfied,
  MdOutlineSentimentNeutral,
  MdOutlineSentimentSatisfied,
  MdOutlineSentimentVerySatisfied,
} from "react-icons/md"
import { useState, useRef } from "react"
import type { Sentiment, FeedbackData, FeedbackUser } from "./types"
import type { IconType } from "react-icons"

const sentiments: Array<{ value: Sentiment; icon: IconType; label: string }> = [
  { value: 'very-dissatisfied', icon: MdOutlineSentimentVeryDissatisfied, label: 'Very Dissatisfied' },
  { value: 'dissatisfied', icon: MdOutlineSentimentDissatisfied, label: 'Dissatisfied' },
  { value: 'neutral', icon: MdOutlineSentimentNeutral, label: 'Neutral' },
  { value: 'satisfied', icon: MdOutlineSentimentSatisfied, label: 'Satisfied' },
  { value: 'very-satisfied', icon: MdOutlineSentimentVerySatisfied, label: 'Very Satisfied' },
]

interface FeedbackContentProps {
  user?: FeedbackUser
  context?: Record<string, unknown>
  captureMetadata?: boolean
  onSubmit?: (data: FeedbackData) => Promise<void> | void
  apiEndpoint?: string
  placeholder?: string
  submitLabel?: string
  onSuccess: () => void
  onError: (error: string) => void
}

function captureCurrentMetadata() {
  return {
    url: window.location.href,
    timestamp: new Date().toISOString(),
    viewport: { width: window.innerWidth, height: window.innerHeight },
    userAgent: navigator.userAgent,
  }
}

export function FeedbackContent({
  user,
  context,
  captureMetadata = true,
  onSubmit,
  apiEndpoint,
  placeholder = "Write your feedback (optional)",
  submitLabel = "Submit",
  onSuccess,
  onError,
}: FeedbackContentProps) {
  const [selectedSentiment, setSelectedSentiment] = useState<Sentiment | null>(null)
  const [message, setMessage] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [hoveredSentiment, setHoveredSentiment] = useState<Sentiment | null>(null)
  const hoverTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  const handleMouseEnter = (value: Sentiment) => {
    // Clear any pending timeout
    if (hoverTimeoutRef.current) {
      clearTimeout(hoverTimeoutRef.current)
    }
    // Delay tooltip by 300ms
    hoverTimeoutRef.current = setTimeout(() => {
      setHoveredSentiment(value)
    }, 300)
  }

  const handleMouseLeave = () => {
    if (hoverTimeoutRef.current) {
      clearTimeout(hoverTimeoutRef.current)
    }
    setHoveredSentiment(null)
  }

  const handleSubmit = async () => {
    if (!selectedSentiment) return

    setIsSubmitting(true)

    const data: FeedbackData = {
      sentiment: selectedSentiment,
      message: message.trim() || undefined,
      user,
      context,
      metadata: captureMetadata ? captureCurrentMetadata() : undefined,
    }

    try {
      if (onSubmit) {
        await onSubmit(data)
      } else if (apiEndpoint) {
        const response = await fetch(apiEndpoint, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(data),
        })
        if (!response.ok) {
          throw new Error(`Failed to submit feedback: ${response.statusText}`)
        }
      }
      onSuccess()
    } catch (err) {
      onError(err instanceof Error ? err.message : "Failed to submit feedback")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="flex flex-col gap-4">
      {/* Sentiment selector */}
      <div className="flex flex-col gap-1">
        <div
          role="radiogroup"
          aria-label="Select your satisfaction level"
          className="grid grid-cols-5 gap-1 w-full"
        >
          {sentiments.map(({ value, icon: Icon, label }) => (
            <Tooltip key={value} open={hoveredSentiment === value}>
              <TooltipTrigger asChild>
                <button
                  type="button"
                  role="radio"
                  aria-checked={selectedSentiment === value}
                  aria-label={label}
                  onClick={() => setSelectedSentiment(value)}
                  onMouseEnter={() => handleMouseEnter(value)}
                  onMouseLeave={handleMouseLeave}
                  className={cn(
                    "flex items-center justify-center p-3 rounded-[var(--radius-md)] transition-colors",
                    "border hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
                    selectedSentiment === value
                      ? "border-primary text-primary bg-primary/5"
                      : "border-border text-muted-foreground"
                  )}
                >
                  <Icon className="size-7" />
                </button>
              </TooltipTrigger>
              <TooltipContent>{label}</TooltipContent>
            </Tooltip>
          ))}
        </div>
        {/* Labels under icons */}
        <div className="grid grid-cols-5 gap-1 w-full">
          <span className="col-span-2 text-xs text-muted-foreground text-left">Unsatisfied</span>
          <span className="col-span-1" />
          <span className="col-span-2 text-xs text-muted-foreground text-right">Satisfied</span>
        </div>
      </div>

      {/* Message textarea with label */}
      <div className="flex flex-col gap-2">
        <Label htmlFor="feedback-message" className="text-sm text-muted-foreground">
          {placeholder}
        </Label>
        <Textarea
          id="feedback-message"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          rows={4}
          className="resize-y min-h-24 max-h-48"
        />
      </div>

      {/* Submit button - full width */}
      <Button
        onClick={handleSubmit}
        disabled={!selectedSentiment || isSubmitting}
        className="w-full"
      >
        {isSubmitting ? "Submitting..." : submitLabel}
      </Button>
    </div>
  )
}
