import {
  useEffect,
  useState,
} from 'react';

import _ from 'lodash';
import { CopyIcon } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { Lang, useLang } from '@/lang/Lang';
import { useLLText } from '@/lang/localizationService';
import { copyTextToClipboard } from '@/utils/helpers';

import DataDescription from './components/DataDescription';
import DataLabel from './components/DataLabel';
import { ItemDataProps } from './types';

export const NumberData = (props: ItemDataProps) => {

  const lang = useLang();
  const titlePlaceholder = useLLText(props.structure.title ?? '', lang);

  const [localValue, setLocalValue] = useState(props.getValue());

  useEffect(() => {
    props.setValue(localValue);
  }, [localValue]);


  if (props.onlyShow || !props.structure.editable) {


    return <div>

      <DataLabel {...props} />
      <Button variant="secondary" className='w-full flex items-center justify-between' onClick={() => {

        if (localValue) {

          copyTextToClipboard(localValue);
        }

      }}>
        {!!localValue ? localValue : ' - '}
        <CopyIcon />
      </Button>
      <DataDescription {...props} />

    </div>





  }




  return (
    <>
      <Tooltip>

        <TooltipTrigger asChild>
          <DataLabel {...props} />
        </TooltipTrigger>
        <TooltipContent >
          {props.structure.type == "float" ? Lang.key("enabled_float_number") : Lang.key("only_int_number")}
        </TooltipContent>
      </Tooltip>

      <Input

        placeholder={titlePlaceholder}
        min={props.structure.min ?? undefined}
        max={props.structure.max ?? undefined}
        className='w-full'
        value={localValue}
        onChange={(e) => {

          let value = e.target.value;
          // precision={props.structure.type == "float" ? undefined : 0}
          if (props.structure.type == "float") {

            //если есть запятая, то заменяем ее на точку
            if (value.includes(',')) {
              value = value.replace(',', '.');
            }

            value = value.replace(/[^0-9.]/g, '');
          } else {
            value = value.replace(/[^0-9.,-]/g, '');

          }

          setLocalValue(value);
        }}

      />
      <DataDescription {...props} />

    </>
  );
};


