import clsx from 'clsx';
import { ChangeEvent, FC, ReactNode, useMemo, useRef, useState } from 'react';
import moment from 'moment';
import Icon from '@/components/Icon';
import { Datepicker } from '@/components/UI/Datepicker';
import { useClickOutside } from '@/hooks/useClickOutside';
import { Input } from '@/components/UI/Input';
import type { IDatePickerProps } from '@/components/UI/Datepicker/Datepicker';

interface DatepickerWithInputProps extends Omit<IDatePickerProps, 'onChange'> {
  label?: string | ReactNode;
  className?: string;
  placeholder?: string;
  /** параметр "дата" в формате YY:MM:DD  */
  onChange?: (date: string) => void;
}

const FORMAT = 'YY:MM:DD';

const DatepickerWithInput: FC<DatepickerWithInputProps> = ({
  className,
  label,
  placeholder,
  onChange,
  ...rest
}) => {
  const [inputValue, setInputValue] = useState<string>('');
  const wrapperRef = useRef<HTMLDivElement>(null);
  const [isOpenDatepicker, setIsOpenDatepicker] = useState<boolean>(false);

  useClickOutside(wrapperRef, () => setIsOpenDatepicker(false));

  const handleDatepickerChange = (date: Date | null): void => {
    if (date === null) {
      setInputValue('');
      onChange?.('');
      return;
    }
    onChange?.(moment(date).format(FORMAT));
    setInputValue(moment(date).format(FORMAT));
  };

  const handleInputChange = (event: ChangeEvent<HTMLInputElement>): void => {
    setInputValue(event.target.value);
    const [year, month, day] = event.target.value.split(':');
    const date = `${month}-${day}-${year}`;
    if (year && month && day && moment(date).isValid()) {
      onChange?.(moment(date).format(FORMAT));
    }
  };

  const datePickerData = useMemo((): { selected: Date | null; value: string | undefined } => {
    if (inputValue.length === 8) {
      const [year, month, day] = inputValue.split(':');
      const date = `${month}-${day}-${year}`;
      if (year && month && day && moment(date).isValid()) {
        return {
          selected: moment(date).toDate(),
          value: date,
        };
      }
    }
    return {
      selected: null,
      value: undefined,
    };
  }, [inputValue]);

  return (
    <div className={clsx('relative w-full', className)} ref={wrapperRef}>
      {label && <p className='text-base leading-5 mb-1 text-[#011844]'>{label}</p>}
      <div role='button' onClick={() => setIsOpenDatepicker(true)}>
        <Input
          placeholder={placeholder}
          icon={<Icon src='/images/icons/icon-calendar.svg' className='size-6 mr-4' />}
          wrapperInputClassName='h-[56px]'
          value={inputValue}
          onChange={handleInputChange}
          mask='99:99:99'
          maskChar={null}
        />
      </div>

      {isOpenDatepicker && (
        <div className='absolute top-full w-full left-0 z-50 modal_animation'>
          <Datepicker open {...rest} {...datePickerData} onChange={handleDatepickerChange} />
        </div>
      )}
    </div>
  );
};

export default DatepickerWithInput;
