import { getClassNames } from '@websolutespa/bom-core';
import { FormControl, useControl } from '@websolutespa/bom-mixer-forms';
import { useLabel } from '@websolutespa/bom-mixer-hooks';
import { IconEye, IconEyeOff } from '@websolutespa/bom-mixer-icons';
import { ChangeEvent, FocusEvent, ReactElement, useEffect, useId, useRef, useState } from 'react';
import { Button } from '../components';
import { Field, Input, InputProps, Label } from '../forms';
import { FieldError } from './field-error';

type FieldPasswordProps = InputProps & {
  control: FormControl;
  icon?: (type: string) => ReactElement;
};

function getIcon(type: string) {
  return type === 'password' ? <IconEye /> : <IconEyeOff />;
}

export function FieldPassword({ control, icon = getIcon }: FieldPasswordProps) {
  const uid = useId();
  const label = useLabel();

  const uniqueName = `${control.name}-${uid}`;

  const [state, setValue, setTouched] = useControl<string>(control);

  const [focus, setFocus] = useState(false);

  const ref = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const onChange = (value: any) => {
      if (focus) {
        return;
      }
      if (ref.current) {
        ref.current.value = value;
      }
      // console.log('FieldText.onChange', ref.current, value);
    };
    // control.on('change', onChange);
    return () => control.off('change', onChange);
  }, [control, focus]);

  const [type, setType] = useState('password');

  const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    // console.log('FieldPassword', event.target.value);
    setValue(event.target.value);
    // control.value = event.target.value;
  };

  const onBlur = (_: FocusEvent<HTMLInputElement>) => {
    setTouched();
    setFocus(false);
  };

  const onFocus = (_: FocusEvent<HTMLInputElement>) => {
    setFocus(true);
  };

  const onToggle = () => {
    setType(type === 'password' ? 'text' : 'password');
  };

  const controlLabel = control.label && label(control.label);
  return (
    state.flags.hidden ? (
      <input type="hidden" value={state.value || ''} />
    ) : (
      <Field state={state} className={getClassNames({ required: control.required && !control.disabled })}>
        {controlLabel && (
          <Label htmlFor={uniqueName}>
            {controlLabel}
          </Label>
        )}

        <Input
          width="100%"
          ref={ref}
          id={uniqueName}
          name={uniqueName}
          type={type}
          placeholder={label(control.placeholder || control.label || '')}
          defaultValue={state.value || ''}
          onChange={onChange}
          onBlur={onBlur}
          onFocus={onFocus}
          required={state.errors.some(x => x.key === 'required')}
          disabled={state.flags.disabled}
          readOnly={state.flags.readonly}
          aria-invalid={state.flags.invalid}
          aria-describedby={`${uniqueName}-error`}
          autoComplete="on"
          after={
            <Button onClick={() => onToggle()}>
              {icon(type)}
            </Button>
          }
        />

        <FieldError state={state} label={controlLabel} id={`${uniqueName}-error`} />
      </Field>
    )
  );
}
