import { cn } from "@/lib/utils";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/ui";
import React, { useMemo } from "react";

interface FormGroupProps
  extends React.HTMLAttributes<HTMLHeadingElement>,
    React.HTMLAttributes<HTMLDivElement> {
  description?: string;
  actions?: JSX.Element;
  footerActions?: JSX.Element;
}

export const FormGroup = React.forwardRef<HTMLDivElement, FormGroupProps>(
  (
    { className, title, description, actions, footerActions, children },
    ref
  ) => {
    const id = React.useId();
    const hasHeader = useMemo(
      () => title || description || actions,
      [title, description, actions]
    );
    return (
      <Card
        id={id}
        className={cn(!hasHeader ? "pt-6" : "", className)}
        ref={ref}
      >
        {hasHeader && (
          <CardHeader className="flex flex-row flex-wrap items-center justify-between sm:flex-nowrap">
            <div>
              {title && (
                <CardTitle className="text-lg leading-normal">
                  {title}
                </CardTitle>
              )}
              {description && (
                <CardDescription className="leading-loose">
                  {description}
                </CardDescription>
              )}
            </div>
            {actions && <div className="flex-shrink-0">{actions}</div>}
          </CardHeader>
        )}
        <CardContent className="grid items-start gap-6">{children}</CardContent>
        {footerActions && (
          <CardFooter
            className="px-6 py-4 border-t"
            style={{ borderStyle: "inherit" }}
          >
            {footerActions}
          </CardFooter>
        )}
      </Card>
    );
  }
);

FormGroup.displayName = "FormGroup";
