import React, { useState, useEffect } from 'react';
import { Upload } from 'antd';
import clasnames from 'classnames';
import { FileOutlined, DeleteFilled } from '@easyv/react-icons';
import { FileTypeEnum, FileInfo } from '@easytwin/core';
import DefaultProviewImg from '@/assets/img/default_preview.png';
import EmptyFileImg from '@/assets/img/empty_file.png';
import { ProButton, ProButtonProp } from '@/components';
import { FileApi } from '@/server';

type DefaultPreviewImgModeType = 'emptyFile' | 'emptyPreview';
type ChangedValueType = 'info' | 'string';

const DefaultPreviewImgs: Record<DefaultPreviewImgModeType, string> = {
  emptyFile: EmptyFileImg,
  emptyPreview: DefaultProviewImg,
};

export interface FileCardProp {
  value?: string | null;
  className?: string;
  innerContextClassName?: string;
  mode?: FileTypeEnum;
  uploadAccept?: string;
  hoverContent?: React.ReactNode;
  uploadBtnProType?: ProButtonProp['proType'];
  hoverContentExtra?: React.ReactNode;
  defaultPreviewImgMode?: DefaultPreviewImgModeType;
  backgroundSize?: string;
  changedValueType?: ChangedValueType;
  showDeleteBtn?: boolean;
  onChange?: (info: FileInfo | string) => void;
  onRemove?: (info: FileInfo | string) => void;
}

const FileCard: React.FC<FileCardProp> = function ({
  value: _url = '',
  className,
  innerContextClassName,
  mode = FileTypeEnum.IMAGE,
  uploadAccept = 'image/*',
  hoverContent,
  uploadBtnProType,
  hoverContentExtra,
  defaultPreviewImgMode = 'emptyFile',
  backgroundSize = 'contain',
  changedValueType = 'string',
  showDeleteBtn = true,
  onChange,
  onRemove,
}) {
  const [url, setUrl] = useState<string>('');

  useEffect(() => {
    setUrl(_url || '');
  }, [_url]);

  const handleCreateFileInfo = React.useCallback(
    async (file: File) => {
      console.log(file);
      const url = await FileApi.upload(`/${mode}/${file.name}`, file);
      setUrl(url);
      onChange?.(url);
      return false;
    },
    [changedValueType, onChange],
  );

  const innerRender = (url: string) => {
    switch (mode) {
      case FileTypeEnum.IMAGE:
        return (
          <div className={clasnames('w-full h-full', innerContextClassName)}>
            <div
              className="w-full h-full"
              style={{
                backgroundImage: `url("${import.meta.env.VITE_ASSETS_URL}${url}")`,
                backgroundSize,
                backgroundRepeat: 'no-repeat',
                backgroundPosition: 'center',
              }}
            />
          </div>
        );
      default:
        return (
          <div className="h-full flex flex-col gap-y-2 justify-center items-center">
            <FileOutlined className="text-22 anticon" />
            <span className="w-full text-xs text-white px-4 truncate">{url}</span>
          </div>
        );
    }
  };

  return (
    <div
      className={clasnames(
        'w-full h-30 bg-bgColorLayout border border-borderColorBase rounded group',
        className,
      )}>
      {url ? (
        innerRender(url)
      ) : (
        <div
          className="w-full h-full"
          style={{
            backgroundImage: `url("${DefaultPreviewImgs[defaultPreviewImgMode]}")`,
            backgroundSize: 'contain',
            backgroundRepeat: 'no-repeat',
            backgroundPosition: 'center',
          }}
        />
      )}
      <div className="w-full h-full absolute top-0 hidden group-hover:block bg-[rgba(0,0,0,0.5)]">
        {hoverContent || (
          <>
            {/*  */}
            <div className="w-full h-full border border-primary rounded flex flex-col justify-center items-center gap-y-2">
              {/*  */}
              <Upload
                accept={uploadAccept}
                showUploadList={false}
                beforeUpload={handleCreateFileInfo}>
                <ProButton
                  block
                  size="small"
                  type="primary"
                  proType={uploadBtnProType}
                  className="!w-20">
                  {url ? '更新' : '上传'}
                </ProButton>
              </Upload>

              {/*  */}
              {hoverContentExtra}
            </div>
            {/*  */}
            <div className="absolute top-0 right-0 p-2">
              {url && showDeleteBtn && (
                <DeleteFilled
                  className="anticon p-1 cursor-pointer"
                  onClick={() => onRemove?.(url)}
                />
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default FileCard;
