
import React, { useState } from 'react';
import { useToast } from '../../context/ToastContext';

interface SaveableInputProps {
  label: string;
  value: string | number;
  onChange?: (val: string) => void;
  type?: 'text' | 'number' | 'date' | 'textarea' | 'email';
  placeholder?: string;
  width?: 'full' | 'half';
  rows?: number;
}

export const SaveableInput: React.FC<SaveableInputProps> = ({ 
  label, 
  value: initialValue, 
  type = 'text', 
  placeholder,
  width = 'full',
  rows = 3
}) => {
  const [value, setValue] = useState(initialValue);
  const [isChanged, setIsChanged] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const { addToast } = useToast();

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setValue(e.target.value);
    setIsChanged(true);
  };

  const handleSave = () => {
    setIsSaving(true);
    // Simulate API save
    setTimeout(() => {
        setIsSaving(false);
        setIsChanged(false);
        addToast(`تم حفظ "${label}" بنجاح`, 'success');
    }, 600);
  };

  const widthClass = width === 'half' ? 'col-span-1' : 'col-span-full md:col-span-2';

  return (
    <div className={widthClass}>
      <label className="block text-xs font-bold text-gray-700 mb-1.5">{label}</label>
      <div className="relative group">
        {type === 'textarea' ? (
            <textarea 
                className="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-transparent transition-all pl-12 bg-white text-gray-900"
                rows={rows}
                value={value}
                onChange={handleChange}
                placeholder={placeholder}
            ></textarea>
        ) : (
            <input 
                type={type}
                className="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-transparent transition-all pl-12 bg-white text-gray-900"
                value={value}
                onChange={handleChange}
                placeholder={placeholder}
            />
        )}
        
        {/* Save Button Overlay */}
        <button
            onClick={handleSave}
            disabled={!isChanged || isSaving}
            className={`absolute left-2 top-2 p-1.5 rounded-lg transition-all flex items-center justify-center ${
                isChanged 
                ? 'bg-primary text-white opacity-100 shadow-md hover:bg-primary-dark' 
                : 'bg-transparent text-gray-300 opacity-0 group-hover:opacity-100'
            }`}
            title="حفظ هذا الحقل"
        >
            {isSaving ? (
                <i className="fas fa-spinner fa-spin text-sm"></i>
            ) : (
                <i className="fas fa-save text-sm"></i>
            )}
        </button>
      </div>
    </div>
  );
};
