import { useState } from 'react';
import { RefreshCw } from 'lucide-react';

export default function AIField({ label, value, onChange, onRegenerate, multiline = true, maxLength, hint }) {
  const [loading, setLoading] = useState(false);

  const handleRegen = async () => {
    setLoading(true);
    await onRegenerate();
    setLoading(false);
  };

  const inputClass = `w-full px-3 py-2 text-sm border-2 rounded-lg focus:outline-none transition-all resize-none
    bg-white focus:border-purple-400
    ${value ? 'border-purple-300' : 'border-gray-200'}`;

  return (
    <div className="space-y-1">
      <div className="flex items-center justify-between">
        <label className="text-xs font-semibold text-gray-700">{label}</label>
        <div className="flex items-center gap-2">
          {maxLength && (
            <span className={`text-xs ${value?.length > maxLength ? 'text-red-500' : 'text-gray-400'}`}>
              {value?.length || 0}/{maxLength}
            </span>
          )}
          <button
            onClick={handleRegen}
            disabled={loading}
            className="flex items-center gap-1 text-xs text-purple-600 hover:text-purple-800 font-medium disabled:opacity-50 transition-colors"
          >
            <RefreshCw size={11} className={loading ? 'animate-spin' : ''} />
            Regenerate
          </button>
        </div>
      </div>
      {multiline ? (
        <textarea
          value={value || ''}
          onChange={e => onChange(e.target.value)}
          rows={label.includes('Description') ? 6 : 3}
          className={inputClass}
          style={{ boxShadow: value ? '0 0 0 3px rgba(147,51,234,0.08)' : 'none' }}
        />
      ) : (
        <input
          type="text"
          value={value || ''}
          onChange={e => onChange(e.target.value)}
          className={inputClass}
          style={{ boxShadow: value ? '0 0 0 3px rgba(147,51,234,0.08)' : 'none' }}
        />
      )}
      {hint && <p className="text-xs text-gray-400">{hint}</p>}
    </div>
  );
}