"use client"

import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@mdxui/primitives/popover"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@mdxui/primitives/dialog"
import { useState, useEffect } from "react"
import { ResolutionTrigger } from "./resolution-trigger"
import { ResolutionContent } from "./resolution-content"
import type { ResolutionProps } from "./types"

type ResolutionState = "idle" | "success" | "error"

export function Resolution({
  variant = "modal",
  side = "top",
  triggerLabel = "Rate Support",
  title = "How did we do?",
  ticketId,
  showFollowUp = true,
  user,
  context,
  captureMetadata = true,
  onSubmit,
  apiEndpoint,
  submitLabel,
  className,
}: ResolutionProps) {
  const [open, setOpen] = useState(false)
  const [state, setState] = useState<ResolutionState>("idle")
  const [errorMessage, setErrorMessage] = useState("")

  // Reset state when closed
  useEffect(() => {
    if (!open) {
      // Small delay to allow close animation
      const timer = setTimeout(() => {
        setState("idle")
        setErrorMessage("")
      }, 200)
      return () => clearTimeout(timer)
    }
  }, [open])

  // Auto-close after success
  useEffect(() => {
    if (state === "success") {
      const timer = setTimeout(() => {
        setOpen(false)
      }, 1500)
      return () => clearTimeout(timer)
    }
  }, [state])

  const handleSuccess = () => setState("success")
  const handleError = (error: string) => {
    setState("error")
    setErrorMessage(error)
  }

  const content = (
    <>
      {state === "success" ? (
        <div className="flex items-center justify-center py-8 text-center">
          <p className="text-foreground font-medium">Thanks for your feedback!</p>
        </div>
      ) : (
        <>
          {state === "error" && (
            <p className="text-destructive text-sm mb-4">{errorMessage}</p>
          )}
          <ResolutionContent
            ticketId={ticketId}
            showFollowUp={showFollowUp}
            user={user}
            context={context}
            captureMetadata={captureMetadata}
            onSubmit={onSubmit}
            apiEndpoint={apiEndpoint}
            submitLabel={submitLabel}
            onSuccess={handleSuccess}
            onError={handleError}
          />
        </>
      )}
    </>
  )

  if (variant === "modal") {
    return (
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger asChild>
          <ResolutionTrigger label={triggerLabel} className={className} />
        </DialogTrigger>
        <DialogContent className="sm:max-w-[480px]">
          <DialogHeader>
            <DialogTitle>{title}</DialogTitle>
          </DialogHeader>
          {content}
        </DialogContent>
      </Dialog>
    )
  }

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <ResolutionTrigger label={triggerLabel} className={className} />
      </PopoverTrigger>
      <PopoverContent className="w-[440px]" side={side}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-foreground font-semibold">{title}</h3>
        </div>
        {content}
      </PopoverContent>
    </Popover>
  )
}
