"use client"

import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@mdxui/primitives/popover"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@mdxui/primitives/dialog"
import { toast } from "sonner"
import { useState, useCallback } from "react"
import { ReportIssueTrigger } from "./report-issue-trigger"
import { ReportIssueContent } from "./report-issue-content"
import type { MessageType, ReportIssueProps } from "./types"

const TAB_TITLES: Record<MessageType, string> = {
  question: "Submit a Question",
  feedback: "Submit Feedback",
  bug: "Report an Issue",
}

export function ReportIssue({
  variant = "modal",
  side = "top",
  triggerLabel = "Report Issue",
  defaultTab = "question",
  defaultValues,
  topics,
  severityOptions,
  user,
  context,
  captureMetadata = true,
  onSubmit,
  apiEndpoint,
  apiHeaders,
  submitLabel,
  successMessage = "Thanks! We'll look into this right away.",
  open: controlledOpen,
  onOpenChange,
  children,
  className,
}: ReportIssueProps) {
  const [uncontrolledOpen, setUncontrolledOpen] = useState(false)
  const [activeTab, setActiveTab] = useState<MessageType>(defaultTab)
  const [errorMessage, setErrorMessage] = useState("")

  const isControlled = controlledOpen !== undefined
  const open = isControlled ? controlledOpen : uncontrolledOpen

  const setOpen = useCallback(
    (value: boolean) => {
      if (!isControlled) setUncontrolledOpen(value)
      onOpenChange?.(value)
    },
    [isControlled, onOpenChange]
  )

  const title = TAB_TITLES[activeTab]

  const handleSuccess = () => {
    setOpen(false)
    toast.success(successMessage)
  }

  const handleError = (error: string) => {
    setErrorMessage(error)
  }

  const handleOpenChange = (value: boolean) => {
    setOpen(value)
    if (!value) {
      setTimeout(() => setErrorMessage(""), 200)
    }
  }

  const trigger = children ?? (
    <ReportIssueTrigger label={triggerLabel} className={className} />
  )

  const formContent = (
    <>
      {errorMessage && (
        <p className="text-destructive text-sm mb-4">{errorMessage}</p>
      )}
      <ReportIssueContent
        defaultTab={defaultTab}
        defaultValues={defaultValues}
        topics={topics}
        severityOptions={severityOptions}
        user={user}
        context={context}
        captureMetadata={captureMetadata}
        onSubmit={onSubmit}
        apiEndpoint={apiEndpoint}
        apiHeaders={apiHeaders}
        submitLabel={submitLabel}
        onSuccess={handleSuccess}
        onError={handleError}
        onTabChange={setActiveTab}
      />
    </>
  )

  if (variant === "modal") {
    return (
      <Dialog open={open} onOpenChange={handleOpenChange}>
        <DialogTrigger asChild>{trigger}</DialogTrigger>
        <DialogContent className="max-w-[520px] max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{title}</DialogTitle>
          </DialogHeader>
          {formContent}
        </DialogContent>
      </Dialog>
    )
  }

  return (
    <Popover open={open} onOpenChange={handleOpenChange}>
      <PopoverTrigger asChild>{trigger}</PopoverTrigger>
      <PopoverContent className="w-[440px] max-h-[85vh] overflow-y-auto" side={side}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-foreground font-semibold">{title}</h3>
        </div>
        {formContent}
      </PopoverContent>
    </Popover>
  )
}
