import { clsx } from 'clsx';
import { createRef, PureComponent, KeyboardEvent } from 'react';
import Calendar from '../calendar';
import {
  Size,
  MonthFormat,
  Position,
  type SizeSmall,
  type SizeMedium,
  type SizeLarge,
} from '../common';
import ResponsivePanel from '../common/responsivePanel';
import { WithInputAttributesProps, withInputAttributes } from '../inputs/contexts';
import { OverlayIdProvider } from '../provider/overlay/OverlayIdProvider';
import DateTrigger from './dateTrigger';

export interface DateLookupProps {
  id?: string;
  value: Date | null;
  min?: Date | null;
  max?: Date | null;
  size?: SizeSmall | SizeMedium | SizeLarge;
  placeholder?: string;
  label?: string;
  'aria-labelledby'?: string;
  monthFormat?: `${MonthFormat}`;
  disabled?: boolean;
  clearable?: boolean;
  onChange: (date: Date | null) => void;
  onFocus?: () => void;
  onBlur?: () => void;
}

type DateLookupPropsWithInputAttributes = DateLookupProps & Partial<WithInputAttributesProps>;

interface DateLookupState {
  originalDate: Date | null;
  open: boolean;
}

class DateLookup extends PureComponent<DateLookupPropsWithInputAttributes, DateLookupState> {
  declare props: DateLookupPropsWithInputAttributes &
    Required<Pick<DateLookupPropsWithInputAttributes, keyof typeof DateLookup.defaultProps>>;

  static defaultProps = {
    value: null,
    min: null,
    max: null,
    size: Size.MEDIUM,
    placeholder: '',
    label: '',
    monthFormat: MonthFormat.LONG,
    disabled: false,
    clearable: false,
  } satisfies Partial<DateLookupPropsWithInputAttributes>;

  element = createRef<HTMLDivElement>();

  constructor(props: DateLookup['props']) {
    super(props);
    this.state = {
      originalDate: null,
      open: false,
    };
  }

  componentDidUpdate(previousProps: DateLookupPropsWithInputAttributes) {
    if (this.props.value?.getTime() !== previousProps.value?.getTime() && this.state.open) {
      this.focusOn('.active');
    }
  }

  open = () => {
    const { onFocus } = this.props;

    this.setState({ open: true });
    if (onFocus) {
      onFocus();
    }
  };

  discard = () => {
    const { originalDate } = this.state;
    if (originalDate !== null) {
      this.props.onChange(originalDate);
    }
    this.close();
  };

  close = () => {
    const { onBlur } = this.props;
    this.setState({ open: false, originalDate: null });
    if (onBlur) {
      onBlur();
    }
  };

  handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    const { open, originalDate } = this.state;
    switch (event.key) {
      case 'ArrowLeft':
      case 'ArrowUp':
      case 'ArrowRight':
      case 'ArrowDown':
        if (!open) {
          this.open();
          event.preventDefault();
        }
        break;
      case 'Escape':
        if (originalDate !== null) {
          this.props.onChange(originalDate);
        }
        this.close();
        event.preventDefault();
        break;
      default:
        break;
    }
  };

  focusOn = (preferredElement: string, fallbackElement?: string) => {
    const element = this.element.current?.querySelector(preferredElement) as HTMLElement | null;
    if (element) {
      element.focus();
    } else if (fallbackElement) {
      this.focusOn(fallbackElement);
    }
  };

  handleDateChange = (date: Date | null) => {
    this.setState(
      (state) => {
        const originalDate = state.originalDate ?? this.props.value;
        return { originalDate };
      },
      () => {
        this.props.onChange(date);
      },
    );
  };

  handleDateSelect = (date: Date) => {
    this.props.onChange(date);
    this.close();
    this.focusOn('.btn');
  };

  getCalendar = () => {
    const { value, min, max, monthFormat, placeholder } = this.props;
    return (
      <div className="p-a-1">
        <Calendar
          value={value}
          min={min}
          max={max}
          monthFormat={monthFormat}
          placeholder={placeholder}
          onChange={this.handleDateChange}
          onSelect={this.handleDateSelect}
        />
      </div>
    );
  };

  handleClear = () => {
    this.props.onChange(null);
    this.focusOn('.np-date-trigger');
  };

  render() {
    const { open } = this.state;

    const {
      inputAttributes,
      id: idProp,
      'aria-labelledby': ariaLabelledByProp,
      size,
      placeholder,
      label,
      monthFormat,
      disabled,
      clearable,
      value,
    } = this.props;
    const id = idProp ?? inputAttributes?.id;
    const ariaLabelledBy = ariaLabelledByProp ?? inputAttributes?.['aria-labelledby'];

    return (
      <div
        ref={this.element}
        aria-labelledby={id}
        aria-invalid={inputAttributes?.['aria-invalid']}
        aria-describedby={inputAttributes?.['aria-describedby']}
        className={clsx('input-group', disabled && 'disabled')}
        onKeyDown={this.handleKeyDown}
      >
        <OverlayIdProvider open={open}>
          <DateTrigger
            id={id}
            ariaLabelledBy={ariaLabelledBy}
            selectedDate={value}
            size={size}
            placeholder={placeholder}
            label={label}
            monthFormat={monthFormat}
            disabled={disabled || false}
            onClick={this.open}
            onClear={!disabled && clearable && value ? this.handleClear : undefined}
          />
          <ResponsivePanel
            anchorRef={this.element}
            open={open}
            className="tw-date-lookup-menu"
            position={Position.BOTTOM}
            considerHeight
            onClose={this.discard}
          >
            {this.getCalendar()}
          </ResponsivePanel>
        </OverlayIdProvider>
      </div>
    );
  }
}

export const DateLookupWithoutInputAttributes = DateLookup;

const WrappedDateLookup = withInputAttributes(
  DateLookup as React.ComponentType<DateLookupPropsWithInputAttributes>,
  { nonLabelable: true },
);
WrappedDateLookup.displayName = 'DateLookup';

export default WrappedDateLookup;
