'use client'
import { useCallback, useState } from 'react'
import { RiCloseLine, RiUploadCloud2Line } from '@remixicon/react'
import s from './index.module.css'
import cn from '@/utils/classnames'
import Modal from '@/app/components/base/modal'
import Button from '@/app/components/base/button'
import 'react-multi-email/dist/style.css'
import FileInput from '@/app/components/base/file-uploader/file-input'
import { FileContextProvider, useStore } from '@/app/components/base/file-uploader/store'
import { useFile } from '@/app/components/base/file-uploader/hooks'
import useSWR from 'swr'
import { addMouldFile, delMouldFile, fetchMoulds } from '@/service/common'
import { useDebounceFn } from 'ahooks'
import Confirm from '@/app/components/base/confirm'
import { downloadFile } from '@/app/components/base/file-uploader/utils'

const DetailModel = ({
  datasetId,
  transfer,
  onCancel,
}: any) => {
  const [showConfirmDelete, setShowConfirmDelete] = useState(false)
  const [delId, setDelId] = useState('')
  const [delFileName, setDelFileName] = useState('')

  const fileConfig: any = {
    image: {
      detail: 'high',
      enabled: true,
      number_limits: 3,
      transfer_methods: [
        'local_file',
        'remote_url',
      ],
    },
    enabled: true,
    allowed_file_types: [
      'custom',
    ],
    allowed_file_extensions: [
      '.doc',
      '.docx',
      '.xls',
      '.xlsx',
      '.ppt',
      '.pptx',
      '.pdf',
      '.csv',
    ],
    allowed_file_upload_methods: [
      'local_file',
    ],
    number_limits: 6,
    fileUploadConfig: {
      file_size_limit: 15,
      batch_count_limit: 5,
      image_file_size_limit: 10,
      video_file_size_limit: 100,
      audio_file_size_limit: 50,
      workflow_file_upload_limit: 10,
    },
  }
  const files = useStore(s => s.files)
  const {
    handleRemoveFile,
    handleReUploadFile,
  } = useFile(fileConfig)
  const { data, mutate }: any = useSWR(
    {
      url: '/workspaces/123123',
      params: {},
    },
    fetchMoulds,
  )
  const fileList = data?.data || []
  const handleAdd = useCallback(async () => {
    try {
      const { result }: any = await addMouldFile({
        url: '/workspaces/123123',
        body: { id: files[0].id, fileName: files[0].name },
      })
      handleRemoveFile(files[0].id)
      if (result === 'success')
        mutate()
    }
    catch (e) { }
  }, [files, handleRemoveFile])
  const { run: getFiles } = useDebounceFn(() => {
    if (files.length > 0) {
      console.log(5555)
      console.log(files)
      handleAdd()
    }
  }, { wait: 500 })
  getFiles()
  const handleDel = useCallback(async () => {
    try {
      const { result }: any = await delMouldFile({
        url: '/workspaces/123123',
        body: { id: delId },
      })
      if (result === 'success')
        mutate()
    }
    catch (e) { }
  }, [delId])
  return (
    <>
      <div className={cn(s.wrap)}>
        <Modal overflowVisible isShow onClose={() => { }} className={cn(s.modal)}>
          <div className='mb-2 flex justify-between'>
            <div className='text-xl font-semibold text-text-primary'>模板{transfer.mode === 'manage' ? '管理' : '下载'}</div>
            <RiCloseLine className='h-4 w-4 cursor-pointer text-text-tertiary' onClick={onCancel} />
          </div>
          <div>
            {
              transfer.mode === 'manage' && (
                <div className="flex w-full">
                  <Button
                    className='relative w-[80px]'
                    variant='secondary-accent'
                  >
                    <RiUploadCloud2Line className='mr-1 h-4 w-4' />
                    新增
                    <FileInput fileConfig={fileConfig} />
                  </Button>
                  <div className="flex grow items-center justify-center text-sm text-[#666666]">共{fileList.length}个模板</div>
                </div>
              )
            }
          </div>
          <div className="mt-2.5 flex max-h-[400px] w-full flex-col gap-2.5 overflow-y-auto">
            {
              fileList.map((file: any) => (
                <div key={file.id} className='flex w-full items-center rounded border border-[#E0E3E8] bg-[#F3F4F8] px-4 py-3'>
                  <div>
                    {
                      (file.fileName.includes('.xls') || file.fileName.includes('.xlsx')) && (
                        <img src="/imgs/excel.png"/>
                      )
                    }
                    {
                      (file.fileName.includes('.doc') || file.fileName.includes('.docx')) && (
                        <img src="/imgs/word.png"/>
                      )
                    }
                    {
                      (file.fileName.includes('.ppt') || file.fileName.includes('.pptx')) && (
                        <img src="/imgs/ppt.png"/>
                      )
                    }
                  </div>
                  <div className="ml-2">{file.fileName}</div>
                  <div className="cursor ml-auto" onClick={(e) => {
                    e.stopPropagation()
                    downloadFile(`/files/${file.id}/file-preview?timestamp=${new Date().getTime()}` || '', file.fileName)
                  }}>
                    <img src="/imgs/download.png"/>
                  </div>
                  {
                    transfer.mode === 'manage' && (
                      <div className="cursor ml-5" onClick={() => {
                        setDelId(file.id)
                        setShowConfirmDelete(true)
                      }}>
                        <img src="/imgs/del.png"/>
                      </div>
                    )
                  }
                </div>
              ))
            }
          </div>
        </Modal>
      </div>
      {showConfirmDelete && (
        <Confirm
          title="删除确认"
          content={`请确认是否删除${delFileName}？`}
          isShow={showConfirmDelete}
          onConfirm={handleDel}
          onCancel={() => setShowConfirmDelete(false)}
        />
      )}
    </>
  )
}

const DetailModelWrapper = (props: any) => {
  return (
    <FileContextProvider>
      <DetailModel {...props} />
    </FileContextProvider>
  )
}

export default DetailModelWrapper
