import { useState, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { supabase } from '@/lib/supabase';
import { toast } from 'sonner';
import { IconPhotoPlus, IconX, IconLoader2 } from '@tabler/icons-react';

interface ImageUploadProps {
    value?: string;
    onChange: (url: string) => void;
    bucket?: string;
}

export function ImageUpload({
    value,
    onChange,
    bucket = 'avatars'
}: ImageUploadProps) {
    const [uploading, setUploading] = useState(false);
    const fileInputRef = useRef<HTMLInputElement>(null);

    const handleUpload = async (event: any) => {
        try {
            setUploading(true);
            const file = event.target.files?.[0];
            if (!file) return;

            // 1. 检查文件类型
            if (!file.type.startsWith('image/')) {
                toast.error('请选择图片文件');
                return;
            }

            // 2. 检查文件大小 (限制 2MB)
            if (file.size > 2 * 1024 * 1024) {
                toast.error('图片大小不能超过 2MB');
                return;
            }

            const fileExt = file.name.split('.').pop();
            const fileName = `${Math.random().toString(36).substring(2)}.${fileExt}`;
            const filePath = `${fileName}`;

            // 3. 上传到 Supabase Storage
            const { error: uploadError } = await supabase.storage
                .from(bucket)
                .upload(filePath, file);

            if (uploadError) {
                throw uploadError;
            }

            // 4. 获取公共 URL
            const { data: { publicUrl } } = supabase.storage
                .from(bucket)
                .getPublicUrl(filePath);

            onChange(publicUrl);
            toast.success('上传成功');
        } catch (error: any) {
            toast.error(`上传失败: ${error.message}`);
        } finally {
            setUploading(false);
            if (fileInputRef.current) {
                fileInputRef.current.value = '';
            }
        }
    };

    const removeImage = () => {
        onChange('');
    };

    return (
        <div className="space-y-4">
            <div className="flex items-center gap-4">
                {value ? (
                    <div className="relative group h-24 w-24 rounded-lg overflow-hidden border">
                        <img
                            src={value}
                            alt="Avatar"
                            className="h-full w-full object-cover"
                        />
                        <button
                            type="button"
                            onClick={removeImage}
                            className="absolute top-1 right-1 p-1 bg-red-500 rounded-full text-white opacity-0 group-hover:opacity-100 transition-opacity"
                        >
                            <IconX size={14} />
                        </button>
                    </div>
                ) : (
                    <div
                        onClick={() => fileInputRef.current?.click()}
                        className="h-24 w-24 rounded-lg border-2 border-dashed border-muted-foreground/25 flex flex-col items-center justify-center cursor-pointer hover:border-primary/50 transition-colors bg-muted/30"
                    >
                        {uploading ? (
                            <IconLoader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                        ) : (
                            <>
                                <IconPhotoPlus className="h-8 w-8 text-muted-foreground" />
                                <span className="text-[10px] text-muted-foreground mt-1">选择图片</span>
                            </>
                        )}
                    </div>
                )}

                <div className="flex-1 space-y-1">
                    <p className="text-xs text-muted-foreground">
                        推荐尺寸: 500x500px <br />
                        最大限制: 2MB
                    </p>
                    <input
                        type="file"
                        ref={fileInputRef}
                        onChange={handleUpload}
                        accept="image/*"
                        className="hidden"
                    />
                    {!value && (
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            disabled={uploading}
                            onClick={() => fileInputRef.current?.click()}
                        >
                            {uploading ? '上传中...' : '上传头像'}
                        </Button>
                    )}
                </div>
            </div>
        </div>
    );
}
