'use client';
import clsx from 'clsx';
import { FC, useCallback, useRef, useState } from 'react';
import { IOption } from '@/types/IOption';
import Icon from '@/components/Icon';
import { useClickOutside } from '@/hooks/useClickOutside';

interface ITimepickerProps {
  value: IOption['value'];
  label?: string;
  placeholder?: string;
  onChange?: (_value: IOption['value']) => void;
  className?: string;
  wrapperClassName?: string;

  to?: string;
  from?: string;
}

const hours = new Array(24).fill('');
const minutes = new Array(60).fill('');

export const Timepicker: FC<ITimepickerProps> = ({
  value,
  className,
  placeholder,
  label,
  onChange,
  wrapperClassName,
  to = '23:59',
  from = '-01:00',
}) => {
  const [isOpen, setIsOpen] = useState<boolean>(false);
  const wrapperRef = useRef<HTMLDivElement>(null);

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

  const handleSelect = useCallback(
    (type: 'hour' | 'minute', newvalue: number) => () => {
      const currValArr = value?.split(':') || [];

      if (type === 'hour') {
        currValArr[0] = newvalue.toString().padStart(2, '0');
      }

      if (type === 'minute') {
        currValArr[1] = newvalue.toString().padStart(2, '0');
      }

      if (!currValArr[0]) {
        currValArr[0] = '00';
      }

      if (!currValArr[1]) {
        currValArr[1] = '00';
      }

      onChange?.(currValArr.join(':'));
    },
    [onChange, value],
  );

  const isInOk = useCallback((val: string) => {
    const valNum = +val.replaceAll(':', '')


    const fromNum = +from.replaceAll(':', '')
    const toNum = +to.replaceAll(':', '')


    return valNum < toNum && valNum > fromNum;
  }, [from, to])




  return (
    <div className={clsx('w-full', wrapperClassName)}>
      {label && <p className='text-base leading-4 mb-1'>{label}</p>}
      <div className={clsx(className, 'relative w-full')} ref={wrapperRef}>
        <div
          role='button'
          onClick={() => setIsOpen((prev) => !prev)}
          className='w-full bg-white relative rounded-xl border-[1px] border-light_gray flex justify-between items-center h-[56px] pl-[26px] pr-[24px]'
        >
          <p className='text-[#AFAFAF] text-sm leading-4'>{!value ? placeholder : value}</p>
          <button type='button'>
            <Icon src='/images/icons/icon-clock.svg' className='w-6 h-6 text-primary' />
          </button>
        </div>
        <div
          className={clsx(
            'absolute top-full left-0 w-full bg-white z-10 mt-1 border-[1px] rounded-xl border-light_gray max-h-[200px] overflow-y-auto  flex',
            isOpen ? 'visible opacity-100' : 'invisible opacity-0',
          )}
        >
          <ul className='w-full'>
            {hours.map((_, index) => (
              <li
                key={index}
                role='button'
                className={clsx(
                  'border-b-[1px] border-light_gray last:border-b-0 whitespace-nowrap overflow-hidden line-clamp-1 p-2 transition-transform duration-300',
                  {
                    'bg-gray-200 pointer-events-none': !isInOk(`${index.toString().padStart(2, '0')}:${value?.split(":")[1] || '00'}`)
                  }
                )}
                onClick={handleSelect('hour', index)}
              >
                {index.toString().padStart(2, '0')}
              </li>
            ))}
          </ul>
          <ul className='w-full'>
            {minutes.map((_, index) => (
              <li
                key={index}
                role='button'
                className={clsx(
                  'border-b-[1px] border-light_gray last:border-b-0 whitespace-nowrap overflow-hidden line-clamp-1 p-2 transition-transform duration-300',
                  {
                    'bg-gray-200 pointer-events-none': !isInOk(`${value?.split(":")[0] || '00'}:${index.toString().padStart(2, '0')}`)
                  }
                )}
                onClick={handleSelect('minute', index)}
              >
                {index.toString().padStart(2, '0')}
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
};
