"use client"

import * as React from "react"
import { cn } from "@/lib/utils"

const FieldSet = ({ className, ...props }: React.ComponentProps<"fieldset">) => (
  <fieldset role="group" className={cn("grid gap-3", className)} {...props} />
)

const FieldLegend = (
  { className, variant = "legend", ...props }: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }
) => (
  <legend
    className={cn(
      variant === "label" ? "text-sm font-medium" : "text-sm font-semibold",
      "text-foreground",
      className
    )}
    {...props}
  />
)

const FieldGroup = ({ className, ...props }: React.ComponentProps<"div">) => (
  <div className={cn("@container/field-group grid gap-4", className)} {...props} />
)

const Field = (
  { className, orientation = "vertical", ...props }: React.ComponentProps<"div"> & { orientation?: "vertical" | "horizontal" | "responsive" }
) => (
  <div
    data-orientation={orientation}
    className={cn(
      "flex gap-2",
      orientation === "vertical" && "flex-col",
      orientation === "horizontal" && "items-center",
      orientation === "responsive" && "@[480px]/field-group:flex-row @[480px]/field-group:items-center flex-col",
      className
    )}
    {...props}
  />
)

const FieldContent = ({ className, ...props }: React.ComponentProps<"div">) => (
  <div className={cn("flex flex-col", className)} {...props} />
)

const FieldLabel = ({ className, ...props }: React.ComponentProps<"label"> & { asChild?: boolean }) => (
  <label className={cn("text-sm font-medium text-foreground", className)} {...props} />
)

const FieldTitle = ({ className, ...props }: React.ComponentProps<"div">) => (
  <div className={cn("text-sm font-medium", className)} {...props} />
)

const FieldDescription = ({ className, ...props }: React.ComponentProps<"p">) => (
  <p className={cn("text-xs text-muted-foreground", className)} {...props} />
)

const FieldError = ({ className, children, errors, ...props }: React.ComponentProps<"div"> & { errors?: Array<{ message?: string }> | undefined }) => {
  const items = (errors ?? []) as Array<{ message?: string }>
  if (!children && (!items || items.length === 0)) return null
  return (
    <div className={cn("text-xs text-destructive", className)} {...props}>
      {children ? children : (
        <ul className="ml-4 list-disc">
          {items.map((e, i) => (
            <li key={i}>{e?.message}</li>
          ))}
        </ul>
      )}
    </div>
  )
}

const FieldSeparator = ({ className, ...props }: React.ComponentProps<"div">) => (
  <div className={cn("my-2 h-px w-full bg-border", className)} {...props} />
)

export { FieldSet, FieldLegend, FieldGroup, Field, FieldContent, FieldLabel, FieldTitle, FieldDescription, FieldError, FieldSeparator }
