'use client';

import * as React from 'react';
import { Info } from 'lucide-react';

import { Label } from '@/components/ui/label';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';

export interface FieldLabelProps extends React.ComponentPropsWithoutRef<typeof Label> {
  /**
   * Optional explainer copy. When set, an Info icon is rendered next
   * to the label that opens a Tooltip on hover / focus. Tooltip writing
   * guidelines: 1-2 sentences max; state the unit ("...in days",
   * "...in MB"); lead with the risk for dangerous settings; explain the
   * "why and how to choose a value" rather than restating the label.
   */
  tooltip?: React.ReactNode;
  /** Mark the field as required - appends an asterisk after the label text. */
  required?: boolean;
}

/**
 * Shared label-with-explainer primitive for admin forms. Wraps the
 * shadcn Label + an optional Info-tooltip slot. Adopting this everywhere
 * an admin setting needs a non-obvious explainer (Sort Order, Weight,
 * TTL, Cap, Confidence, Threshold) gives admins consistent tooltip UX
 * without per-form bespoke implementations.
 */
export function FieldLabel({
  tooltip,
  required,
  className,
  children,
  ...labelProps
}: FieldLabelProps) {
  if (!tooltip) {
    return (
      <Label className={cn('inline-flex items-center gap-1.5', className)} {...labelProps}>
        {children}
        {required ? <span aria-hidden>*</span> : null}
      </Label>
    );
  }

  return (
    <Label className={cn('inline-flex items-center gap-1.5', className)} {...labelProps}>
      {children}
      {required ? <span aria-hidden>*</span> : null}
      <TooltipProvider delayDuration={200}>
        <Tooltip>
          <TooltipTrigger asChild>
            <button
              type="button"
              aria-label="More info"
              className="text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-sm"
            >
              <Info className="h-3.5 w-3.5" aria-hidden />
            </button>
          </TooltipTrigger>
          <TooltipContent className="max-w-xs text-xs leading-relaxed">{tooltip}</TooltipContent>
        </Tooltip>
      </TooltipProvider>
    </Label>
  );
}
