
import React, { useState, useEffect } from 'react';
import { FieldConfig } from '../../types';
import { useData } from '../../context/DataContext';
import { useToast } from '../../context/ToastContext';

interface SmartFieldProps {
  config: FieldConfig;
  value: any;
  onChange: (val: any) => void;
  isEditMode: boolean; // The master "Edit" toggle for the page
}

export const SmartField: React.FC<SmartFieldProps> = ({ config, value, onChange, isEditMode }) => {
  const { updateFieldConfig } = useData();
  const { addToast } = useToast();
  
  const [localLabel, setLocalLabel] = useState(config.label);
  const [isRenaming, setIsRenaming] = useState(false);

  // Sync label if updated from elsewhere
  useEffect(() => {
      setLocalLabel(config.label);
  }, [config.label]);

  // If disabled and NOT in edit mode, return null (hide it)
  if (!config.isEnabled && !isEditMode) return null;

  const handleToggleEnable = () => {
    updateFieldConfig({ ...config, isEnabled: !config.isEnabled });
  };

  const handleToggleVisibility = () => {
    updateFieldConfig({ ...config, isVisibleToPatient: !config.isVisibleToPatient });
  };

  const handleRename = () => {
      updateFieldConfig({ ...config, label: localLabel });
      setIsRenaming(false);
      addToast('تم تغيير اسم الحقل', 'success');
  };

  const widthClass = config.width === 'half' ? 'col-span-1' : 'col-span-full md:col-span-2';
  const opacityClass = !config.isEnabled ? 'opacity-50 grayscale' : '';

  return (
    <div className={`${widthClass} relative group transition-all duration-300 ${opacityClass} ${isEditMode ? 'p-3 border-2 border-dashed border-gray-300 rounded-xl hover:border-primary bg-gray-50/50 hover:bg-white hover:shadow-lg z-10' : ''}`}>
      
      {/* Configuration Toolbar (Visible only in Edit Mode) */}
      {isEditMode && (
          <div className="flex items-center justify-between mb-3 bg-white p-2 rounded-lg shadow-sm border border-gray-200">
              <div className="flex items-center gap-2">
                  {/* Enable/Disable Toggle */}
                  <button 
                    onClick={handleToggleEnable}
                    className={`w-8 h-8 rounded-lg flex items-center justify-center transition-colors ${config.isEnabled ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}
                    title={config.isEnabled ? 'انقر للتعطيل' : 'انقر للتفعيل'}
                  >
                      <i className={`fas ${config.isEnabled ? 'fa-toggle-on' : 'fa-toggle-off'} text-lg`}></i>
                  </button>
                  
                  {/* Public/Private Toggle */}
                  <button 
                    onClick={handleToggleVisibility}
                    className={`w-8 h-8 rounded-lg flex items-center justify-center transition-colors ${config.isVisibleToPatient ? 'bg-blue-100 text-blue-700' : 'bg-gray-200 text-gray-500'}`}
                    title={config.isVisibleToPatient ? 'يظهر للزبون' : 'مخفي عن الزبون'}
                  >
                      <i className={`fas ${config.isVisibleToPatient ? 'fa-eye' : 'fa-eye-slash'} text-sm`}></i>
                  </button>
              </div>

              {/* Rename Action */}
              <div className="flex items-center gap-1">
                  {isRenaming ? (
                      <div className="flex items-center gap-1 animate-fade-in">
                        <input 
                            type="text" 
                            value={localLabel} 
                            onChange={(e) => setLocalLabel(e.target.value)}
                            className="text-xs border border-primary rounded px-2 py-1 w-32 focus:outline-none bg-white text-gray-900"
                            autoFocus
                        />
                        <button onClick={handleRename} className="bg-green-500 text-white rounded p-1 hover:bg-green-600"><i className="fas fa-check text-xs"></i></button>
                        <button onClick={() => { setIsRenaming(false); setLocalLabel(config.label); }} className="bg-red-500 text-white rounded p-1 hover:bg-red-600"><i className="fas fa-times text-xs"></i></button>
                      </div>
                  ) : (
                      <button onClick={() => setIsRenaming(true)} className="text-xs text-gray-500 hover:text-primary flex items-center gap-1 px-2 py-1 hover:bg-gray-100 rounded transition-colors">
                          <i className="fas fa-pen"></i> تعديل الاسم
                      </button>
                  )}
              </div>
          </div>
      )}

      {/* The Actual Input Field */}
      <div>
          <label className="block text-xs font-bold text-gray-700 mb-2 flex justify-between items-center">
              <span className={isEditMode && !config.isEnabled ? 'line-through text-gray-400' : ''}>{config.label}</span>
              {config.isVisibleToPatient && !isEditMode && (
                  <span className="bg-blue-50 text-blue-600 text-[10px] px-2 py-0.5 rounded-full flex items-center gap-1">
                      <i className="fas fa-globe"></i> مرئي للزبون
                  </span>
              )}
          </label>
          
          {config.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 bg-white text-gray-900 placeholder-gray-400"
                rows={3}
                value={value || ''}
                onChange={(e) => onChange(e.target.value)}
                disabled={isEditMode} // Disable input while configuring to prevent confusion
                placeholder={isEditMode ? 'الحقل معطل أثناء التعديل' : ''}
              ></textarea>
          ) : config.type === 'select' ? (
              <select 
                className="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-transparent bg-white text-gray-900"
                value={value || ''}
                onChange={(e) => onChange(e.target.value)}
                disabled={isEditMode}
              >
                  <option value="">اختر...</option>
                  {config.options?.map(opt => <option key={opt} value={opt}>{opt}</option>)}
              </select>
          ) : config.type === 'date' ? (
              <input 
                type="date"
                className="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-transparent transition-all bg-white text-gray-900"
                value={value || ''}
                onChange={(e) => onChange(e.target.value)}
                disabled={isEditMode}
              />
          ) : (
              <input 
                type={config.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 bg-white text-gray-900 placeholder-gray-400"
                value={value || ''}
                onChange={(e) => onChange(e.target.value)}
                disabled={isEditMode}
                placeholder={isEditMode ? 'الحقل معطل أثناء التعديل' : ''}
              />
          )}
      </div>
    </div>
  );
};
