import { Star } from "lucide-react";
import * as React from "react";
import { ElementError, getElementErrorAria } from "@/components/general/element-error";
import { ElementHeader } from "@/components/general/element-header";
import { Label } from "@/components/general/label";
import {
  ConfusedFace,
  FrowningFace,
  GrinningFaceWithSmilingEyes,
  GrinningSquintingFace,
  NeutralFace,
  PerseveringFace,
  SlightlySmilingFace,
  SmilingFaceWithSmilingEyes,
  TiredFace,
  WearyFace,
} from "@/components/general/smileys";
import { FB_PART } from "@/lib/parts";
import { type RatingRange, getSmileyColorClasses } from "@/lib/smiley-colors";
import { useRovingRadioGroup } from "@/lib/use-roving-radio-group";
import { cn, getRTLScaleOptionClasses } from "@/lib/utils";

/**
 * Get the smiley icon at the given position in the face set, painted with the given fill
 */
const getSmileyIcon = (iconIdx: number, fillClass: string): React.JSX.Element => {
  const icons = [
    <TiredFace key="tired-face" className={fillClass} />,
    <WearyFace key="weary-face" className={fillClass} />,
    <PerseveringFace key="persevering-face" className={fillClass} />,
    <FrowningFace key="frowning-face" className={fillClass} />,
    <ConfusedFace key="confused-face" className={fillClass} />,
    <NeutralFace key="neutral-face" className={fillClass} />,
    <SlightlySmilingFace key="slightly-smiling-face" className={fillClass} />,
    <SmilingFaceWithSmilingEyes key="smiling-face-with-smiling-eyes" className={fillClass} />,
    <GrinningFaceWithSmilingEyes key="grinning-face-with-smiling-eyes" className={fillClass} />,
    <GrinningSquintingFace key="grinning-squinting-face" className={fillClass} />,
  ];
  return icons[iconIdx];
};

/**
 * Which faces each scale length is drawn from, as indices into the icon set above: a short scale
 * uses the middle of the range, a long one spreads across all ten.
 */
const FACE_SET: Record<RatingRange, number[]> = {
  3: [4, 5, 7],
  4: [4, 5, 6, 7],
  5: [3, 4, 5, 6, 7],
  6: [0, 2, 4, 5, 7, 9],
  7: [1, 3, 4, 5, 6, 8, 9],
  10: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
};

/**
 * Smiley component for rating scale
 */
const RatingSmiley = ({
  idx,
  range,
  fillClass,
}: Readonly<{
  idx: number;
  range: RatingRange;
  /** Tailwind `fill-*` class for the face circle (see getSmileyColorClasses) */
  fillClass: string;
}>): React.JSX.Element => {
  return getSmileyIcon(FACE_SET[range][idx], fillClass);
};

interface RatingProps {
  /** Unique identifier for the element container */
  elementId: string;
  /** The main element or prompt text displayed as the headline */
  headline: string;
  /** Optional descriptive text displayed below the headline */
  description?: string;
  /** Unique identifier for the rating group */
  inputId: string;
  /** Rating scale type: 'number', 'star', or 'smiley' */
  scale: "number" | "star" | "smiley";
  /** Number of rating options (3, 4, 5, 6, 7, or 10) */
  range: RatingRange;
  /** Currently selected rating value (1 to range) */
  value?: number;
  /** Callback function called when rating changes */
  onChange: (value: number) => void;
  /** Optional label for the lower end of the scale */
  lowerLabel?: string;
  /** Optional label for the upper end of the scale */
  upperLabel?: string;
  /** Whether color coding is enabled (for smiley scale) */
  colorCoding?: boolean;
  /** Whether the field is required (shows asterisk indicator) */
  required?: boolean;
  /** Custom label for the required indicator */
  requiredLabel?: string;
  /** Error message to display */
  errorMessage?: string;
  /** Text direction: 'ltr' (left-to-right), 'rtl' (right-to-left), or 'auto' (auto-detect from content) */
  dir?: "ltr" | "rtl" | "auto";
  /** Whether the controls are disabled */
  disabled?: boolean;
  /** Image URL to display above the headline */
  imageUrl?: string;
  /** Alt text for the image; empty or absent marks it decorative */
  imageAltText?: string;
  /** Video URL to display above the headline */
  videoUrl?: string;
}

