import React, { useEffect, useState, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Check, Loader2, AlertCircle } from 'lucide-react';
import { cn } from '@/utils';

interface SaveFeedbackProps {
    isSaving: boolean;
    lastSavedAt?: number;
    error: string | null;
    trigger?: boolean;
    onComplete?: () => void;
}

export function SaveFeedback({ isSaving, lastSavedAt, error, trigger = true, onComplete }: SaveFeedbackProps) {
    const [isVisible, setIsVisible] = useState(false);
    const [message, setMessage] = useState('');
    const [type, setType] = useState<'success' | 'error' | 'saving'>('success');
    const prevSavedAt = useRef(lastSavedAt);
    const onCompleteRef = useRef(onComplete);

    // Update ref when onComplete changes
    useEffect(() => {
        onCompleteRef.current = onComplete;
    }, [onComplete]);

    useEffect(() => {
        let timer: NodeJS.Timeout;

        if (isSaving) {
            // Only start showing if triggered (manual save)
            if (trigger) {
                setIsVisible(true);
                setType('saving');
                setMessage('保存中...');
            }
        } else if (error) {
            // Only show error if we were already showing feedback
            if (isVisible) {
                setType('error');
                setMessage('保存失败');
                timer = setTimeout(() => {
                    setIsVisible(false);
                    onCompleteRef.current?.();
                }, 3000);
            }
        } else if (lastSavedAt && lastSavedAt !== prevSavedAt.current) {
            // Only show success if timestamp changed (actual save happened)
            // AND we were already showing feedback
            if (isVisible) {
                setType('success');
                setMessage('已保存');
                timer = setTimeout(() => {
                    setIsVisible(false);
                    onCompleteRef.current?.();
                }, 2000);
            }
            // Always update ref even if not visible to prevent stale success messages later
            prevSavedAt.current = lastSavedAt;
        }

        return () => {
            if (timer) clearTimeout(timer);
        };
    }, [isSaving, error, lastSavedAt, trigger, isVisible]);

    return (
        <AnimatePresence>
            {isVisible && (
                <motion.div
                    initial={{ opacity: 0, y: -20, x: '-50%' }}
                    animate={{ opacity: 1, y: 0, x: '-50%' }}
                    exit={{ opacity: 0, y: -20, x: '-50%' }}
                    className={cn(
                        "absolute top-6 left-1/2 z-[100] flex items-center gap-2 px-4 py-2 rounded-full shadow-lg backdrop-blur-md border pointer-events-none select-none",
                        type === 'saving' && "bg-background/80 border-border text-foreground",
                        type === 'success' && "bg-green-500/10 border-green-500/20 text-green-500",
                        type === 'error' && "bg-red-500/10 border-red-500/20 text-red-500"
                    )}
                >
                    {type === 'saving' && <Loader2 className="w-4 h-4 animate-spin" />}
                    {type === 'success' && <Check className="w-4 h-4" />}
                    {type === 'error' && <AlertCircle className="w-4 h-4" />}
                    <span className="text-sm font-medium">{message}</span>
                </motion.div>
            )}
        </AnimatePresence>
    );
}
