import { useEffect, useState } from 'react';
import { KeyParse, getTips } from './key-parse';
import { FormControlLabel, TextField, Select, MenuItem, Tooltip } from '@mui/material';
import { DatePicker } from '../draw/modules/DatePicker';
import { TagsInput } from '@kevisual/components/select/TagsInput.tsx';
import { HelpCircle } from 'lucide-react';
import clsx from 'clsx';
import { useTranslation } from 'react-i18next';
export const KeyShareSelect = ({ name, value, onChange }: { name: string; value: string; onChange?: (value: string) => void }) => {
  const { t } = useTranslation();
  return (
    <Select
      variant='outlined'
      size='small'
      name={name}
      value={value || ''}
      onChange={(e) => onChange?.(e.target.value)}
      sx={{
        width: '100%',
        marginBottom: '16px',
      }}>
      <MenuItem value='public' title={t('Public')}>
        {t('Public')}
      </MenuItem>
      <MenuItem value='protected' title={t('Protected')}>
        {t('Protected')}
      </MenuItem>
      <MenuItem value='private' title={t('Private')}>
        {t('Private')}
      </MenuItem>
    </Select>
  );
};
export const KeyTextField = ({ name, value, onChange }: { name: string; value: string; onChange?: (value: string) => void }) => {
  return (
    <TextField
      variant='outlined'
      size='small'
      name={name}
      value={value}
      onChange={(e) => onChange?.(e.target.value)}
      sx={{
        width: '100%',
        marginBottom: '16px',
      }}
    />
  );
};

type PermissionManagerProps = {
  value: Record<string, any>;
  onChange: (value: Record<string, any>) => void;
  className?: string;
};
export const PermissionManager = ({ value, onChange, className }: PermissionManagerProps) => {
  const { t, i18n } = useTranslation();
  const [formData, setFormData] = useState<any>(value);
  const [keys, setKeys] = useState<any>([]);
  useEffect(() => {
    const hasShare = value?.share && value?.share === 'protected';
    setFormData(KeyParse.parse(value || {}));
    if (hasShare) {
      setKeys(['password', 'usernames', 'expiration-time']);
    } else {
      setKeys([]);
    }
  }, [value]);
  const onChangeValue = (key: string, newValue: any) => {
    // setFormData({ ...formData, [key]: newValue });
    let newFormData = { ...formData, [key]: newValue };
    if (key === 'share') {
      if (newValue === 'protected') {
        newFormData = { ...newFormData, password: '', usernames: [], 'expiration-time': null };
        onChange(KeyParse.stringify(newFormData));
        setKeys(['password', 'usernames', 'expiration-time']);
      } else {
        delete newFormData.password;
        delete newFormData.usernames;
        delete newFormData['expiration-time'];
        onChange(KeyParse.stringify(newFormData));
        setKeys([]);
      }
    } else {
      onChange(KeyParse.stringify(newFormData));
    }
  };
  const tips = getTips('share', i18n.language);
  return (
    <form className={clsx('flex flex-col w-full gap-2', className)}>
      <FormControlLabel
        labelPlacement='top'
        control={<KeyShareSelect name='share' value={formData?.share} onChange={(value) => onChangeValue('share', value)} />}
        label={
          <div className='flex items-center gap-1'>
            {t('Share')}
            <Tooltip title={tips}>
              <HelpCircle size={16} />
            </Tooltip>
          </div>
        }
      />
      {keys.map((item: any) => {
        let control: React.ReactNode | null = null;
        const tips = getTips(item);

        const label = (
          <div className='flex items-center gap-1'>
            {t(item)}
            {tips && (
              <Tooltip title={tips}>
                <HelpCircle size={16} />
              </Tooltip>
            )}
          </div>
        );
        if (item === 'expiration-time') {
          control = <DatePicker className='mt-1' value={formData[item] || ''} onChange={(date) => onChangeValue(item, date)} />;
        } else if (item === 'usernames') {
          control = <TagsInput value={formData[item] || []} onChange={(value) => onChangeValue(item, value)} />;
        } else {
          control = <KeyTextField name={item} value={formData[item] || ''} onChange={(value) => onChangeValue(item, value)} />;
        }
        return <FormControlLabel key={item} labelPlacement='top' control={control} label={label} />;
      })}
    </form>
  );
};