function Rating({
  elementId,
  headline,
  description,
  inputId,
  scale,
  range,
  value,
  onChange,
  lowerLabel,
  upperLabel,
  colorCoding = false,
  required = false,
  requiredLabel,
  errorMessage,
  dir = "auto",
  disabled = false,
  imageUrl,
  imageAltText,
  videoUrl,
}: Readonly<RatingProps>): React.JSX.Element {
  const errorAria = getElementErrorAria(inputId, errorMessage);

  const [hoveredValue, setHoveredValue] = React.useState<number | null>(null);

  // Ensure value is within valid range
  const currentValue = value && value >= 1 && value <= range ? value : undefined;

  // Handle rating selection
  const handleSelect = (ratingValue: number): void => {
    if (!disabled) {
      onChange(ratingValue);
    }
  };

  // The options share a radio group name (single Tab stop, native <input> as
  // the focusable control), but selection is decoupled from arrow-key focus
  // moves because selecting can trigger auto-progress (see useRovingRadioGroup).
  const ratingValues = Array.from({ length: range }, (_, i) => String(i + 1));
  const { getRadioProps, keyboardValue } = useRovingRadioGroup({
    values: ratingValues,
    selectedValue: currentValue === undefined ? undefined : String(currentValue),
    onSelect: (v) => {
      handleSelect(Number(v));
    },
  });

  // The value the scale previews before anything is selected: the pointer first, otherwise the
  // option the respondent arrowed to. Deliberately NOT every focus: cards autofocus their first
  // control on mount (focusFirstControl in block-conditional.tsx), and previewing that painted
  // option 1 as hovered — grey on the number scale, a filled star or smiley — on a card nobody had
  // touched yet (ENG-2288). `keyboardValue` is only set by an explicit arrow/Home/End move, so the
  // preview a pointer user gets on hover is the one a keyboard user gets on arrow, and mount focus
  // gets none (it is marked by the focus ring in survey-ui's globals.css, like every other card).
  const previewValue = hoveredValue ?? (keyboardValue === null ? null : Number(keyboardValue));

  // Get number option color for color coding
  const getRatingNumberOptionColor = (ratingRange: number, idx: number): string => {
    if (ratingRange > 5) {
      if (ratingRange - idx < 2) return "bg-emerald-100";
      if (ratingRange - idx < 4) return "bg-orange-100";
      return "bg-rose-100";
    } else if (ratingRange < 5) {
      if (ratingRange - idx < 1) return "bg-emerald-100";
      if (ratingRange - idx < 2) return "bg-orange-100";
      return "bg-rose-100";
    }
    if (ratingRange - idx < 2) return "bg-emerald-100";
    if (ratingRange - idx < 3) return "bg-orange-100";
    return "bg-rose-100";
  };

  // Render number scale option
  const renderNumberOption = (number: number, totalLength: number): React.JSX.Element => {
    const isSelected = currentValue === number;
    const isHovered = previewValue === number;
    const isLast = totalLength === number;
    const isFirst = number === 1;

    // Use CSS logical properties for RTL-aware borders and border radius
    // The parent div's dir attribute automatically handles direction
    const { borderRadiusClasses, borderClasses } = getRTLScaleOptionClasses(isFirst, isLast);

    return (
      <label
        key={number}
        data-fb-scale-cell
        data-fb-part={FB_PART.option}
        data-checked={isSelected ? "true" : undefined}
        className={cn(
          "text-input-text font-input font-input-weight relative flex w-full cursor-pointer items-center justify-center overflow-hidden transition-colors",
          borderClasses,
          isSelected
            ? "bg-brand-20 border-brand z-10 -ml-[1px] border-2 first:ml-0"
            : "border-input-border bg-input-bg",
          borderRadiusClasses,
          isHovered && !isSelected && "bg-input-selected-bg",
          colorCoding ? "min-h-[47px]" : "min-h-[41px]",
          disabled && "cursor-not-allowed opacity-50"
        )}
        onMouseEnter={() => {
          if (!disabled) {
            setHoveredValue(number);
          }
        }}
        onMouseLeave={() => {
          setHoveredValue(null);
        }}>
        {colorCoding ? (
          <div
            className={cn("absolute top-0 left-0 h-[6px] w-full", getRatingNumberOptionColor(range, number))}
          />
        ) : null}
        <input
          type="radio"
          name={inputId}
          value={number}
          checked={isSelected}
          onChange={() => {
            handleSelect(number);
          }}
          disabled={disabled}
          className="sr-only"
          aria-label={`Rate ${String(number)} out of ${String(range)}`}
          {...getRadioProps(String(number))}
        />
        <span className="text-sm">{number}</span>
      </label>
    );
  };

  // Render star scale option
  const renderStarOption = (number: number): React.JSX.Element => {
    const isSelected = currentValue === number;
    // Fill all stars up to the previewed value (pointer or arrow key) or the selected value
    const activeValue = previewValue ?? currentValue ?? 0;
    const isActive = number <= activeValue;

    return (
      // The flex-1 wrapper keeps the even column layout; the label is sized to the icon so the
      // global focus ring hugs the star (matching the design) instead of spanning the whole cell.
      <div key={number} className="flex flex-1 items-center justify-center">
        <label
          data-fb-part={FB_PART.option}
          data-checked={isSelected ? "true" : undefined}
          className={cn(
            "flex min-h-[48px] w-full max-w-[74px] cursor-pointer items-center justify-center rounded-lg transition-opacity",
            disabled && "cursor-not-allowed opacity-50"
          )}
          onMouseEnter={() => {
            if (!disabled) {
              setHoveredValue(number);
            }
          }}
          onMouseLeave={() => {
            setHoveredValue(null);
          }}>
          <input
            type="radio"
            name={inputId}
            value={number}
            checked={isSelected}
            onChange={() => {
              handleSelect(number);
            }}
            disabled={disabled}
            className="sr-only"
            aria-label={`Rate ${String(number)} out of ${String(range)} stars`}
            {...getRadioProps(String(number))}
          />
          <div className="pointer-events-none flex w-full items-center justify-center">
            {isActive ? (
              <Star className="h-full w-full fill-yellow-400 text-yellow-400 transition-colors" />
            ) : (
              <Star className="h-full w-full fill-slate-300 text-slate-300 transition-colors" />
            )}
          </div>
        </label>
      </div>
    );
  };

  // Render smiley scale option
  const renderSmileyOption = (number: number, index: number): React.JSX.Element => {
    const isSelected = currentValue === number;
    const isActive = isSelected || previewValue === number;
    // Fill and ink are one decision: a face with a fill carries its own ink, because every fill the
    // scale paints is light in both appearances (ENG-3937).
    const { fill, ink } = getSmileyColorClasses(range, index, isActive, colorCoding);

    return (
      // The flex-1 wrapper keeps the even column layout; the label is sized to the icon so the
      // global focus ring hugs the smiley (matching the design) instead of spanning the whole cell.
      <div key={number} className="flex flex-1 items-center justify-center">
        <label
          data-fb-part={FB_PART.option}
          data-checked={isSelected ? "true" : undefined}
          className={cn(
            "relative flex max-h-16 min-h-9 w-full max-w-[74px] cursor-pointer justify-center rounded-lg transition-colors",
            isActive ? "stroke-brand text-brand" : "stroke-muted-foreground text-muted-foreground",
            disabled && "cursor-not-allowed opacity-50"
          )}
          onMouseEnter={() => {
            if (!disabled) {
              setHoveredValue(number);
            }
          }}
          onMouseLeave={() => {
            setHoveredValue(null);
          }}>
          <input
            type="radio"
            name={inputId}
            value={number}
            checked={isSelected}
            onChange={() => {
              handleSelect(number);
            }}
            disabled={disabled}
            className="sr-only"
            aria-label={`Rate ${String(number)} out of ${String(range)}`}
            {...getRadioProps(String(number))}
          />
          <div className={cn("text-input-text pointer-events-none h-full w-full object-contain", ink)}>
            <RatingSmiley idx={index} range={range} fillClass={fill} />
          </div>
        </label>
      </div>
    );
  };

  // Generate rating options
  const ratingOptions = Array.from({ length: range }, (_, i) => i + 1);

  return (
    <div className="w-full space-y-4" id={elementId} dir={dir}>
      {/* The whole scale is one radio group, named by its headline via aria-labelledby. This
          replaces a dangling <label htmlFor> (the headline pointed at a non-input); the headline
          stays a plain block so its media/required badge are not nested in a <legend> (invalid
          HTML). role="radiogroup" keeps aria-required valid. */}
      <fieldset
        className="w-full space-y-4"
        role="radiogroup"
        aria-labelledby={`${inputId}-headline`}
        aria-required={required}
        aria-invalid={errorAria.ariaInvalid}
        aria-describedby={errorAria.ariaDescribedBy}
        dir={dir}>
        <ElementHeader
          headlineId={`${inputId}-headline`}
          headline={headline}
          description={description}
          required={required}
          requiredLabel={requiredLabel}
          imageUrl={imageUrl}
          imageAltText={imageAltText}
          videoUrl={videoUrl}
        />

        {/* Rating Options */}
        <div className="relative" data-element-input>
          <ElementError errorMessage={errorMessage} dir={dir} id={errorAria.errorId} />
          <div className="flex w-full px-[2px]">
            {ratingOptions.map((number, index) => {
              if (scale === "number") {
                return renderNumberOption(number, ratingOptions.length);
              } else if (scale === "star") {
                return renderStarOption(number);
              }
              return renderSmileyOption(number, index);
            })}
          </div>

          {/* Labels */}
          {(lowerLabel ?? upperLabel) ? (
            <div className="mt-4 flex justify-between gap-8 px-1.5">
              {lowerLabel ? (
                <Label variant="card" className="max-w-[50%] leading-6" dir={dir}>
                  {lowerLabel}
                </Label>
              ) : null}
              {upperLabel ? (
                <Label variant="card" className="max-w-[50%] text-right leading-6" dir={dir}>
                  {upperLabel}
                </Label>
              ) : null}
            </div>
          ) : null}
        </div>
      </fieldset>
    </div>
  );
}

export { Rating };
export type { RatingProps };
