import { useResourceFileStore } from '@kevisual/resources/pages/store/resource-file';
import { FormControlLabel, Box, ButtonGroup, Tooltip, Typography } from '@mui/material';
import { IconButton } from '@kevisual/components/button/index.tsx';
import { Info, Plus, Save, Share, Shuffle, Trash } from 'lucide-react';
import { useState, useEffect } from 'react';
import { toast } from 'react-toastify';
import { create } from 'zustand';
import { uniq } from 'lodash-es';
import { DatePicker } from './DatePicker';
import { DialogKey } from './DialogKey';
import { keysTips, KeyParse } from '../../modules/key-parse';
import { KeyShareSelect, KeyTextField } from '../../modules/PermissionManager';
import { TagsInput } from '@kevisual/components/select/TagsInput.tsx';
export const setShareKeysOperate = (value: 'public' | 'protected' | 'private') => {
  const keys = ['password', 'usernames', 'expiration-time'];
  const deleteKeys = keys.map((item) => {
    return {
      key: item,
      operate: 'delete',
    };
  });
  if (value === 'protected') {
    return deleteKeys.map((item) => {
      return {
        ...item,
        operate: 'add',
      };
    });
  }
  return deleteKeys;
};

export const useMetaOperate = ({
  onSave,
  metaStore,
  handleFormDataChange,
}: {
  onSave: () => void;
  metaStore: MetaStore;
  handleFormDataChange: (key: string, value: string | Date | null | string[]) => void;
}) => {
  const { keys, setKeys, openPropertyModal, setOpenPropertyModal } = metaStore;
  const hasShare = keys.includes('share');
  const hasPassword = keys.includes('password');
  const addMeta = (key: string) => {
    setKeys(uniq([...keys, key]));
  };
  const defaultBtnList = [
    {
      icon: <Save />,
      key: 'save',
      tooltip: '保存元数据, 修改后需要手动保存',
      onClick: () => onSave(),
    },
    {
      icon: <Plus />,
      key: 'add',
      tooltip: '添加元数据',
      onClick: () => setOpenPropertyModal(true),
    },
  ];
  if (!hasShare) {
    defaultBtnList.push({
      icon: <Share />,
      key: 'share',
      tooltip: '开启共享',
      onClick: () => addMeta('share'),
    });
  }
  if (hasShare && hasPassword) {
    defaultBtnList.push({
      icon: <Shuffle />,
      key: 'password',
      tooltip: '随机生成密码',
      onClick: () => {
        const password = Math.random().toString(36).substring(2, 8);
        handleFormDataChange('password', password);
      },
    });
  }
  return defaultBtnList;
};
type MetaStore = {
  keys: string[];
  setKeys: (keys: string[]) => void;
  openPropertyModal: boolean;
  setOpenPropertyModal: (openPropertyModal: boolean) => void;
};
export const useMetaStore = create<MetaStore>((set) => ({
  keys: [],
  setKeys: (keys) => set({ keys }),
  openPropertyModal: false,
  setOpenPropertyModal: (openPropertyModal) => set({ openPropertyModal }),
}));
export const MetaForm = () => {
  const { resource, updateMeta } = useResourceFileStore();
  const [formData, setFormData] = useState<any>({});
  const metaStore = useMetaStore();
  const { keys, setKeys } = metaStore;
  useEffect(() => {
    // setFormData(resource?.metaData || {});
    setFormData(KeyParse.parse(resource?.metaData || {}));
  }, [resource]);
  useEffect(() => {
    setKeys(Object.keys(resource?.metaData || {}));
  }, [resource]);
  if (!keys.length) {
    return <div className='text-center text-gray-500'>没有元数据</div>;
  }

  const handleFormDataChange = (key: string, value: string | Date | null | string[]) => {
    // setFormData({ ...formData, [key]: value });
    const _formData = { ...formData };
    if (key === 'share') {
      const shareKeysOperate = setShareKeysOperate(value as 'public' | 'protected' | 'private');
      shareKeysOperate.forEach((item) => {
        if (item.operate === 'add') {
          _formData[item.key] = '';
        } else if (item.operate === 'delete') {
          delete _formData[item.key];
        }
      });
      _formData.share = value;
      setFormData(_formData);
      const newKeys = keys
        .map((item) => {
          const operate = shareKeysOperate.find((item2) => item2.key === item);
          if (operate && operate.operate === 'delete') {
            return null;
          }
          return item;
        })
        .filter((item) => item !== null);
      const addKeys = shareKeysOperate.filter((item) => item.operate === 'add').map((item) => item.key);
      const _newKeys = uniq([...newKeys, ...addKeys]);
      setKeys(_newKeys);
      console.log(_newKeys);
      return;
    } else {
      _formData[key] = value;
    }
    setFormData({ ..._formData });
  };
  const deleteMeta = (key: string) => {
    setKeys(keys.filter((item) => item !== key));
    delete formData[key];
    setFormData({ ...formData });
  };
  const onSave = () => {
    const newMetadata = KeyParse.stringify(formData);
    updateMeta(newMetadata);
  };
  const addMetaKey = (key: string) => {
    if (keys.includes(key)) {
      toast.error('元数据key已存在');
      return;
    }
    formData[key] = '';
    setKeys([...keys, key]);
    setFormData({ ...formData });
  };
  const btnList = useMetaOperate({ onSave, metaStore, handleFormDataChange });

  return (
    <div className='relative w-full h-full'>
      <Box className='sticky top-0 z-10  pointer-events-none'>
        <div className='flex justify-end mr-20'>
          <div className=' pointer-events-auto '>
            <ButtonGroup
              variant='contained'
              sx={{
                mt: 1,
                backgroundColor: 'primary.main',
              }}>
              {btnList.map((item) => {
                const icon = <IconButton onClick={item.onClick}>{item.icon}</IconButton>;
                if (item.tooltip) {
                  return (
                    <Tooltip key={item.key} title={item.tooltip} placement='top' arrow>
                      {icon}
                    </Tooltip>
                  );
                }
                return <>{icon}</>;
              })}
            </ButtonGroup>
          </div>
        </div>
      </Box>
      <form className='flex flex-col gap-1 pb-4'>
        {keys.map((key) => {
          let control: React.ReactNode | null = null;
          if (key === 'share') {
            control = <KeyShareSelect name={key} value={formData[key] || ''} onChange={(value) => handleFormDataChange(key, value)} />;
          } else if (key === 'expiration-time') {
            control = <DatePicker value={formData[key]} onChange={(date) => handleFormDataChange(key, date)} />;
          } else if (key === 'usernames') {
            control = <TagsInput value={formData[key] || []} showLabel={false} onChange={(value) => handleFormDataChange(key, value)} />;
          } else {
            control = <KeyTextField name={key} value={formData[key] || ''} onChange={(value) => handleFormDataChange(key, value)} />;
          }
          const Label = () => {
            const tip = keysTips.find((item) => item.key === key);
            return (
              <div className='flex justify-between items-center gap-2'>
                <div className='flex items-center gap-2'>
                  <Typography variant='caption' color='primary'>
                    {key}
                  </Typography>
                  {tip && (
                    <Tooltip title={tip?.tips} placement='top' arrow>
                      <Info size={12} />
                    </Tooltip>
                  )}
                </div>
                <IconButton
                  variant='text'
                  sx={{
                    color: 'primay.main',
                  }}
                  color='error'
                  size='small'
                  onClick={() => deleteMeta(key)}>
                  <Trash />
                </IconButton>
              </div>
            );
          };
          return <FormControlLabel key={key} labelPlacement={'top'} label={<Label />} control={control} />;
        })}
      </form>
      <DialogKey onAdd={addMetaKey} />
    </div>
  );
};
