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

export const FieldManager: React.FC = () => {
  const { fieldConfigs, updateFieldConfig, addFieldConfig, deleteFieldConfig } = useData();
  const { addToast } = useToast();
  
  const [activeSection, setActiveSection] = useState('personal');
  const [isModalOpen, setIsModalOpen] = useState(false);
  
  // New Field State
  const [newFieldLabel, setNewFieldLabel] = useState('');
  const [newFieldType, setNewFieldType] = useState<FieldConfig['type']>('text');
  const [newFieldWidth, setNewFieldWidth] = useState<'full' | 'half'>('half');

  const sections = [
      { id: 'personal', label: 'البيانات الشخصية', icon: 'fa-id-card' },
      { id: 'history', label: 'السجل الطبي', icon: 'fa-heartbeat' },
      { id: 'obgyn', label: 'الحمل والولادة', icon: 'fa-baby' },
      { id: 'pediatric', label: 'طب الأطفال', icon: 'fa-child' },
      { id: 'surgery', label: 'الجراحة', icon: 'fa-procedures' },
      { id: 'dental', label: 'الأسنان', icon: 'fa-tooth' },
      { id: 'followup', label: 'المتابعة', icon: 'fa-chart-line' },
      { id: 'consultation', label: 'الاستشارات', icon: 'fa-comments' },
  ];

  const currentFields = fieldConfigs.filter(f => f.section === activeSection);

  const handleToggleEnable = (field: FieldConfig) => {
      updateFieldConfig({ ...field, isEnabled: !field.isEnabled });
      addToast(field.isEnabled ? 'تم تعطيل الحقل' : 'تم تفعيل الحقل', 'info');
  };

  const handleToggleVisibility = (field: FieldConfig) => {
      updateFieldConfig({ ...field, isVisibleToPatient: !field.isVisibleToPatient });
      addToast('تم تحديث ظهور الحقل', 'info');
  };

  const handleRename = (field: FieldConfig, newLabel: string) => {
      updateFieldConfig({ ...field, label: newLabel });
  };

  const handleDelete = (id: string) => {
      if(window.confirm('هل أنت متأكد من حذف هذا الحقل؟ لا يمكن التراجع عن هذا الإجراء.')) {
          deleteFieldConfig(id);
          addToast('تم حذف الحقل بنجاح', 'error');
      }
  };

  const handleAddField = (e: React.FormEvent) => {
      e.preventDefault();
      if(newFieldLabel) {
          const newField: FieldConfig = {
              id: `custom_${Date.now()}`,
              label: newFieldLabel,
              type: newFieldType,
              section: activeSection,
              isEnabled: true,
              isVisibleToPatient: false,
              width: newFieldWidth,
              order: currentFields.length + 1,
              isSystem: false
          };
          addFieldConfig(newField);
          addToast('تم إضافة الحقل الجديد بنجاح', 'success');
          setIsModalOpen(false);
          setNewFieldLabel('');
      }
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h2 className="text-2xl font-bold text-gray-800">إدارة الحقول والنماذج</h2>
          <p className="text-gray-500">التحكم المركزي في البيانات التي تظهر في ملفات المرضى</p>
        </div>
        <button 
          onClick={() => setIsModalOpen(true)}
          className="bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-xl shadow-md transition-colors flex items-center gap-2"
        >
          <i className="fas fa-plus"></i>
          <span>حقل جديد</span>
        </button>
      </div>

      <div className="flex flex-col lg:flex-row gap-6">
          {/* Sidebar Sections */}
          <div className="lg:w-64 bg-white rounded-2xl shadow-sm border border-gray-100 p-2 h-fit">
              {sections.map(sec => (
                  <button
                    key={sec.id}
                    onClick={() => setActiveSection(sec.id)}
                    className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl mb-1 transition-all ${
                        activeSection === sec.id 
                        ? 'bg-blue-50 text-primary font-bold' 
                        : 'text-gray-600 hover:bg-gray-50'
                    }`}
                  >
                      <i className={`fas ${sec.icon} w-5 text-center`}></i>
                      {sec.label}
                  </button>
              ))}
          </div>

          {/* Fields List */}
          <div className="flex-1 bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
              <h3 className="font-bold text-gray-800 mb-6 flex items-center gap-2 text-lg border-b border-gray-100 pb-4">
                  <i className={`fas ${sections.find(s => s.id === activeSection)?.icon} text-primary`}></i>
                  حقول قسم {sections.find(s => s.id === activeSection)?.label}
              </h3>

              <div className="space-y-3">
                  {currentFields.map(field => (
                      <div key={field.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-xl border border-gray-200 hover:border-blue-300 transition-colors group">
                          <div className="flex items-center gap-4 flex-1">
                              <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center text-gray-500 border border-gray-200 text-lg">
                                  {field.type === 'text' && <i className="fas fa-font"></i>}
                                  {field.type === 'number' && <i className="fas fa-hashtag"></i>}
                                  {field.type === 'date' && <i className="fas fa-calendar"></i>}
                                  {field.type === 'textarea' && <i className="fas fa-align-left"></i>}
                                  {field.type === 'select' && <i className="fas fa-list"></i>}
                              </div>
                              <div className="flex-1">
                                  <input 
                                    type="text" 
                                    value={field.label}
                                    onChange={(e) => handleRename(field, e.target.value)}
                                    className="font-bold text-gray-800 bg-transparent border-b border-transparent focus:border-primary focus:ring-0 px-0 w-full"
                                  />
                                  <div className="flex gap-2 mt-1">
                                      <span className="text-[10px] bg-gray-200 text-gray-600 px-2 py-0.5 rounded uppercase">{field.type}</span>
                                      {field.isSystem && <span className="text-[10px] bg-purple-100 text-purple-700 px-2 py-0.5 rounded flex items-center gap-1"><i className="fas fa-lock text-[8px]"></i> أساسي</span>}
                                      {!field.isSystem && <span className="text-[10px] bg-blue-100 text-blue-700 px-2 py-0.5 rounded">مخصص</span>}
                                  </div>
                              </div>
                          </div>

                          <div className="flex items-center gap-2">
                              {/* Public Toggle */}
                              <button 
                                onClick={() => handleToggleVisibility(field)}
                                className={`w-9 h-9 rounded-lg flex items-center justify-center transition-colors ${field.isVisibleToPatient ? 'bg-blue-100 text-blue-600' : 'bg-gray-100 text-gray-400'}`}
                                title={field.isVisibleToPatient ? 'يظهر للمريض' : 'مخفي عن المريض'}
                              >
                                  <i className={`fas ${field.isVisibleToPatient ? 'fa-eye' : 'fa-eye-slash'}`}></i>
                              </button>

                              {/* Enable Toggle */}
                              <button 
                                onClick={() => handleToggleEnable(field)}
                                className={`w-9 h-9 rounded-lg flex items-center justify-center transition-colors ${field.isEnabled ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-500'}`}
                                title={field.isEnabled ? 'مفعل' : 'معطل'}
                              >
                                  <i className={`fas ${field.isEnabled ? 'fa-check' : 'fa-ban'}`}></i>
                              </button>

                              {/* Delete (Custom only) */}
                              {!field.isSystem && (
                                  <button 
                                    onClick={() => handleDelete(field.id)}
                                    className="w-9 h-9 rounded-lg bg-white border border-red-100 text-red-400 hover:bg-red-50 hover:text-red-600 transition-colors flex items-center justify-center"
                                    title="حذف"
                                  >
                                      <i className="fas fa-trash"></i>
                                  </button>
                              )}
                          </div>
                      </div>
                  ))}
              </div>
          </div>
      </div>

      {/* Add Field Modal */}
      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="إضافة حقل مخصص">
          <form onSubmit={handleAddField} className="space-y-4">
              <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">اسم الحقل (Label)</label>
                  <input 
                    type="text" 
                    value={newFieldLabel}
                    onChange={e => setNewFieldLabel(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900"
                    placeholder="مثال: رقم الملف الورقي"
                    required 
                  />
              </div>
              <div className="grid grid-cols-2 gap-4">
                  <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">نوع البيانات</label>
                      <select 
                        value={newFieldType}
                        onChange={e => setNewFieldType(e.target.value as any)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white text-gray-900"
                      >
                          <option value="text">نص قصير</option>
                          <option value="textarea">نص طويل</option>
                          <option value="number">رقم</option>
                          <option value="date">تاريخ</option>
                      </select>
                  </div>
                  <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">العرض</label>
                      <select 
                        value={newFieldWidth}
                        onChange={e => setNewFieldWidth(e.target.value as any)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white text-gray-900"
                      >
                          <option value="half">نصف سطر (50%)</option>
                          <option value="full">سطر كامل (100%)</option>
                      </select>
                  </div>
              </div>
              <div className="bg-blue-50 p-3 rounded-lg text-xs text-blue-700">
                  <i className="fas fa-info-circle mr-1"></i> سيتم إضافة الحقل إلى قسم <b>{sections.find(s => s.id === activeSection)?.label}</b>
              </div>
              <button type="submit" className="w-full bg-primary text-white py-2.5 rounded-xl font-bold hover:bg-primary-dark transition-colors">
                  إضافة الحقل
              </button>
          </form>
      </Modal>
    </div>
  );
};
