"use client";

import { InfoIcon, PlusIcon, TrashIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { TAllowedFileExtension } from "@formbricks/types/storage";
import {
  TSurveyElement,
  TSurveyElementTypeEnum,
  TSurveyOpenTextElementInputType,
} from "@formbricks/types/surveys/elements";
import {
  TAddressField,
  TContactInfoField,
  TValidationRule,
  TValidationRuleType,
} from "@formbricks/types/surveys/validation-rules";
import { cn } from "@/lib/cn";
import { Button } from "@/modules/ui/components/button";
import { RULE_TYPE_CONFIG } from "../lib/validation-rules-config";
import { describeRelativeDateRule, getAvailableRuleTypes, getRuleValue } from "../lib/validation-rules-utils";
import { ValidationRuleFieldSelector } from "./validation-rule-field-selector";
import { ValidationRuleInputTypeSelector } from "./validation-rule-input-type-selector";
import { ValidationRuleTypeSelector } from "./validation-rule-type-selector";
import { ValidationRuleUnitSelector } from "./validation-rule-unit-selector";
import { ValidationRuleValueInput } from "./validation-rule-value-input";

interface ValidationRuleRowProps {
  rule: TValidationRule;
  index: number;
  elementType: TSurveyElementTypeEnum;
  element?: TSurveyElement;
  inputType?: TSurveyOpenTextElementInputType;
  onInputTypeChange?: (inputType: TSurveyOpenTextElementInputType) => void;
  fieldOptions: { value: TAddressField | TContactInfoField; label: string }[];
  needsFieldSelector: boolean;
  validationRules: TValidationRule[];
  ruleLabels: Record<string, string>;
  onFieldChange: (ruleId: string, field: TAddressField | TContactInfoField | undefined) => void;
  onRuleTypeChange: (ruleId: string, newType: TValidationRuleType) => void;
  onRuleValueChange: (ruleId: string, value: string) => void;
  onRuleParamsChange: (ruleId: string, params: TValidationRule["params"]) => void;
  onFileExtensionChange: (ruleId: string, extensions: TAllowedFileExtension[]) => void;
  onDelete: (ruleId: string) => void;
  onAdd: (insertAfterIndex: number) => void;
  canAddMore: boolean;
}

export const ValidationRuleRow = ({
  rule,
  index,
  elementType,
  element,
  inputType,
  onInputTypeChange,
  fieldOptions,
  needsFieldSelector,
  validationRules,
  ruleLabels,
  onFieldChange,
  onRuleTypeChange,
  onRuleValueChange,
  onRuleParamsChange,
  onFileExtensionChange,
  onDelete,
  onAdd,
  canAddMore,
}: Readonly<ValidationRuleRowProps>) => {
  const { t } = useTranslation();
  const ruleType = rule.type;
  const config = RULE_TYPE_CONFIG[ruleType];
  const currentValue = getRuleValue(rule);

  // Get available types for this rule (current type + unused types, no duplicates)
  // For address/contact info, filter by selected field
  const ruleField = rule.field;
  const otherAvailableTypes = getAvailableRuleTypes(
    elementType,
    validationRules.filter((r) => r.id !== rule.id),
    elementType === TSurveyElementTypeEnum.OpenText ? inputType : undefined,
    ruleField
  ).filter((t) => t !== ruleType);
  const availableTypesForSelect = [ruleType, ...otherAvailableTypes];

  // Check if this is OpenText and first rule - show input type selector
  const isOpenText = elementType === TSurveyElementTypeEnum.OpenText;
  const isFirstRule = index === 0;
  const showInputTypeSelector = isOpenText && isFirstRule;

  const handleFileExtensionChange = (extensions: TAllowedFileExtension[]) => {
    onFileExtensionChange(rule.id, extensions);
  };

  // Date rules put up to nine controls on the value side. The operator select soaks up whatever width
  // those controls leave and shrinks first when space is short; at its floor the row wraps, since the
  // toggle's container is overflow-hidden and would otherwise clip the trailing buttons.
  //
  // Every other rule stays on one line, so no control on it may carry a pixel min-width: the toggle's
  // container is overflow-hidden, so a child that refuses to shrink does not scroll into view, it
  // paints over the delete and add buttons and eats their clicks (ENG-3175). Only the two buttons are
  // shrink-0; everything else is min-w-0 and truncates.
  //
  // The three flexible children are sized `w-auto grow` so each asks for its own content width and
  // the surplus is shared equally. Left at the SelectTrigger's `w-full`, all three would ask for the
  // full row and the split would land on exact thirds — which starves the value group, the only one
  // of the three that holds two controls, down to a value field too narrow to read a number in.
  const isDateRule = Boolean(config.supportsRelative);
  const flexibleChildClasses = "w-auto grow";

  const row = (
    <div className={cn("flex w-full gap-2", isDateRule ? "flex-wrap items-start" : "items-center")}>
      {/* Field Selector (for Address and Contact Info elements) */}
      {needsFieldSelector && (
        <ValidationRuleFieldSelector
          value={rule.field}
          onChange={(value) => onFieldChange(rule.id, value)}
          fieldOptions={fieldOptions}
        />
      )}

      {/* Input Type Selector (only for OpenText, first rule) */}
      {showInputTypeSelector && inputType !== undefined && onInputTypeChange && (
        <ValidationRuleInputTypeSelector value={inputType} onChange={onInputTypeChange} />
      )}

      {/* Input Type Display (disabled, for subsequent rules) */}
      {isOpenText && !isFirstRule && inputType !== undefined && (
        <ValidationRuleInputTypeSelector value={inputType} disabled />
      )}

      {/* Rule Type Selector */}
      <ValidationRuleTypeSelector
        value={ruleType}
        onChange={(value) => onRuleTypeChange(rule.id, value)}
        availableTypes={availableTypesForSelect}
        ruleLabels={ruleLabels}
        needsValue={config.needsValue}
        className={isDateRule ? "min-w-[140px] flex-[1_1_0%]" : flexibleChildClasses}
      />

      {/* Value Input (if needed) */}
      {config.needsValue && (
        <div
          className={cn(
            "flex min-w-0 gap-2",
            isDateRule ? "flex-[0_1_auto] items-start" : `${flexibleChildClasses} items-center`
          )}>
          <ValidationRuleValueInput
            rule={rule}
            ruleType={ruleType}
            config={config}
            currentValue={currentValue}
            onChange={(value) => onRuleValueChange(rule.id, value)}
            onParamsChange={(params) => onRuleParamsChange(rule.id, params)}
            onFileExtensionChange={handleFileExtensionChange}
            element={element}
          />

          {/* Unit selector (if applicable) */}
          {config.unitOptions && config.unitOptions.length > 0 && (
            <ValidationRuleUnitSelector
              value={config.unitOptions[0].value}
              unitOptions={config.unitOptions}
              ruleLabels={ruleLabels}
              disabled={config.unitOptions.length === 1}
            />
          )}
        </div>
      )}

      {/* Delete button */}
      <Button
        variant="outline"
        size="icon"
        type="button"
        onClick={() => onDelete(rule.id)}
        className="shrink-0 bg-white"
        aria-label={t("workspace.surveys.edit.validation.delete_validation_rule")}>
        <TrashIcon className="size-4" />
      </Button>

      {/* Add button */}
      {canAddMore && (
        <Button
          variant="outline"
          size="icon"
          type="button"
          onClick={() => onAdd(index)}
          className="shrink-0 bg-white"
          aria-label={t("workspace.surveys.edit.validation.add_validation_rule")}>
          <PlusIcon className="size-4" />
        </Button>
      )}
    </div>
  );

  // A relative date rule is an offset expression; the sentence under the row says what it accepts.
  const relativeSummary = config.supportsRelative ? describeRelativeDateRule(ruleType, rule.params, t) : null;

  if (!relativeSummary) return row;

  return (
    <div className="flex w-full flex-col gap-1.5">
      {row}
      <p className="flex items-start gap-1.5 px-0.5 text-xs text-slate-500">
        <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-slate-400" aria-hidden="true" />
        <span>{relativeSummary}</span>
      </p>
    </div>
  );
};
