import { useShallow } from 'zustand/react/shallow';
import { useFileStore } from '../store';
import { useEffect, useMemo, useRef, useState } from 'react';
import path from 'path-browserify';
import prettyBytes from 'pretty-bytes';
import clsx from 'clsx';
import FileOutlined from '@ant-design/icons/FileOutlined';
import FolderOutlined from '@ant-design/icons/FolderOutlined';
import { IconButton } from '@kevisual/components/button/index.tsx';
import { render, unmount } from '@kevisual/resources/pages/Bootstrap.tsx';
import UploadOutlined from '@ant-design/icons/lib/icons/UploadOutlined';
import { Tooltip } from '@mui/material';
import { useResourceFileStore } from '@kevisual/resources/pages/store/resource-file.ts';
import { FileDrawerApp } from '@kevisual/resources/pages/file/draw/FileDrawer.tsx';
import { Delete, FolderPlus, RefreshCw, Trash, Upload } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { UploadButton } from '@kevisual/resources/pages/upload/index.tsx';
import { DialogDirectory, DialogDeleteDirectory } from '@kevisual/resources/pages/upload/DialogDirectory.tsx';
export const CardPath = ({ children }: any) => {
  const userAppStore = useFileStore(
    useShallow((state) => {
      return {
        list: state.list,
        getList: state.getList,
        setPath: state.setPath,
        path: state.path,
      };
    }),
  );
  const [dialogDirectory, setDialogDirectory] = useState(false);
  const [dialogDeleteDirectory, setDialogDeleteDirectory] = useState(false);
  const paths = ['root', ...userAppStore.path.split('/').filter((item) => item)];
  const onDirectoryClick = (prefix: string) => {
    if (prefix === 'root') {
      userAppStore.setPath('');
      userAppStore.getList();
      return;
    }
    userAppStore.setPath(prefix.replace('root/', '') + '/');
    userAppStore.getList();
  };
  const { t } = useTranslation();

  const [_username, appKey, version, ...directory] = paths;
  const onUloadFinish = (res: any) => {
    console.log(res);
    userAppStore.getList();
  };
  const directoryPath = directory.join('/');
  return (
    <div className='border border-gray-200 rounded h-full overflow-hidden'>
      <div className='p-2'>
        <div className='flex flex-col'>
          <div className='flex justify-between'>
            <div className='flex gap-2 py-2'>
              <div>Path: </div>
              <div className='flex'>
                {paths.map((item, index) => {
                  const isLast = index === paths.length - 1;
                  return (
                    <div
                      key={index}
                      className={clsx('select-none', !isLast && 'hover:text-gray-400 cursor-pointer')}
                      onClick={(e) => {
                        if (!isLast) {
                          onDirectoryClick(paths.slice(0, index + 1).join('/'));
                        }
                      }}>
                      {item}/
                    </div>
                  );
                })}
              </div>
            </div>
            <div className='flex gap-2'>
              <Tooltip title={t('refresh')} placement='bottom'>
                <IconButton
                  color='primary'
                  onClick={() => {
                    userAppStore.getList();
                  }}>
                  <RefreshCw />
                </IconButton>
              </Tooltip>
              {version && (
                <>
                  <Tooltip title={t('create_directory')} placement='bottom'>
                    <IconButton color='primary' onClick={() => setDialogDirectory(true)}>
                      <FolderPlus />
                    </IconButton>
                  </Tooltip>
                  <DialogDirectory
                    open={dialogDirectory}
                    onClose={() => setDialogDirectory(false)}
                    onSuccess={(newPrefix) => {
                      const currentPath = appKey + '/' + version + '/' + newPrefix;
                      onDirectoryClick(currentPath);
                      setDialogDirectory(false);
                    }}
                    prefix={directoryPath}
                    opts={{
                      appKey,
                      version,
                    }}
                  />
                </>
              )}
              {version && (
                <>
                  <Tooltip title={t('uploadDirectory')} placement='bottom'>
                    <IconButton color='primary'>
                      <UploadButton
                        onlyIcon
                        uploadDirectory
                        icon={<Upload />}
                        directory={directoryPath}
                        appKey={appKey}
                        version={version}
                        onUpload={onUloadFinish}
                      />
                    </IconButton>
                  </Tooltip>
                  <Tooltip title={t('upload')} placement='bottom'>
                    <IconButton color='primary'>
                      <UploadButton onlyIcon appKey={appKey} version={version} directory={directoryPath} onUpload={onUloadFinish} />
                    </IconButton>
                  </Tooltip>
                </>
              )}
              {version && directoryPath && (
                <>
                  <Tooltip title={t('deleteDirectory')} placement='bottom'>
                    <IconButton
                      color='primary'
                      onClick={() => {
                        setDialogDeleteDirectory(true);
                      }}>
                      <Trash />
                    </IconButton>
                  </Tooltip>
                  <DialogDeleteDirectory
                    open={dialogDeleteDirectory}
                    onClose={() => setDialogDeleteDirectory(false)}
                    onSuccess={(prefix) => {
                      const newPrefix = prefix.split('/').slice(0, -1).join('/');
                      setDialogDeleteDirectory(false);
                      onDirectoryClick(newPrefix);
                    }}
                    prefix={appKey + '/' + version + '/' + directoryPath}
                  />
                </>
              )}
            </div>
          </div>
        </div>
      </div>
      <div className='scrollbar' style={{ height: 'calc(100% - 20px)' }}>
        {children}
      </div>
    </div>
  );
};
export const List = () => {
  const [tab, setTab] = useState<'folder' | 'upload'>('folder');
  const uploadRef = useRef<HTMLDivElement>(null);
  const { setOpenDrawer, setPrefix, setResource, getStatFile, setOnce } = useResourceFileStore(
    useShallow((state) => {
      return {
        setOpenDrawer: state.setOpenDrawer,
        setPrefix: state.setPrefix,
        setResource: state.setResource,
        getStatFile: state.getStatFile,
        setOnce: state.setOnce,
      };
    }),
  );
  const userAppStore = useFileStore(
    useShallow((state) => {
      return {
        list: state.list,
        getList: state.getList,
        setPath: state.setPath,
        path: state.path,
        getFile: state.getFile,
        file: state.file,
      };
    }),
  );
  useEffect(() => {
    userAppStore.getList();
    return () => {
      setOnce(null);
    };
  }, []);
  const onDirectoryClick = (prefix: string) => {
    userAppStore.setPath(prefix);
    userAppStore.getList();
  };
  const allFolderApp = useMemo(() => {
    return (
      <>
        <CardPath>
          <div className='flex flex-col'>
            {userAppStore.list.map((item, index) => {
              if (item.prefix) {
                let showPrefix = item.prefix.replace(userAppStore.path, '');
                showPrefix = showPrefix.replace('/', '');
                return (
                  <div
                    className=' border-t border-gray-200 flex gap-2 p-2'
                    key={index}
                    onClick={() => {
                      onDirectoryClick(item.prefix);
                    }}>
                    <div>
                      <FolderOutlined />
                    </div>
                    <div>{showPrefix}</div>
                  </div>
                );
              }
              const name = path.basename(item.name);
              const size = prettyBytes(item.size);
              return (
                <div
                  className=' border-t border-gray-200 flex gap-2 p-2'
                  key={index}
                  onClick={() => {
                    setPrefix(item.name);
                    setResource(item);
                    getStatFile();
                    setOpenDrawer(true);
                    setOnce((data: any) => {
                      // console.log(data);
                      userAppStore.getList();
                    });
                    console.log(item);
                  }}>
                  <div>
                    <FileOutlined />
                  </div>
                  <div>{name}</div>
                  <div>size: {size}</div>
                </div>
              );
            })}
          </div>
        </CardPath>
        <FileDrawerApp />
      </>
    );
  }, [userAppStore.list, userAppStore.path]);

  useEffect(() => {
    if (tab === 'upload') {
      render(uploadRef.current!);
    } else {
      uploadRef.current && unmount(uploadRef.current!);
    }
    console.log('unmount', tab, uploadRef.current);
  }, [tab]);
  return (
    <div className='flex w-full h-full'>
      <div className='flex gap-2 border border-gray-200 shadow-md p-2'>
        <div className='flex flex-col gap-2'>
          <Tooltip title='所有的资源文件' placement='right'>
            <IconButton color={tab !== 'folder' ? 'primary' : 'secondary'} onClick={() => setTab('folder')}>
              <FolderOutlined />
            </IconButton>
          </Tooltip>
          <Tooltip title='上传资源文件管理' placement='right'>
            <IconButton color={tab !== 'upload' ? 'primary' : 'secondary'} onClick={() => setTab('upload')}>
              <UploadOutlined />
            </IconButton>
          </Tooltip>
        </div>
      </div>
      <div className='grow' style={{ height: 'calc(100% - 0px)', overflow: 'hidden' }}>
        {tab === 'folder' && <div className='p-4 w-full h-full'>{allFolderApp}</div>}
        {tab === 'upload' && <div className='w-full h-full' ref={uploadRef}></div>}
      </div>
    </div>
  );
};
