import { useState } from 'react';
import { Save, Check, Loader2 } from 'lucide-react';

/*
 * SFR-02 공통컴포넌트: 저장 버튼
 */

interface SaveButtonProps {
  onClick: () => void | Promise<void>;
  label?: string;
  disabled?: boolean;
  className?: string;
}

export function SaveButton({ onClick, label = '저장', disabled = false, className = '' }: SaveButtonProps) {
  const [state, setState] = useState<'idle' | 'saving' | 'done'>('idle');

  const handleClick = async () => {
    if (state !== 'idle') return;
    setState('saving');
    try {
      await onClick();
      setState('done');
      setTimeout(() => setState('idle'), 1500);
    } catch {
      setState('idle');
    }
  };

  return (
    <button
      type="button"
      onClick={handleClick}
      disabled={disabled || state !== 'idle'}
      className={`flex items-center gap-1.5 px-4 py-1.5 rounded-lg text-[11px] font-bold transition-colors disabled:opacity-40 ${
        state === 'done'
          ? 'bg-green-600 text-on-vivid'
          : 'bg-blue-600 hover:bg-blue-500 text-on-vivid'
      } ${className}`}
    >
      {state === 'saving' ? <Loader2 className="w-3.5 h-3.5 animate-spin" />
        : state === 'done' ? <Check className="w-3.5 h-3.5" />
        : <Save className="w-3.5 h-3.5" />}
      {state === 'saving' ? '저장 중...' : state === 'done' ? '저장 완료' : label}
    </button>
  );
}
