import React, { useRef, useState } from 'react';
import { FormField, DatePicker } from '@wix/design-system';
import { BaseInputProps, BaseInputRef } from '../BaseInput';
import { Field } from '../Field';
import { dataHooks } from '../dataHooks';
import { useCustomFieldsFormContext } from '../../components/CustomFieldsFormContext';
import {
  getDateWithoutTimezone,
  getISODateStringWithFixedTimezone,
} from '../../utils/datesUtil';

export interface DateInputProps extends BaseInputProps<string | null> {}

export const DateInput = ({
  dataHook,
  schema,
  initialValue,
  inputRef,
  onChange,
}: DateInputProps) => {
  const [date, setDate] = useState<Date | undefined>(() =>
    initialValue
      ? getDateWithoutTimezone(getISODateStringWithFixedTimezone(initialValue))
      : undefined,
  );

  const ref = useRef<BaseInputRef>({});
  const [statusMessage, setStatusMessage] = useState('');
  const formState = useCustomFieldsFormContext();

  return (
    <Field dataHook={dataHook} type={schema.type}>
      <FormField dataHook={dataHooks.Label} label={schema.label}>
        <DatePicker
          ref={(internalRef) => {
            inputRef?.(ref.current);
            // TODO: PR to WSR needed to expose as public API
            // @ts-expect-error
            ref.current.focus = () => internalRef?.state?.inputRef?.focus?.();
          }}
          dataHook={dataHooks.Input}
          width="100%"
          value={date}
          onChange={(newValue: Date) => {
            const formatedDate = getISODateStringWithFixedTimezone(newValue);
            setDate(newValue);
            onChange(formatedDate.split('T')[0]);
          }}
          onValidate={({ validationType, value, format }) => {
            if (validationType === 'valid') {
              setStatusMessage('');
              ref.current.invalid = false;
            } else if (validationType === 'formatError' && value === '') {
              setDate(undefined);
              onChange(null);
              setStatusMessage('');
              ref.current.invalid = false;
            } else {
              setStatusMessage(
                formState._translate(
                  'cairo.customFields.fieldType.date.invalid.value',
                  { dateFormat: format ?? '' },
                ),
              );
              ref.current.invalid = true;
            }
          }}
          status={ref.current.invalid ? 'error' : undefined}
          statusMessage={statusMessage}
        />
      </FormField>
    </Field>
  );
};
