import React, { useCallback, useEffect, useState } from 'react';
import { Input, Button, message, Spin } from 'antd';
import styles from './ShareCodeValidator.module.css';
import { api } from '@nice/client';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import { env } from '@web/src/env';
import { copyToClipboard } from './sharecodegenerator';
import { ShareCodeResponse, useQuickFileContext } from '../quick-file/quickFileContext';
dayjs.extend(utc);
dayjs.extend(timezone);
export const ShareCodeValidator: React.FC = ({ }) => {
  const { saveCodeRecord,handleValidSuccess,isGetingFileId,downloadCode,setDownloadCode,refetchShareCodeWithResource,isLoading,downloadResult } = useQuickFileContext();
  
  const validateCode = useCallback(async () => {

    if (!downloadCode?.trim()) {
      message.warning('请输入正确的分享码');
      return;
    }
    try {
      const { data: latestResult } = await refetchShareCodeWithResource();
      console.log('验证分享码返回数据:', latestResult);
      saveCodeRecord(latestResult as any as ShareCodeResponse,'shareCodeDownloadRecords')
      handleValidSuccess(latestResult.resource.url, latestResult.fileName);
    } catch (error) {
      console.error('验证分享码失败:', error);
      message.error('分享码无效或已过期');
    }
  }, [refetchShareCodeWithResource, downloadCode, handleValidSuccess]);
  const getDownloadUrl = useCallback(async () => {
    try {
      const { data: latestResult } = await refetchShareCodeWithResource();
      console.log('验证分享码返回数据:', latestResult);
      const downloadUrl = `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${latestResult.resource.url}`;
      copyToClipboard(downloadUrl)
        .then(() => {
          message.success(`${latestResult.fileName}的下载链接已复制`, 6)
        })
        .catch(() => {
          message.error('复制失败')
        });
    } catch (error) {
      console.error('验证分享码失败:', error);
      message.error('分享码无效或已过期');
    }
  }, [refetchShareCodeWithResource, downloadCode, handleValidSuccess]);
  return (
    <>
      {
        isGetingFileId ?
          (<Spin spinning={isGetingFileId} fullscreen />) :
          (
            <>
              <div className={styles.container}>
                <Input
                  className={styles.input}
                  value={downloadCode}
                  onChange={(e) => setDownloadCode(e.target.value.toUpperCase())}
                  placeholder="请输入分享码"
                  maxLength={8}
                  onPressEnter={validateCode}
                />
                <Button
                  type="primary"
                  onClick={getDownloadUrl}
                  loading={isLoading}
                  disabled={!downloadCode?.trim()}
                >
                  获取下载链接
                </Button>
                <Button
                  type="primary"
                  onClick={validateCode}
                  loading={isLoading}
                  disabled={!downloadCode?.trim()}
                >
                  下载
                </Button>
              </div>
              {
                !isLoading && downloadResult && (
                  <div className='w-full flex justify-between my-2 p-1 antialiased text-secondary-600'>
                    <span >{`分享码：${downloadResult?.code ? downloadResult.code : ''}`}</span>
                    <span >{`文件名：${downloadResult?.fileName ? downloadResult.fileName : ''}`}</span>
                    <span >{`过期时间：${downloadResult?.expiresAt ? dayjs(downloadResult.expiresAt).format('YYYY-MM-DD HH:mm:ss') : ''}`}</span>
                    <span >{`剩余使用次数：${downloadResult?.canUseTimes ? downloadResult.canUseTimes : ''}`}</span>
                  </div>
                )
              }
            </>
          )
      }
    </>
  );
};