"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 { Checkbox } from "@mdxui/primitives/checkbox"
import { useState } from "react"
import type { ResolutionStatus, SatisfactionRating, ResolutionData, ResolutionUser } from "./types"

const resolutionOptions: Array<{ value: ResolutionStatus; label: string }> = [
  { value: 'yes', label: 'Yes' },
  { value: 'partially', label: 'Partially' },
  { value: 'no', label: 'No' },
]

const satisfactionOptions: SatisfactionRating[] = [1, 2, 3, 4, 5]

interface ResolutionContentProps {
  ticketId?: string
  showFollowUp?: boolean
  user?: ResolutionUser
  context?: Record<string, unknown>
  captureMetadata?: boolean
  onSubmit?: (data: ResolutionData) => Promise<void> | void
  apiEndpoint?: 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 ResolutionContent({
  ticketId,
  showFollowUp = true,
  user,
  context,
  captureMetadata = true,
  onSubmit,
  apiEndpoint,
  submitLabel = "Submit",
  onSuccess,
  onError,
}: ResolutionContentProps) {
  const [resolved, setResolved] = useState<ResolutionStatus | null>(null)
  const [satisfaction, setSatisfaction] = useState<SatisfactionRating | null>(null)
  const [feedback, setFeedback] = useState("")
  const [stillNeedsHelp, setStillNeedsHelp] = useState("")
  const [wantsFollowUp, setWantsFollowUp] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const showStillNeedsHelp = resolved === 'no' || resolved === 'partially'
  const isValid = resolved !== null && satisfaction !== null

  const handleSubmit = async () => {
    if (!resolved || !satisfaction) return

    setIsSubmitting(true)

    const data: ResolutionData = {
      resolved,
      satisfaction,
      feedback: feedback.trim() || undefined,
      stillNeedsHelp: showStillNeedsHelp ? stillNeedsHelp.trim() || undefined : undefined,
      wantsFollowUp: showFollowUp ? wantsFollowUp : undefined,
      ticketId,
      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: ${response.statusText}`)
        }
      }
      onSuccess()
    } catch (err) {
      onError(err instanceof Error ? err.message : "Failed to submit resolution")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="flex flex-col gap-5">
      {/* Resolution status */}
      <div className="flex flex-col gap-1">
        <Label className="text-sm text-foreground">
          Was your issue resolved?
        </Label>
        <div
          role="radiogroup"
          aria-label="Select resolution status"
          className="flex gap-2"
        >
          {resolutionOptions.map(({ value, label }) => (
            <button
              key={value}
              type="button"
              role="radio"
              aria-checked={resolved === value}
              onClick={() => setResolved(value)}
              className={cn(
                "flex-1 px-3 py-2 text-sm font-medium rounded-[var(--radius-md)] transition-colors",
                "border hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
                resolved === value
                  ? "border-primary bg-primary/10 text-primary"
                  : "border-border text-muted-foreground"
              )}
            >
              {label}
            </button>
          ))}
        </div>
      </div>

      {/* Satisfaction rating */}
      <div className="flex flex-col gap-1">
        <Label className="text-sm text-foreground">
          How satisfied are you with our support?
        </Label>
        <div
          role="radiogroup"
          aria-label="Select satisfaction rating"
          className="flex gap-2"
        >
          {satisfactionOptions.map((rating) => (
            <button
              key={rating}
              type="button"
              role="radio"
              aria-checked={satisfaction === rating}
              aria-label={`${rating} out of 5`}
              onClick={() => setSatisfaction(rating)}
              className={cn(
                "flex-1 px-3 py-2 text-sm font-medium rounded-[var(--radius-md)] transition-colors",
                "border hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
                satisfaction === rating
                  ? "border-primary bg-primary/10 text-primary"
                  : "border-border text-muted-foreground"
              )}
            >
              {rating}
            </button>
          ))}
        </div>
        <div className="flex justify-between text-xs text-muted-foreground mt-1">
          <span>Very dissatisfied</span>
          <span>Very satisfied</span>
        </div>
      </div>

      {/* Still needs help (conditional) */}
      {showStillNeedsHelp && (
        <div className="flex flex-col gap-1">
          <Label htmlFor="resolution-still-needs-help" className="text-sm text-foreground">
            What&apos;s still wrong?
          </Label>
          <Textarea
            id="resolution-still-needs-help"
            value={stillNeedsHelp}
            onChange={(e) => setStillNeedsHelp(e.target.value)}
            placeholder="Please describe what's still not working..."
            rows={3}
            className="resize-y min-h-20 max-h-40"
          />
        </div>
      )}

      {/* Feedback textarea */}
      <div className="flex flex-col gap-1">
        <Label htmlFor="resolution-feedback" className="text-sm text-foreground">
          What could have been better? (optional)
        </Label>
        <Textarea
          id="resolution-feedback"
          value={feedback}
          onChange={(e) => setFeedback(e.target.value)}
          placeholder="Any suggestions for improvement..."
          rows={3}
          className="resize-y min-h-20 max-h-40"
        />
      </div>

      {/* Follow-up checkbox */}
      {showFollowUp && (
        <div className="flex items-center gap-2">
          <Checkbox
            id="resolution-follow-up"
            checked={wantsFollowUp}
            onCheckedChange={(checked) => setWantsFollowUp(checked === true)}
          />
          <Label htmlFor="resolution-follow-up" className="text-sm text-muted-foreground cursor-pointer">
            I would like a follow-up from support
          </Label>
        </div>
      )}

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