import React, { useState } from 'react';
import { useTusUpload } from '../hooks/useTusUpload';

export function SimpleUploadExample() {
	const { uploadProgress, isUploading, uploadError, handleFileUpload, getFileUrlByFileId } = useTusUpload();
	const [uploadedFileUrl, setUploadedFileUrl] = useState<string>('');

	const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
		const file = e.target.files?.[0];
		if (!file) return;

		try {
			const result = await handleFileUpload(
				file,
				(result) => {
					console.log('上传成功！', result);
					setUploadedFileUrl(result.url);
				},
				(error) => {
					console.error('上传失败：', error);
				},
			);
		} catch (error) {
			console.error('上传出错：', error);
		}
	};

	return (
		<div className="p-6 max-w-md mx-auto bg-white rounded-lg shadow-md">
			<h3 className="text-lg font-semibold mb-4">简单上传示例</h3>

			<div className="mb-4">
				<input
					type="file"
					onChange={handleFileChange}
					disabled={isUploading}
					className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
				/>
			</div>

			{isUploading && (
				<div className="mb-4">
					<div className="flex justify-between mb-1">
						<span className="text-sm font-medium text-blue-700">上传进度</span>
						<span className="text-sm font-medium text-blue-700">{uploadProgress}%</span>
					</div>
					<div className="w-full bg-gray-200 rounded-full h-2">
						<div
							className="bg-blue-600 h-2 rounded-full transition-all duration-300"
							style={{ width: `${uploadProgress}%` }}
						></div>
					</div>
				</div>
			)}

			{uploadError && (
				<div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">{uploadError}</div>
			)}

			{uploadedFileUrl && (
				<div className="mb-4 p-3 bg-green-100 border border-green-400 text-green-700 rounded">
					<p className="text-sm font-medium mb-2">上传成功！</p>
					<a
						href={uploadedFileUrl}
						target="_blank"
						rel="noopener noreferrer"
						className="text-blue-600 hover:text-blue-800 underline text-sm"
					>
						查看文件
					</a>
				</div>
			)}
		</div>
	);
}
