'use client';

import type {
  AllowedCharacters,
  PropertyType,
  PropertyValidation,
} from '@/features/custom-properties/api.client';

/**
 * Validation rules in the property editor's Field type section (HUB-354): number range and
 * decimal places, text length, allowed characters and a format (regex), date range, past or
 * future dates and weekdays. Kept as typed
 * text until saved; the API checks every write against them (records, imports, forms).
 */

export interface RulesDraft {
  minValue: string;
  maxValue: string;
  decimalPlaces: string;
  minLength: string;
  maxLength: string;
  characters: AllowedCharacters;
  pattern: string;
  minDate: string;
  maxDate: string;
  noPastDates: boolean;
  noFutureDates: boolean;
  weekdaysOnly: boolean;
}

export const EMPTY_RULES: RulesDraft = {
  minValue: '',
  maxValue: '',
  decimalPlaces: '',
  minLength: '',
  maxLength: '',
  characters: 'any',
  pattern: '',
  minDate: '',
  maxDate: '',
  noPastDates: false,
  noFutureDates: false,
  weekdaysOnly: false,
};

const CHARACTER_OPTIONS: Array<[AllowedCharacters, string]> = [
  ['any', 'Any characters'],
  ['letters', 'Letters only'],
  ['numbers', 'Numbers only'],
  ['alphanumeric', 'Letters and numbers (no special characters)'],
];

/** Which rules a field kind takes: by data type, characters on plain text only. */
export function rulesKind(
  type: PropertyType,
  fieldType: string | undefined,
): 'number' | 'text' | 'textarea' | 'date' | null {
  if (type === 'number') return 'number';
  // #247: File takes none (the design's rules are for text and number properties).
  if (fieldType === 'file') return null;
  if (type === 'text') return fieldType ? 'textarea' : 'text';
  if (type === 'textarea') return 'textarea';
  if (type === 'date' || type === 'datetime') return 'date';
  return null;
}

const str = (v: number | undefined) => (v === undefined ? '' : String(v));

export function rulesDraftOf(v: PropertyValidation | null | undefined): RulesDraft {
  if (!v) return EMPTY_RULES;
  return {
    minValue: str(v.minValue),
    maxValue: str(v.maxValue),
    decimalPlaces: str(v.decimalPlaces),
    minLength: str(v.minLength),
    maxLength: str(v.maxLength),
    characters: v.characters ?? 'any',
    pattern: v.pattern ?? '',
    minDate: v.minDate ?? '',
    maxDate: v.maxDate ?? '',
    noPastDates: v.noPastDates ?? false,
    noFutureDates: v.noFutureDates ?? false,
    weekdaysOnly: v.weekdaysOnly ?? false,
  };
}

const num = (s: string) => (s.trim() === '' ? undefined : Number(s));

/**
 * The rules to save for a field of `kind`, or null for none; `error` says what to fix first.
 * Rules of other kinds (left from a kind switched away from) are dropped.
 */
export function rulesOf(
  d: RulesDraft,
  kind: ReturnType<typeof rulesKind>,
): { rules: PropertyValidation | null; error: string | null } {
  const rules: PropertyValidation = {};
  let error: string | null = null;
  if (kind === 'number') {
    const [min, max, places] = [num(d.minValue), num(d.maxValue), num(d.decimalPlaces)];
    if ([min, max].some((n) => n !== undefined && !Number.isFinite(n))) {
      error = 'Enter numbers for the minimum and maximum';
    } else if (min !== undefined && max !== undefined && min > max) {
      error = 'The minimum is more than the maximum';
    } else if (places !== undefined && !(Number.isInteger(places) && places >= 0 && places <= 10)) {
      error = 'Decimal places is a whole number from 0 to 10';
    }
    if (min !== undefined) rules.minValue = min;
    if (max !== undefined) rules.maxValue = max;
    if (places !== undefined) rules.decimalPlaces = places;
  } else if (kind === 'text' || kind === 'textarea') {
    const [min, max] = [num(d.minLength), num(d.maxLength)];
    if (
      [min, max].some((n) => n !== undefined && !(Number.isInteger(n) && n >= 1 && n <= 10_000))
    ) {
      error = 'Lengths are whole numbers from 1 to 10,000';
    } else if (min !== undefined && max !== undefined && min > max) {
      error = 'The minimum length is more than the maximum';
    }
    if (min !== undefined) rules.minLength = min;
    if (max !== undefined) rules.maxLength = max;
    if (kind === 'text' && d.characters !== 'any') rules.characters = d.characters;
    const pattern = d.pattern.trim();
    if (kind === 'text' && pattern) {
      try {
        // A first check only: the API runs patterns on RE2 and has the last word (it allows
        // `\-`, which JavaScript's unicode mode refuses, and no lookarounds).
        new RegExp(pattern);
        rules.pattern = pattern;
      } catch {
        error ??= 'The format is not a valid regular expression';
      }
    }
  } else if (kind === 'date') {
    if (d.minDate && d.maxDate && d.minDate > d.maxDate) {
      error = 'The earliest date is after the latest';
    }
    if (d.minDate) rules.minDate = d.minDate;
    if (d.maxDate) rules.maxDate = d.maxDate;
    if (d.noPastDates) rules.noPastDates = true;
    if (d.noFutureDates) rules.noFutureDates = true;
    if (d.noPastDates && d.noFutureDates)
      error ??= 'Past and future dates are both refused: only today is left';
    if (d.weekdaysOnly) rules.weekdaysOnly = true;
  }
  return { rules: Object.keys(rules).length ? rules : null, error };
}

