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

import { EyeOff } from 'lucide-react';

import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Lang } from '@/lang/Lang';

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

export const generatePassword = (length: number) => {
  var password = '';
  var characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var charactersLength = characters.length;

  for (var i = 0; i < length; i++) {
    password += characters.charAt(
      Math.floor(Math.random() * charactersLength)
    );
  }

  return password;
};
export const PasswordData = (props: ItemDataProps) => {



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

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








  const [passEditModal, setPassEditModal] = useState<boolean>(false);

  const onChangeInputPassword = (e: any) => {
    let val = e.target.value ?? null;

    setLocalValue(val);
  };


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

    return <div>
      <DataLabel {...props} />
      <Button variant="secondary" className='w-full flex items-center justify-between'>
        <EyeOff className='text-gray-300 text-base ' />
      </Button>
      <DataDescription {...props} />
    </div>




  }



  return (
    <React.Fragment>
      <DataLabel {...props} />
      <Button

        onClick={() => setPassEditModal(true)}>
        {Lang.key('set_password')}
      </Button>
      {localValue && (
        <Badge
          onClick={() => {
            setLocalValue(null);
          }}

          className="ml-4"

        >
          {Lang.key('new_password')}: {localValue}
        </Badge>
      )}
      <DataDescription {...props} />

      <Dialog
        open={passEditModal}

        onOpenChange={() => setPassEditModal(false)}
      >


        <DialogContent>
          <DialogTitle>{Lang.key('set_password')}</DialogTitle>
          <Input
            className='w-full'
            value={localValue}
            onChange={onChangeInputPassword}
          />

          <Button

            variant="outline"
            style={{ marginTop: 15, width: '100%' }}
            onClick={() => setLocalValue(generatePassword(16))}
          >
            {Lang.key('generate_random_password')}
          </Button>

          <Button
            style={{ marginTop: 15, width: '100%' }}
            onClick={() => setPassEditModal(false)}
          >
            {Lang.key('close')}
          </Button>
        </DialogContent>
      </Dialog>
    </React.Fragment>
  );
}
