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

import { Copy } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
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 TextData = (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
        onClick={() => {
          if (localValue) {
            copyTextToClipboard(localValue);
          }
        }}
        variant="secondary" className='w-full flex items-center justify-between truncate'>
        {!!localValue ? localValue : Lang.key('no_data_short')}  <Copy />
      </Button>
      <DataDescription {...props} />
    </div>



  }




  if (props.structure.type == "text") {
    return (<>

      <DataLabel {...props} />
      <Textarea
        placeholder={titlePlaceholder}
        className="w-full"
        value={localValue}
        onChange={(e) => {
          setLocalValue(e.target.value);
        }}

      //  autoSize={{ minRows: 3, maxRows: 6 }}
      />
      <DataDescription {...props} />

    </>
    );
  }


  if (props.structure.type == "login") {

    return <>
      <DataLabel {...props} />
      <Input
        value={localValue}
        placeholder={titlePlaceholder}
        onChange={(e) => {

          //Оставляем только латинские буквы, цифры и символы _ и - 
          const sanitizedValue = e.target.value.replace(/[^a-zA-Z0-9_-]/g, '');
          setLocalValue(sanitizedValue);


        }}

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


  return (
    <>
      <DataLabel {...props} />
      <Input
        placeholder={titlePlaceholder}
        value={localValue}
        onChange={(e) => {
          setLocalValue(e.target.value);
        }}

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


