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

export const AdminTemplates: React.FC = () => {
  const { templates, addTemplate, updateTemplate, toggleTemplateStatus } = useData();
  const { addToast } = useToast();
  const [filter, setFilter] = useState('all');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [previewTemplate, setPreviewTemplate] = useState<Template | null>(null);

  // Form State
  const [name, setName] = useState('');
  const [category, setCategory] = useState('طب عام');
  const [thumbnail, setThumbnail] = useState('');
  const [editingTemplate, setEditingTemplate] = useState<Template | null>(null);

  const handleToggle = (id: string, currentStatus: boolean) => {
    toggleTemplateStatus(id);
    addToast(currentStatus ? 'تم تعطيل القالب' : 'تم تفعيل القالب', 'info');
  };

  const handleSave = (e: React.FormEvent) => {
      e.preventDefault();
      if (name && thumbnail) {
          if (editingTemplate) {
              const updatedTemplate: Template = {
                  ...editingTemplate,
                  name,
                  category,
                  thumbnail,
                  // isActive is preserved from editingTemplate
              };
              updateTemplate(updatedTemplate);
              addToast('تم تحديث بيانات القالب بنجاح', 'success');
          } else {
              const newTemplate: Template = {
                  id: `t_${Date.now()}`,
                  name,
                  category,
                  thumbnail,
                  isActive: true
              };
              addTemplate(newTemplate);
              addToast('تم رفع القالب وإضافته للمكتبة بنجاح', 'success');
          }
          
          closeModal();
      }
  };

  const openCreateModal = () => {
      setEditingTemplate(null);
      setName('');
      setCategory('طب عام');
      setThumbnail('');
      setIsModalOpen(true);
  };

  const openEditModal = (t: Template) => {
      setEditingTemplate(t);
      setName(t.name);
      setCategory(t.category);
      setThumbnail(t.thumbnail);
      setIsModalOpen(true);
  };

  const closeModal = () => {
      setIsModalOpen(false);
      setEditingTemplate(null);
      setName('');
      setCategory('طب عام');
      setThumbnail('');
  };

  const filteredTemplates = filter === 'all' 
    ? templates 
    : templates.filter(t => {
        if (filter === 'general') return t.category === 'طب عام';
        if (filter === 'dental') return t.category === 'أسنان';
        if (filter === 'obgyn') return t.category === 'نسائية';
        if (filter === 'vet') return t.category === 'بيطري';
        if (filter === 'ophth') return t.category === 'عيون';
        return !['طب عام', 'أسنان', 'نسائية', 'بيطري', 'عيون'].includes(t.category);
    });

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row justify-between items-center gap-4 mb-6">
        <div>
          <h2 className="text-2xl font-bold text-gray-800">قوالب المواقع</h2>
          <p className="text-gray-500">مكتبة التصاميم المتاحة للمشتركين</p>
        </div>
        <button 
            onClick={openCreateModal}
            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-upload"></i>
          <span>رفع قالب جديد</span>
        </button>
      </div>

      {/* Categories Tabs */}
      <div className="flex gap-2 overflow-x-auto pb-2 border-b border-gray-200">
        <button onClick={() => setFilter('all')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${filter === 'all' ? 'bg-gray-800 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>الكل</button>
        <button onClick={() => setFilter('general')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${filter === 'general' ? 'bg-blue-600 text-white' : 'bg-blue-50 text-blue-600 hover:bg-blue-100'}`}>طب عام</button>
        <button onClick={() => setFilter('dental')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${filter === 'dental' ? 'bg-emerald-600 text-white' : 'bg-emerald-50 text-emerald-600 hover:bg-emerald-100'}`}>أسنان</button>
        <button onClick={() => setFilter('obgyn')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${filter === 'obgyn' ? 'bg-rose-500 text-white' : 'bg-rose-50 text-rose-600 hover:bg-rose-100'}`}>نسائية</button>
        <button onClick={() => setFilter('vet')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${filter === 'vet' ? 'bg-amber-600 text-white' : 'bg-amber-50 text-amber-600 hover:bg-amber-100'}`}>بيطري</button>
        <button onClick={() => setFilter('ophth')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${filter === 'ophth' ? 'bg-indigo-600 text-white' : 'bg-indigo-50 text-indigo-600 hover:bg-indigo-100'}`}>عيون</button>
        <button onClick={() => setFilter('other')} className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${filter === 'other' ? 'bg-purple-600 text-white' : 'bg-purple-50 text-purple-600 hover:bg-purple-100'}`}>أخرى</button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredTemplates.map((template) => (
            <div key={template.id} className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden group">
                <div className="relative h-48 bg-gray-200 overflow-hidden">
                    <img src={template.thumbnail} alt={template.name} className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110" />
                    <div className={`absolute top-2 right-2 backdrop-blur-sm px-3 py-1 rounded-full text-xs font-bold shadow-sm text-white ${
                        template.category === 'أسنان' ? 'bg-emerald-500/90' :
                        template.category === 'نسائية' ? 'bg-rose-500/90' :
                        template.category === 'بيطري' ? 'bg-amber-500/90' :
                        template.category === 'عيون' ? 'bg-indigo-500/90' :
                        'bg-blue-500/90'
                    }`}>
                        {template.category}
                    </div>
                    {!template.isActive && (
                        <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
                            <span className="text-white font-bold border-2 border-white px-4 py-1 rounded-lg">غير نشط</span>
                        </div>
                    )}
                </div>
                <div className="p-5">
                    <h3 className="font-bold text-lg text-gray-800 mb-1">{template.name}</h3>
                    <p className="text-xs text-gray-500 mb-4">HTML5, Tailwind CSS, React Ready</p>
                    
                    <div className="flex justify-between items-center">
                        <div className="flex items-center gap-2">
                             <div className={`w-3 h-3 rounded-full ${template.isActive ? 'bg-success' : 'bg-gray-300'}`}></div>
                             <span className="text-sm text-gray-600">{template.isActive ? 'متاح للبيع' : 'معطل'}</span>
                        </div>
                        <button 
                            onClick={() => setPreviewTemplate(template)}
                            className="text-primary hover:text-primary-dark text-sm font-semibold flex items-center gap-1"
                        >
                            معاينة <i className="fas fa-eye"></i>
                        </button>
                    </div>
                </div>
                <div className="bg-gray-50 p-3 flex justify-between border-t border-gray-100">
                     <button 
                        onClick={() => openEditModal(template)}
                        className="flex-1 text-center text-gray-600 hover:text-primary text-sm font-medium border-l border-gray-200 pl-2"
                     >
                        <i className="fas fa-edit"></i> تعديل
                     </button>
                     <button 
                       onClick={() => handleToggle(template.id, template.isActive)}
                       className={`flex-1 text-center text-sm font-medium ${template.isActive ? 'text-red-500 hover:text-red-700' : 'text-green-500 hover:text-green-700'}`}
                     >
                        <i className={`fas ${template.isActive ? 'fa-ban' : 'fa-check'}`}></i> {template.isActive ? 'تعطيل' : 'تفعيل'}
                     </button>
                </div>
            </div>
        ))}
        {filteredTemplates.length === 0 && (
            <div className="col-span-full py-12 text-center text-gray-400">
                <i className="fas fa-box-open text-4xl mb-2"></i>
                <p>لا توجد قوالب في هذا التصنيف</p>
            </div>
        )}
      </div>

      {/* Add/Edit Modal */}
      <Modal isOpen={isModalOpen} onClose={closeModal} title={editingTemplate ? "تعديل بيانات القالب" : "رفع قالب جديد"}>
          <form onSubmit={handleSave} className="space-y-4">
              <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">اسم القالب</label>
                  <input 
                    type="text" 
                    value={name}
                    onChange={(e) => setName(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>
                  <label className="block text-sm font-medium text-gray-700 mb-1">تصنيف القالب</label>
                  <select 
                    value={category}
                    onChange={(e) => setCategory(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"
                  >
                      <option value="طب عام">طب عام</option>
                      <option value="أسنان">أسنان</option>
                      <option value="نسائية">نسائية وتوليد</option>
                      <option value="أطفال">أطفال</option>
                      <option value="تجميل">جلدية وتجميل</option>
                      <option value="بيطري">بيطري</option>
                      <option value="عيون">عيون</option>
                      <option value="عظام">عظام</option>
                      <option value="تغذية">تغذية</option>
                      <option value="علاج طبيعي">علاج طبيعي</option>
                      <option value="نفسية">نفسية</option>
                      <option value="قلبية">قلبية</option>
                      <option value="أعصاب">أعصاب</option>
                      <option value="أخرى">أخرى</option>
                  </select>
              </div>
              <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">رابط الصورة المصغرة (Thumbnail URL)</label>
                  <input 
                    type="url" 
                    value={thumbnail}
                    onChange={(e) => setThumbnail(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="https://..."
                    required
                  />
              </div>
              
              {thumbnail && (
                  <div className="mt-2 relative h-32 w-full rounded-lg overflow-hidden border border-gray-200">
                      <img src={thumbnail} alt="Preview" className="w-full h-full object-cover" />
                      <div className="absolute inset-0 bg-black/20 flex items-center justify-center text-white font-bold text-sm">
                          معاينة الصورة
                      </div>
                  </div>
              )}

              <button type="submit" className="w-full bg-primary text-white py-2.5 rounded-xl font-bold hover:bg-primary-dark transition-colors mt-4">
                  {editingTemplate ? 'حفظ التغييرات' : 'إضافة القالب'}
              </button>
          </form>
      </Modal>

      {/* Preview Modal */}
      {previewTemplate && (
          <Modal isOpen={!!previewTemplate} onClose={() => setPreviewTemplate(null)} title={`معاينة: ${previewTemplate.name}`}>
              <div className="space-y-4">
                  <div className="rounded-lg overflow-hidden border border-gray-200 shadow-xl max-h-[60vh] overflow-y-auto">
                      <img src={previewTemplate.thumbnail} alt={previewTemplate.name} className="w-full h-auto" />
                  </div>
                  <div className="flex justify-between items-center bg-gray-50 p-4 rounded-lg">
                      <div>
                          <h4 className="font-bold text-gray-800">{previewTemplate.name}</h4>
                          <span className="text-sm text-gray-500">تصنيف: {previewTemplate.category}</span>
                      </div>
                      <div className="flex gap-2">
                          <button onClick={() => setPreviewTemplate(null)} className="px-4 py-2 bg-gray-200 rounded-lg text-gray-700 hover:bg-gray-300 text-sm font-bold">
                              إغلاق
                          </button>
                      </div>
                  </div>
              </div>
          </Modal>
      )}
    </div>
  );
};
