import { useId, useMemo } from 'react';
import type { DateInputProps } from './DateInput';
import { Input } from '../input/Input';
import './date-range-inputs.css';

/** Props for each side of the range (same as DateInput, without per-field label/helper/error — those live on the group). */
export type DateRangeSideProps = Omit<DateInputProps, 'label' | 'error' | 'errorMessage' | 'helperText' | 'type'>;

export type DateRangeInputsProps = {
  className?: string;
  /** Visible label for the pair (default "Date range"). Pass "" to hide and use `aria-label` on the group instead. */
  label?: string;
  /** When `label` is empty, use this for the group’s accessible name. */
  'aria-label'?: string;
  error?: boolean;
  errorMessage?: string;
  helperText?: string;
  required?: boolean;
  start?: DateRangeSideProps;
  end?: DateRangeSideProps;
};

function mergeClassNames(a: string | undefined, b: string): string {
  return [b, a].filter(Boolean).join(' ');
}

function mergeDescribedBy(...parts: (string | undefined)[]): string | undefined {
  const s = parts.filter(Boolean).join(' ').trim();
  return s || undefined;
}

export function DateRangeInputs({
  className,
  label = 'Date range',
  'aria-label': groupAriaLabel,
  error = false,
  errorMessage = '',
  helperText = '',
  required,
  start,
  end,
}: DateRangeInputsProps) {
  const uid = useId().replace(/:/g, '');
  const hintId = `ccl-date-range-${uid}-hint`;
  const errorId = `ccl-date-range-${uid}-error`;

  const hasLegend = label.length > 0;

  const groupDescribedBy = useMemo(() => {
    const ids: string[] = [];
    if (helperText) ids.push(hintId);
    if (error && errorMessage) ids.push(errorId);
    return ids.length ? ids.join(' ') : undefined;
  }, [helperText, hintId, error, errorMessage, errorId]);

  const startRest = start ?? {};
  const endRest = end ?? {};

  const startAria = mergeDescribedBy(groupDescribedBy, startRest['aria-describedby']);
  const endAria = mergeDescribedBy(groupDescribedBy, endRest['aria-describedby']);

  const shellClass = [
    'ccl-date-range-picker__shell',
    error ? 'ccl-date-range-picker__shell--error' : '',
    startRest.disabled && endRest.disabled ? 'ccl-date-range-picker__shell--disabled' : '',
  ]
    .filter(Boolean)
    .join(' ');

  return (
    <div
      className={['ccl-input-wrapper', 'ccl-date-range-picker', error ? 'ccl-date-range-picker--error' : '', className ?? '']
        .filter(Boolean)
        .join(' ')}
    >
      <fieldset
        className="ccl-date-range-picker__fieldset"
        aria-label={!hasLegend ? (groupAriaLabel ?? 'Date range') : undefined}
      >
        {hasLegend ? (
          <legend className="ccl-input__label">
            {label}
            {required ? (
              <span className="ccl-input__required" aria-label="required">
                *
              </span>
            ) : null}
          </legend>
        ) : null}

        <div className={shellClass}>
          <Input
            type="date"
            label=""
            error={error}
            errorMessage=""
            helperText=""
            required={required}
            {...startRest}
            aria-label={startRest['aria-label'] ?? 'Start date'}
            aria-describedby={startAria}
            className={mergeClassNames(startRest.className, 'ccl-date-range-picker__native')}
          />
          <span className="ccl-date-range-picker__sep" aria-hidden="true">
            –
          </span>
          <Input
            type="date"
            label=""
            error={error}
            errorMessage=""
            helperText=""
            required={required}
            {...endRest}
            aria-label={endRest['aria-label'] ?? 'End date'}
            aria-describedby={endAria}
            className={mergeClassNames(endRest.className, 'ccl-date-range-picker__native')}
          />
        </div>
      </fieldset>

      {helperText ? (
        <span id={hintId} className="ccl-input__helper">
          {helperText}
        </span>
      ) : null}

      {error && errorMessage ? (
        <span id={errorId} className="ccl-input__error" role="alert">
          {errorMessage}
        </span>
      ) : null}
    </div>
  );
}
