"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 { ContactTrigger } from "./contact-trigger"
import { ContactContent } from "./contact-content"
import type { ContactProps } from "./types"

type ContactState = "idle" | "success" | "error"

export function Contact({
  variant = "modal",
  side = "top",
  triggerLabel = "Contact Us",
  title = "Contact Us",
  showName = true,
  showEmail = true,
  showCompanyName = false,
  showCompanySize = false,
  showTopic = true,
  showMessage = true,
  showAdditionalInfo = false,
  requireName = true,
  requireEmail = true,
  requireCompanyName = false,
  requireCompanySize = false,
  requireTopic = false,
  requireMessage = true,
  requireAdditionalInfo = false,
  topics,
  companySizeOptions,
  rows,
  user,
  context,
  captureMetadata = true,
  sessionId,
  correlationId,
  appVersion,
  environment,
  onSubmit,
  apiEndpoint,
  submitLabel,
  className,
}: ContactProps) {
  const [open, setOpen] = useState(false)
  const [state, setState] = useState<ContactState>("idle")
  const [errorMessage, setErrorMessage] = useState("")

  // Reset state when closed
  useEffect(() => {
    if (!open) {
      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! We'll be in touch soon.</p>
        </div>
      ) : (
        <>
          {state === "error" && (
            <p className="text-destructive text-sm mb-4">{errorMessage}</p>
          )}
          <ContactContent
            showName={showName}
            showEmail={showEmail}
            showCompanyName={showCompanyName}
            showCompanySize={showCompanySize}
            showTopic={showTopic}
            showMessage={showMessage}
            showAdditionalInfo={showAdditionalInfo}
            requireName={requireName}
            requireEmail={requireEmail}
            requireCompanyName={requireCompanyName}
            requireCompanySize={requireCompanySize}
            requireTopic={requireTopic}
            requireMessage={requireMessage}
            requireAdditionalInfo={requireAdditionalInfo}
            topics={topics}
            companySizeOptions={companySizeOptions}
            rows={rows}
            user={user}
            context={context}
            captureMetadata={captureMetadata}
            sessionId={sessionId}
            correlationId={correlationId}
            appVersion={appVersion}
            environment={environment}
            onSubmit={onSubmit}
            apiEndpoint={apiEndpoint}
            submitLabel={submitLabel}
            onSuccess={handleSuccess}
            onError={handleError}
          />
        </>
      )}
    </>
  )

  if (variant === "modal") {
    return (
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger asChild>
          <ContactTrigger 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>
        <ContactTrigger label={triggerLabel} className={className} />
      </PopoverTrigger>
      <PopoverContent className="w-[400px]" side={side}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-foreground font-semibold">{title}</h3>
        </div>
        {content}
      </PopoverContent>
    </Popover>
  )
}
