/**
 * Button Group Field Component
 *
 * Renders a segmented control (connected buttons) for single-value selection.
 * Uses shadcn ToggleGroup with custom connected-button styling.
 * Supports optional icon, disabled state, and tooltip description.
 */

import { useMemo, memo } from 'react';
import { Label } from '../ui/label';
import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip';
import { ActionField, ActionFieldOption } from '../../types/action';
import { resolveIcon } from '../../lib/icon-resolver';

interface ButtonGroupFieldProps {
  fieldName: string;
  field: ActionField;
  value: string;
  onChange: (value: string) => void;
  error?: string;
}

/**
 * Formats a string value into a readable label.
 */
function formatLabel(value: string): string {
  return value.charAt(0).toUpperCase() + value.slice(1).replace(/_/g, ' ');
}

function ButtonContent({ option }: { option: ActionFieldOption }) {
  const Icon = resolveIcon(option.icon);

  return (
    <span className="flex items-center gap-1.5">
      {Icon && <Icon className="h-3.5 w-3.5 shrink-0" />}
      {option.label}
    </span>
  );
}

export const ButtonGroupField = memo(function ButtonGroupField({
  fieldName,
  field,
  value,
  onChange,
  error,
}: ButtonGroupFieldProps) {
  const normalizedOptions = useMemo((): ActionFieldOption[] => {
    if (!field.options) return [];

    if (Array.isArray(field.options)) {
      return field.options.map((opt) => {
        if (typeof opt === 'string') {
          return { value: opt, label: formatLabel(opt) };
        }
        return opt;
      });
    }

    return Object.entries(field.options).map(([key, label]) => ({
      value: key,
      label: String(label),
    }));
  }, [field.options]);

  const hasDescriptions = normalizedOptions.some((opt) => opt.description);

  return (
    <div className="space-y-2">
      <Label htmlFor={fieldName} className="text-[13px] font-medium text-slate-700 tracking-tight">
        {field.label}
        {field.required && <span className="text-rose-500 ml-0.5">*</span>}
      </Label>

      <ToggleGroup
        type="single"
        value={value}
        onValueChange={(val) => {
          // Prevent deselection on required fields
          if (val || !field.required) {
            onChange(val);
          }
        }}
        className="flex w-fit rounded-lg border border-slate-200 p-0.5 bg-slate-50/50"
      >
        {normalizedOptions.map((option) => {
          const item = (
            <ToggleGroupItem
              key={option.value}
              value={option.value}
              disabled={option.disabled}
              className="rounded-md px-3 py-1.5 text-[13px] font-medium text-slate-600 transition-colors duration-150
                data-[state=on]:bg-cyan-600 data-[state=on]:text-white data-[state=on]:shadow-sm
                hover:text-slate-900 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <ButtonContent option={option} />
            </ToggleGroupItem>
          );

          if (option.description && hasDescriptions) {
            return (
              <TooltipProvider key={option.value}>
                <Tooltip>
                  <TooltipTrigger asChild>{item}</TooltipTrigger>
                  <TooltipContent side="bottom">
                    <p className="text-xs max-w-48">{option.description}</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            );
          }

          return item;
        })}
      </ToggleGroup>

      <p className="text-[12px] text-slate-400 leading-relaxed">{field.description}</p>
      {error && (
        <div className="flex items-start gap-2 rounded-lg bg-rose-50 border border-rose-100 px-3 py-2.5">
          <span className="text-[13px] text-rose-700 leading-snug">{error}</span>
        </div>
      )}
    </div>
  );
});
