import type { ComponentChildren, JSX } from 'preact';
import { cn } from './cn';

export type SectionCardVariant = 'default' | 'subtle' | 'dashed';
export type SectionCardPadding = 'sm' | 'md';

export type SectionCardProps = JSX.HTMLAttributes<HTMLElement> & {
  title?: ComponentChildren;
  description?: ComponentChildren;
  icon?: ComponentChildren;
  actions?: ComponentChildren;
  contentClassName?: string;
  variant?: SectionCardVariant;
  padding?: SectionCardPadding;
};

const VARIANTS: Record<SectionCardVariant, string> = {
  default: 'ask-border-borderSubtle ask-bg-surfaceAlt',
  subtle: 'ask-border-borderSubtle ask-bg-surface',
  dashed: 'ask-border-dashed ask-border-borderSubtle ask-bg-surfaceAlt',
};

const PADDINGS: Record<SectionCardPadding, string> = {
  sm: 'ask-p-3',
  md: 'ask-p-4',
};

export function SectionCard({
  className,
  children,
  title,
  description,
  icon,
  actions,
  contentClassName,
  variant = 'default',
  padding = 'sm',
  ...props
}: SectionCardProps) {
  const hasHeader = Boolean(title || description || icon || actions);

  return (
    <section
      className={cn(
        'ask-section-card ask-rounded-2xl ask-border',
        VARIANTS[variant],
        PADDINGS[padding],
        className,
      )}
      {...props}
    >
      {hasHeader ? (
        <div className="ask-flex ask-items-start ask-justify-between ask-gap-3">
          <div className="ask-min-w-0 ask-flex-1">
            <div className="ask-flex ask-items-center ask-gap-2">
              {icon ? (
                <span className="ask-flex ask-h-7 ask-w-7 ask-shrink-0 ask-items-center ask-justify-center ask-rounded-full ask-bg-primarySoft ask-text-primary">
                  {icon}
                </span>
              ) : null}
              {title ? <div className="ask-text-[12px] ask-font-semibold ask-text-textMain">{title}</div> : null}
            </div>
            {description ? <p className="ask-mt-2 ask-text-[11px] ask-leading-5 ask-text-textMuted">{description}</p> : null}
          </div>
          {actions ? <div className="ask-flex ask-shrink-0 ask-items-center ask-gap-2">{actions}</div> : null}
        </div>
      ) : null}
      {children ? <div className={cn(hasHeader ? 'ask-mt-3' : '', contentClassName)}>{children}</div> : null}
    </section>
  );
}
