import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';

dayjs.extend(customParseFormat);

const DATE_FORMAT = 'DD.MM.YYYY';
const DATETIME_FORMAT = 'DD.MM.YYYY HH:mm';

export function formatUnixDate(
  value: number | null | undefined,
  withTime: boolean,
): string {
  if (value == null || !Number.isFinite(value) || value === 0) {
    return '';
  }
  return dayjs.unix(value).format(withTime ? DATETIME_FORMAT : DATE_FORMAT);
}

function formatDigits(digits: string, segments: number[]): string {
  let result = '';
  let offset = 0;

  for (let i = 0; i < segments.length; i++) {
    const segment = digits.slice(offset, offset + segments[i]);
    if (!segment) break;
    if (i > 0) result += i === 3 ? ' ' : i === 4 ? ':' : '.';
    result += segment;
    offset += segments[i];
  }

  return result;
}

export function applyDateMask(raw: string): string {
  const digits = raw.replace(/\D/g, '').slice(0, 8);
  return formatDigits(digits, [2, 2, 4]);
}

export function applyDateTimeMask(raw: string): string {
  const digits = raw.replace(/\D/g, '').slice(0, 12);
  return formatDigits(digits, [2, 2, 4, 2, 2]);
}

export function applyDateInputMask(raw: string, withTime: boolean): string {
  return withTime ? applyDateTimeMask(raw) : applyDateMask(raw);
}

export function isMaskComplete(text: string, withTime: boolean): boolean {
  return withTime ? text.length === DATETIME_FORMAT.length : text.length === DATE_FORMAT.length;
}

export function parseMaskedDate(
  text: string,
  withTime: boolean,
): number | null {
  const trimmed = text.trim();
  if (!trimmed) return null;

  const format = withTime ? DATETIME_FORMAT : DATE_FORMAT;
  const parsed = dayjs(trimmed, format, true);
  if (!parsed.isValid()) return null;

  return parsed.unix();
}
