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

export const PageManager: React.FC = () => {
  const { modules, updateModule, dynamicPages, addDynamicPage, customForms, deleteDynamicPage, togglePageVisibility } = useData();
  const { addToast } = useToast();
  
  const [isPageModalOpen, setIsPageModalOpen] = useState(false);
  
  // Page creation state
  const [pageTitle, setPageTitle] = useState('');
  const [pageIcon, setPageIcon] = useState('fa-file');
  const [pageClinic, setPageClinic] = useState<ClinicType | 'all'>('all');
  const [selectedForm, setSelectedForm] = useState('');

  const handleModuleToggle = (id: string, currentStatus: boolean) => {
      const module = modules.find(m => m.id === id);
      if (module) {
          updateModule({ ...module, isEnabled: !currentStatus });
          addToast('تم تحديث حالة الميزة', 'info');
      }
  };

  const handleSavePage = () => {
      if (!pageTitle || !selectedForm) {
          addToast('يرجى إكمال البيانات', 'error');
          return;
      }
      const newPage: DynamicPage = {
          id: `page_${Date.now()}`,
          title: pageTitle,
          path: `custom-${Date.now()}`,
          icon: pageIcon,
          type: 'form',
          connectedFormId: selectedForm,
          clinicType: pageClinic,
          order: dynamicPages.length + 1,
          isVisible: true
      };
      addDynamicPage(newPage);
      addToast('تمت إضافة الصفحة للقائمة بنجاح', 'success');
      setIsPageModalOpen(false);
      // Reset
      setPageTitle('');
      setSelectedForm('');
  };

  return (
    <div className="space-y-8">
      
      {/* 1. Feature Manager Section */}
      <section>
          <h2 className="text-xl font-bold text-gray-800 mb-4 flex items-center gap-2">
              <i className="fas fa-cubes text-primary"></i>
              إدارة الميزات والوحدات (Modules)
          </h2>
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 divide-y md:divide-y-0 md:divide-x md:divide-x-reverse">
                  {modules.map(mod => (
                      <div key={mod.id} className="p-5 flex items-center justify-between hover:bg-gray-50 transition-colors">
                          <div className="flex items-center gap-4">
                              <div className={`w-12 h-12 rounded-xl flex items-center justify-center text-xl shadow-sm ${mod.isEnabled ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-400'}`}>
                                  <i className={`fas ${mod.icon}`}></i>
                              </div>
                              <div>
                                  <h4 className={`font-bold ${mod.isEnabled ? 'text-gray-800' : 'text-gray-500'}`}>{mod.defaultName}</h4>
                                  <p className="text-xs text-gray-500 mt-0.5 line-clamp-1">{mod.description}</p>
                                  <div className="flex flex-wrap gap-1 mt-1.5">
                                      {mod.clinicTypes.slice(0, 3).map(ct => (
                                          <span key={ct} className="text-[10px] bg-gray-100 px-1.5 py-0.5 rounded text-gray-600">{ct}</span>
                                      ))}
                                      {mod.clinicTypes.length > 3 && <span className="text-[10px] text-gray-400">+{mod.clinicTypes.length - 3}</span>}
                                  </div>
                              </div>
                          </div>
                          <label className="relative inline-flex items-center cursor-pointer">
                            <input 
                                type="checkbox" 
                                className="sr-only peer" 
                                checked={mod.isEnabled}
                                onChange={() => handleModuleToggle(mod.id, mod.isEnabled)}
                            />
                            <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                        </label>
                      </div>
                  ))}
              </div>
          </div>
      </section>

      {/* 2. Page Builder Section */}
      <section>
          <div className="flex justify-between items-center mb-4">
             <h2 className="text-xl font-bold text-gray-800 flex items-center gap-2">
                 <i className="fas fa-sitemap text-primary"></i>
                 هيكلية القوائم والصفحات
             </h2>
             <button onClick={() => setIsPageModalOpen(true)} className="bg-primary text-white px-4 py-2 rounded-xl text-sm font-bold shadow-md hover:bg-primary-dark transition-colors">
                 <i className="fas fa-plus ml-2"></i> إضافة صفحة جديدة
             </button>
          </div>

          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
              {dynamicPages.length === 0 && <p className="text-center text-gray-400 py-8">لا توجد صفحات مخصصة مضافة للقائمة</p>}
              <div className="space-y-3">
                  {dynamicPages.map(page => (
                      <div key={page.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">
                              <i className="fas fa-grip-vertical text-gray-300 cursor-move hover:text-gray-500"></i>
                              <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center text-gray-600 border border-gray-200 shadow-sm">
                                  <i className={`fas ${page.icon}`}></i>
                              </div>
                              <div>
                                  <h4 className="font-bold text-gray-800 text-lg">{page.title}</h4>
                                  <div className="flex gap-2 mt-1">
                                      <span className="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded font-medium">نوع: {page.type}</span>
                                      <span className="text-xs bg-gray-200 text-gray-600 px-2 py-0.5 rounded">ظهور: {page.clinicType === 'all' ? 'الكل' : page.clinicType}</span>
                                  </div>
                              </div>
                          </div>
                          
                          <div className="flex items-center gap-3 opacity-60 group-hover:opacity-100 transition-opacity">
                              <div className="text-xs text-gray-400 border-l pl-3 ml-3 hidden md:block">
                                  مرتبط بـ: {customForms.find(f => f.id === page.connectedFormId)?.title || 'Unknown Form'}
                              </div>
                              <button onClick={() => togglePageVisibility(page.id)} className={`text-lg transition-colors ${page.isVisible ? 'text-green-500 hover:text-green-600' : 'text-gray-400 hover:text-gray-600'}`} title={page.isVisible ? 'إخفاء' : 'إظهار'}>
                                  <i className={`fas ${page.isVisible ? 'fa-eye' : 'fa-eye-slash'}`}></i>
                              </button>
                              <button onClick={() => deleteDynamicPage(page.id)} className="w-8 h-8 rounded-full bg-white border border-red-100 text-red-400 hover:text-red-600 hover:bg-red-50 flex items-center justify-center transition-colors" title="حذف">
                                  <i className="fas fa-trash"></i>
                              </button>
                          </div>
                      </div>
                  ))}
              </div>
          </div>
      </section>

      <Modal isOpen={isPageModalOpen} onClose={() => setIsPageModalOpen(false)} title="إضافة صفحة مخصصة للقائمة">
          <div className="space-y-4">
              <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">عنوان الصفحة (كما سيظهر في القائمة)</label>
                  <input type="text" value={pageTitle} onChange={e => setPageTitle(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="مثال: استمارة فحص" />
              </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={pageIcon} onChange={e => setPageIcon(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-lg font-mono text-sm bg-white text-gray-900">
                          <option value="fa-file-alt">File (General)</option>
                          <option value="fa-paw">Paw (Vet)</option>
                          <option value="fa-eye">Eye (Ophth)</option>
                          <option value="fa-tooth">Tooth (Dental)</option>
                          <option value="fa-heartbeat">Heart (Cardio)</option>
                          <option value="fa-child">Child (Peds)</option>
                          <option value="fa-star">Star</option>
                      </select>
                  </div>
                  <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">النموذج المرتبط</label>
                      <select value={selectedForm} onChange={e => setSelectedForm(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white text-gray-900">
                          <option value="">اختر نموذجاً...</option>
                          {customForms.map(f => (
                              <option key={f.id} value={f.id}>{f.title}</option>
                          ))}
                      </select>
                  </div>
              </div>
              <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">تخصيص العيادة (لمن تظهر؟)</label>
                  <select value={pageClinic} onChange={e => setPageClinic(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="all">جميع العيادات</option>
                        <option value="dental">أسنان</option>
                        <option value="vet">بيطري</option>
                        <option value="ophthalmology">عيون</option>
                        <option value="obgyn">نسائية</option>
                        <option value="orthopedics">عظام</option>
                  </select>
              </div>
              <button onClick={handleSavePage} className="w-full bg-primary text-white py-3 rounded-xl font-bold shadow-md hover:bg-primary-dark transition-all mt-2">
                  إضافة الصفحة
              </button>
          </div>
      </Modal>
    </div>
  );
};
