import * as React from 'react';
import { clsx } from 'clsx';
import { Label } from './Label.js';

export interface FieldProps extends React.HTMLAttributes<HTMLDivElement> {
  orientation?: 'vertical' | 'horizontal';
  invalid?: boolean;
}

export function Field({ orientation = 'vertical', invalid, className, ...props }: FieldProps) {
  return (
    <div
      data-invalid={invalid ? 'true' : undefined}
      data-orientation={orientation}
      className={clsx(
        'grid gap-2 text-[var(--bl-text-primary)]',
        orientation === 'horizontal' && 'items-start sm:grid-cols-[minmax(11rem,16rem)_1fr]',
        invalid && 'text-[var(--bl-danger)]',
        className
      )}
      role="group"
      {...props}
    />
  );
}

export type FieldGroupProps = React.HTMLAttributes<HTMLDivElement>;

export function FieldGroup({ className, ...props }: FieldGroupProps) {
  return <div className={clsx('grid gap-5', className)} {...props} />;
}

export type FieldContentProps = React.HTMLAttributes<HTMLDivElement>;

export function FieldContent({ className, ...props }: FieldContentProps) {
  return <div className={clsx('grid gap-1.5', className)} {...props} />;
}

export interface FieldLabelProps extends React.ComponentPropsWithoutRef<typeof Label> {}

export function FieldLabel({ className, ...props }: FieldLabelProps) {
  return (
    <Label
      className={clsx(
        'text-xs font-semibold uppercase tracking-[0.08em] text-[var(--bl-text-secondary)]',
        className
      )}
      {...props}
    />
  );
}

export type FieldTitleProps = React.HTMLAttributes<HTMLDivElement>;

export function FieldTitle({ className, ...props }: FieldTitleProps) {
  return (
    <div
      className={clsx('text-sm font-semibold leading-5 text-[var(--bl-text-primary)]', className)}
      {...props}
    />
  );
}

export type FieldDescriptionProps = React.ComponentPropsWithoutRef<'p'>;

export function FieldDescription({ className, ...props }: FieldDescriptionProps) {
  return (
    <p
      className={clsx('m-0 text-sm leading-6 text-[var(--bl-text-secondary)]', className)}
      {...props}
    />
  );
}

export interface FieldErrorProps extends React.ComponentPropsWithoutRef<'p'> {
  children?: React.ReactNode;
}

export function FieldError({ className, children, ...props }: FieldErrorProps) {
  if (!children) return null;

  return (
    <p
      className={clsx('m-0 text-sm font-medium leading-5 text-[var(--bl-danger)]', className)}
      role="alert"
      {...props}
    >
      {children}
    </p>
  );
}