export function ValidationRulesFields({
  kind,
  value,
  error,
  disabled,
  onChange,
}: {
  kind: ReturnType<typeof rulesKind>;
  value: RulesDraft;
  error: string | null;
  disabled: boolean;
  onChange: (patch: Partial<RulesDraft>) => void;
}) {
  if (!kind) return null;
  const input = (key: keyof RulesDraft, label: string, type: 'number' | 'date', step?: string) => (
    <label className="dm-field">
      <span className="dm-field__label">{label}</span>
      <input
        className="dm-input"
        type={type}
        step={step}
        value={value[key] as string}
        disabled={disabled}
        onChange={(e) => onChange({ [key]: e.target.value })}
      />
    </label>
  );
  return (
    <fieldset className="dm-field dm-pe__fs dm-rules">
      <legend className="dm-field__label">Validation rules</legend>
      <span className="dm-field__hint">
        Values must follow these rules when records are edited, imported or sent from forms. Values
        already saved stay until they are changed.
      </span>
      {kind === 'number' ? (
        <div className="dm-rules__grid">
          {input('minValue', 'Minimum value', 'number', 'any')}
          {input('maxValue', 'Maximum value', 'number', 'any')}
          {input('decimalPlaces', 'Decimal places allowed', 'number', '1')}
        </div>
      ) : null}
      {kind === 'text' || kind === 'textarea' ? (
        <div className="dm-rules__grid">
          {input('minLength', 'Minimum characters', 'number', '1')}
          {input('maxLength', 'Maximum characters', 'number', '1')}
          {kind === 'text' ? (
            <label className="dm-field">
              <span className="dm-field__label">Allowed characters</span>
              <select
                className="dm-input"
                value={value.characters}
                disabled={disabled}
                onChange={(e) => onChange({ characters: e.target.value as AllowedCharacters })}
              >
                {CHARACTER_OPTIONS.map(([v, label]) => (
                  <option key={v} value={v}>
                    {label}
                  </option>
                ))}
              </select>
            </label>
          ) : null}
          {kind === 'text' ? (
            <label className="dm-field">
              <span className="dm-field__label">Format (regular expression)</span>
              <input
                className="dm-input"
                value={value.pattern}
                placeholder={String.raw`e.g. [A-Z]{2}-\d{4}`}
                maxLength={200}
                disabled={disabled}
                onChange={(e) => onChange({ pattern: e.target.value })}
              />
            </label>
          ) : null}
        </div>
      ) : null}
      {kind === 'date' ? (
        <>
          <div className="dm-rules__grid">
            {input('minDate', 'Earliest date', 'date')}
            {input('maxDate', 'Latest date', 'date')}
          </div>
          <label className="dm-check dm-check--plain">
            <input
              type="checkbox"
              checked={value.weekdaysOnly}
              disabled={disabled}
              onChange={(e) => onChange({ weekdaysOnly: e.target.checked })}
            />
            <span>Weekdays only (Monday to Friday)</span>
          </label>
          <label className="dm-check dm-check--plain">
            <input
              type="checkbox"
              checked={value.noPastDates}
              disabled={disabled}
              onChange={(e) => onChange({ noPastDates: e.target.checked })}
            />
            <span>No past dates</span>
          </label>
          <label className="dm-check dm-check--plain">
            <input
              type="checkbox"
              checked={value.noFutureDates}
              disabled={disabled}
              onChange={(e) => onChange({ noFutureDates: e.target.checked })}
            />
            <span>No future dates</span>
          </label>
        </>
      ) : null}
      {error ? <p className="dm-field__error">{error}</p> : null}
    </fieldset>
  );
}
