import * as React from 'react';
import { TextControl, tailwind } from '@tesseract-design/web-base';
import { useFallbackId } from '@modal-sh/react-utils';

const { tw } = tailwind;

const DateDropdownDerivedElementComponent = 'input';

/**
 * Derived HTML element of the {@link DateDropdown} component.
 */
export type DateDropdownDerivedElement = HTMLElementTagNameMap[
  typeof DateDropdownDerivedElementComponent
];

/**
 * Props of the {@link DateDropdown} component.
 */
export interface DateDropdownProps extends Omit<React.HTMLProps<DateDropdownDerivedElement>, 'size' | 'type' | 'label' | 'pattern'> {
  /**
   * Short textual description indicating the nature of the component's value.
   */
  label?: React.ReactNode,
  /**
   * Short textual description as guidelines for valid input values.
   */
  hint?: React.ReactNode,
  /**
   * Size of the component.
   */
  size?: TextControl.Size,
  /**
   * Should the component display a border?
   */
  border?: boolean,
  /**
   * Should the component occupy the whole width of its parent?
   */
  block?: boolean,
  /**
   * Style of the component.
   */
  variant?: TextControl.Variant,
  /**
   * Is the label hidden?
   */
  hiddenLabel?: boolean,
  /**
   * Visual length of the input.
   */
  length?: number,
}

export const dateDropdownPlugin: tailwind.PluginCreator = ({ addComponents }) => {
  addComponents({
    '.date-dropdown': {
      '& > input::-webkit-calendar-picker-indicator': {
        'background-image': 'none',
        'position': 'absolute',
        'bottom': '0',
        'right': '0',
        'height': '100%',
        'padding': '0',
        'aspect-ratio': '1 / 1',
        'cursor': 'inherit',
      },
      '&[data-size="small"] > input::-webkit-calendar-picker-indicator': {
        'width': '2.5rem',
      },
      '&[data-size="medium"] > input::-webkit-calendar-picker-indicator': {
        'width': '3rem',
      },
      '&[data-size="large"] > input::-webkit-calendar-picker-indicator': {
        'width': '4rem',
      },
    },
  });
};

/**
 * Component for inputting date values.
 */
export const DateDropdown = React.forwardRef<
  DateDropdownDerivedElement,
  DateDropdownProps
>((
  {
    label,
    hint,
    size = 'medium' as const,
    border = false,
    block = false,
    variant = 'default' as const,
    hiddenLabel = false,
    className,
    id: idProp,
    style,
    length,
    ...etcProps
  }: DateDropdownProps,
  forwardedRef,
) => {
  const labelId = React.useId();
  const id = useFallbackId(idProp);

  return (
    <div
      className={tw(
        'relative rounded ring-secondary/50 overflow-hidden group has-[:disabled]:opacity-50 date-dropdown',
        'focus-within:ring-4',
        {
          'block': block,
          'inline-block align-middle': !block,
        },
        className,
      )}
      style={style}
      data-size={size}
      data-testid="base"
    >
      {label && (
        <>
          <label
            data-testid="label"
            id={labelId}
            htmlFor={id}
            className={tw(
              'absolute z-[1] w-full top-0.5 left-0 pointer-events-none pl-1 text-xxs font-bold group-focus-within:text-secondary text-primary leading-none bg-negative select-none',
              {
                'sr-only': hiddenLabel,
              },
              {
                'pr-10': size === 'small',
                'pr-12': size === 'medium',
                'pr-16': size === 'large',
              },
            )}
          >
            <span className="block w-full whitespace-nowrap h-[1.1em] overflow-hidden text-ellipsis">
              {label}
            </span>
          </label>
          {' '}
        </>
      )}
      <DateDropdownDerivedElementComponent
        {...etcProps}
        size={length}
        ref={forwardedRef}
        id={id}
        aria-labelledby={labelId}
        type="date"
        data-testid="input"
        pattern="\d{4}-\d{2}-\d{2}"
        className={tw(
          'bg-negative rounded-inherit w-full peer block font-inherit tabular-nums cursor-pointer',
          'focus:outline-0',
          'disabled:cursor-not-allowed',
          {
            'pl-4': variant === 'default',
            'pl-1.5 pt-4': variant === 'alternate',
          },
          {
            'pr-10 h-10 text-xxs': size === 'small',
            'pr-12 h-12 text-xs': size === 'medium',
            'pr-16 h-16': size === 'large',
          },
        )}
      />
      {hint && (
        <div
          data-testid="hint"
          className={tw(
            'absolute left-0 px-1 pointer-events-none text-xxs leading-none w-full bg-negative select-none',
            {
              'bottom-0 pl-4 pb-1': variant === 'default',
              'top-0.5': variant === 'alternate',
            },
            {
              'pt-2': variant === 'alternate' && size === 'small',
              'pt-3': variant === 'alternate' && size !== 'small',
            },
            {
              'pr-10': size === 'small',
              'pr-12': size === 'medium',
              'pr-16': size === 'large',
            },
          )}
        >
          <div
            className="opacity-50 whitespace-nowrap w-full h-[1.1em] overflow-hidden text-ellipsis"
          >
            {hint}
          </div>
        </div>
      )}
      <div
        data-testid="indicator"
        className={tw(
          'text-center flex items-center justify-center aspect-square absolute bottom-0 right-0 pointer-events-none select-none text-primary group-focus-within:text-secondary',
          {
            'w-10': size === 'small',
            'w-12': size === 'medium',
            'w-16': size === 'large',
          },
        )}
      >
        <svg
          className="w-6 h-6 fill-none stroke-current stroke-2 linejoin-round linecap-round"
          viewBox="0 0 24 24"
          role="presentation"
        >
          <rect
            x="3"
            y="4"
            width="18"
            height="18"
            rx="2"
            ry="2"
          />
          <line
            x1="16"
            y1="2"
            x2="16"
            y2="6"
          />
          <line
            x1="8"
            y1="2"
            x2="8"
            y2="6"
          />
          <line
            x1="3"
            y1="10"
            x2="21"
            y2="10"
          />
        </svg>
      </div>
      {border && (
        <span
          data-testid="border"
          className="absolute z-[1] inset-0 rounded-inherit border-2 border-primary pointer-events-none group-focus-within:border-secondary"
        />
      )}
    </div>
  );
});

DateDropdown.displayName = 'DateDropdown';

DateDropdown.defaultProps = {
  label: undefined,
  hint: undefined,
  size: 'medium',
  border: false,
  block: false,
  variant: 'default',
  hiddenLabel: false,
  length: undefined,
};
