import React, { useCallback, useEffect, useState } from 'react';
import { Input, Button, message } from 'antd';
import styles from './ShareCodeValidator.module.css';
import { api } from '@nice/client';
import dayjs from 'dayjs';
interface ShareCodeValidatorProps {
  onValidSuccess: (fileId: string, fileName: string) => void;
}
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);
export const ShareCodeValidator: React.FC<ShareCodeValidatorProps> = ({
  onValidSuccess,
}) => {
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const { data: result, isLoading,refetch } = api.shareCode.getFileByShareCode.useQuery(
    { code: code.trim() },
    {
      enabled: false
    }
  )
  const validateCode = useCallback(async () => {

    if (!code.trim()) {
      message.warning('请输入正确的分享码');
      return;
    }
    setLoading(true);
    try {
      const { data: latestResult } = await refetch();
      console.log('验证分享码返回数据:', latestResult);
      onValidSuccess(latestResult.url, latestResult.fileName);
    } catch (error) {
      console.error('验证分享码失败:', error);
      message.error('分享码无效或已过期');
    } finally {
      setLoading(false);
    }
  }, [refetch, code, onValidSuccess]);

  return (
    <>
      <div className={styles.container}>
        <Input
          className={styles.input}
          value={code}
          onChange={(e) => setCode(e.target.value.toUpperCase())}
          placeholder="请输入分享码"
          maxLength={8}
          onPressEnter={validateCode}
        />
        <Button
          type="primary"
          onClick={validateCode}
          loading={loading}
          disabled={!code.trim()}
        >
          下载
        </Button>
      </div>
      {
        !loading && result && (
          <div className='w-full flex justify-between my-2 p-1 antialiased text-secondary-600'>
            <span >{`分享码：${result?.code ? result.code : ''}`}</span>
            <span >{`文件名：${result?.fileName ? result.fileName : ''}`}</span>
            <span >{`过期时间：${result?.expiresAt ? dayjs(result.expiresAt).format('YYYY-MM-DD HH:mm:ss') : ''}`}</span>
            <span >{`剩余使用次数：${result?.canUseTimes ? result.canUseTimes : ''}`}</span>
          </div>
        )
      }
    </>
  );
};