import { Button } from './ui/button';
import { Loader2, Check } from 'lucide-react';
import { useState, useEffect } from 'react';
import { cn } from '../lib/utils';
import { __ } from '../lib/i18n';

interface SettingsSaveBarProps {
  isDirty: boolean;
  isSaving: boolean;
  onSave: () => Promise<void>;
  onDiscard: () => void;
}

export function SettingsSaveBar({ isDirty, isSaving, onSave, onDiscard }: SettingsSaveBarProps) {
  const [showSuccess, setShowSuccess] = useState(false);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (isDirty) {
      setVisible(true);
      setShowSuccess(false);
    } else if (!isSaving && !showSuccess) {
      const timer = setTimeout(() => setVisible(false), 150);
      return () => clearTimeout(timer);
    }
  }, [isDirty, isSaving, showSuccess]);

  async function handleSave() {
    try {
      await onSave();
      setShowSuccess(true);
      setTimeout(() => setShowSuccess(false), 1500);
    } catch {
      // Error handled by hook, bar stays visible
    }
  }

  if (!visible && !isDirty) return null;

  return (
    <div
      className={cn(
        'fixed bottom-0 left-0 right-0 z-40 transition-transform duration-300 ease-out',
        isDirty || showSuccess ? 'translate-y-0' : 'translate-y-full',
      )}
    >
      <div className="bg-slate-900 border-t border-slate-700 px-6 py-3">
        <div className="max-w-4xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-2">
            <span className="h-2 w-2 rounded-full bg-cyan-400 animate-pulse" />
            <span className="text-sm text-slate-300">
              {showSuccess ? __('Settings saved successfully') : __('You have unsaved changes')}
            </span>
          </div>
          <div className="flex items-center gap-2">
            {!showSuccess && (
              <>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={onDiscard}
                  disabled={isSaving}
                  className="text-slate-400 hover:text-white hover:bg-slate-800"
                >
                  {__('Discard')}
                </Button>
                <Button variant="accent" size="sm" onClick={handleSave} disabled={isSaving}>
                  {isSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                  {__('Save Settings')}
                </Button>
              </>
            )}
            {showSuccess && (
              <div className="flex items-center gap-1 text-emerald-400 text-sm">
                <Check className="h-4 w-4" />
                <span>{__('Saved')}</span>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
