'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, downloadMouldFile, fetchMoulds } from '@/service/common'
import { useDebounceFn } from 'ahooks'
import Confirm from '@/app/components/base/confirm'

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,
    },
    noUpload: true,
  }
  const files = useStore(s => s.files)
  const {
    handleRemoveFile,
    handleReUploadFile,
  } = useFile(fileConfig)
  const { data, mutate }: any = useSWR(
    {
      url: `/datasets/${datasetId}/templates`,
      params: {
        page: 1,
        limit: 1000,
      },
    },
    fetchMoulds,
  )
  const fileList = data?.data || []
  const handleAdd = useCallback(async () => {
    try {
      const formData: any = new FormData()
      formData.set('file', files[0].originalFile)
      await addMouldFile({
        url: `/datasets/${datasetId}/templates`,
        body: formData,
      })
      handleRemoveFile(files[0].id)
      mutate()
    }
    catch (e) { }
  }, [files, handleRemoveFile])
  const { run: getFiles } = useDebounceFn(() => {
    if (files.length > 0)
      handleAdd()
  }, { wait: 500 })
  getFiles()
  const handleDel = useCallback(async () => {
    try {
      await delMouldFile({
        url: `/datasets/template/${delId}`,
      })
      setShowConfirmDelete(false)
      mutate()
    }
    catch (e) { }
  }, [delId])
  const handleDownload = async (file) => {
    await downloadMouldFile({
      url: `/datasets/template/${file.id}`,
      fileName: file.name,
    })
  }
  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.name.includes('.xls') || file.name.includes('.xlsx')) && (
                        <img src="/imgs/excel.png"/>
                      )
                    }
                    {
                      (file.name.includes('.doc') || file.name.includes('.docx')) && (
                        <img src="/imgs/word.png"/>
                      )
                    }
                    {
                      (file.name.includes('.ppt') || file.name.includes('.pptx')) && (
                        <img src="/imgs/ppt.png"/>
                      )
                    }
                    {
                      (file.name.includes('.pdf')) && (
                        <img src="/imgs/pdf.png"/>
                      )
                    }
                    {
                      (file.name.includes('.csv')) && (
                        <img src="/imgs/csv.png"/>
                      )
                    }
                  </div>
                  <div className="ml-2 text-sm">{file.name}</div>
                  <div className="ml-auto cursor-pointer" onClick={(e) => {
                    e.stopPropagation()
                    handleDownload(file)
                  }}>
                    <img src="/imgs/download.png"/>
                  </div>
                  {
                    transfer.mode === 'manage' && (
                      <div className="ml-5 cursor-pointer" onClick={() => {
                        setDelId(file.id)
                        setDelFileName(file.name)
                        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
