
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { SubscriptionStatus, Tenant, ClinicType } from '../../types';
import { Modal } from '../../components/Modal';
import { useToast } from '../../context/ToastContext';
import { useData } from '../../context/DataContext';

export const AdminTenants: React.FC = () => {
  const navigate = useNavigate();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [editingTenant, setEditingTenant] = useState<Tenant | null>(null);
  
  // State for subscription calculation
  const [subDuration, setSubDuration] = useState(12);
  
  const { tenants, addTenant, updateTenant, deleteTenant, templates, setClinicType } = useData();
  const { addToast } = useToast();

  const filteredTenants = tenants.filter(t => {
    const matchesSearch = t.name.includes(searchTerm) || t.clinicName.includes(searchTerm);
    const matchesStatus = statusFilter === 'all' || 
                          (statusFilter === 'active' && t.status === SubscriptionStatus.ACTIVE) ||
                          (statusFilter === 'expired' && t.status === SubscriptionStatus.EXPIRED);
    return matchesSearch && matchesStatus;
  });

  const generateActivationCode = () => {
    return Math.random().toString(36).substring(2, 8).toUpperCase();
  };

  const calculateExpiryDate = (months: number) => {
      const date = new Date();
      date.setMonth(date.getMonth() + months);
      return date.toISOString().split('T')[0];
  };

  const handleResetPassword = (email: string) => {
      // Simulation of sending a reset email
      if(window.confirm(`هل تريد إرسال رابط إعادة تعيين كلمة المرور إلى ${email}؟`)) {
          addToast(`تم إرسال رابط إعادة تعيين كلمة المرور بنجاح إلى ${email}`, 'info');
      }
  };

  const handleLoginAsTenant = (tenant: Tenant) => {
      if(window.confirm(`هل أنت متأكد من الدخول كمدير لعيادة: ${tenant.clinicName}؟`)) {
          // Set the clinic type to match the tenant
          setClinicType(tenant.clinicType);
          addToast(`تم الدخول بنجاح إلى لوحة تحكم ${tenant.clinicName}`, 'success');
          // Navigate to the doctor dashboard
          navigate('/doctor/dashboard');
      }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    
    // Basic Info
    const name = (form.elements.namedItem('name') as HTMLInputElement).value;
    const clinicName = (form.elements.namedItem('clinicName') as HTMLInputElement).value;
    const clinicType = (form.elements.namedItem('clinicType') as HTMLSelectElement).value as ClinicType;
    const phone = (form.elements.namedItem('phone') as HTMLInputElement).value;
    const domainPrefix = (form.elements.namedItem('domain') as HTMLInputElement).value;
    const template = (form.elements.namedItem('template') as HTMLSelectElement).value;
    
    // Auth & Subscription
    const email = (form.elements.namedItem('email') as HTMLInputElement).value;
    const password = (form.elements.namedItem('password') as HTMLInputElement).value; // Captured for backend logic
    const duration = parseInt((form.elements.namedItem('duration') as HTMLInputElement).value);

    // Determine plan type based on duration logic
    const planType = duration >= 12 ? 'yearly' : 'monthly';

    if (name && clinicName && email) {
        if (editingTenant) {
            // Update existing
            const updatedTenant: Tenant = {
                ...editingTenant,
                name,
                email, // Update email
                clinicName,
                clinicType,
                phone,
                plan: planType,
                domain: domainPrefix.includes('.clinicpro.com') ? domainPrefix : `${domainPrefix}.clinicpro.com`,
                template
            };
            updateTenant(updatedTenant);
            addToast('تم تحديث بيانات المشترك بنجاح', 'success');
        } else {
            // Create new
            const newTenant: Tenant = {
                id: Date.now().toString(),
                name,
                email: email, 
                phone,
                clinicName,
                clinicType,
                plan: planType,
                status: SubscriptionStatus.ACTIVE,
                expiryDate: calculateExpiryDate(duration), // Use calculated date
                domain: `${domainPrefix}.clinicpro.com`,
                template,
                activationCode: generateActivationCode(),
                isActivated: false,
                syncStatus: 'online'
            };
            
            console.log(`Creating user: ${email} with password: ${password}`);

            addTenant(newTenant);
            addToast(`تم إنشاء العيادة. كود التفعيل هو: ${newTenant.activationCode}`, 'success');
        }
        closeModal();
    }
  };

  const openEditModal = (tenant: Tenant) => {
    setEditingTenant(tenant);
    // Rough estimate for months if editing
    setSubDuration(12); 
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setEditingTenant(null);
    setIsModalOpen(false);
    setSubDuration(12);
  };

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

  const copyCode = (code: string) => {
      navigator.clipboard.writeText(code);
      addToast('تم نسخ كود التفعيل', 'info');
  };

  const openSite = (domain: string) => {
      window.open(`/#/site/${domain}`, '_blank');
  };

  // Group templates by category for the select dropdown
  const activeTemplates = templates.filter(t => t.isActive);

  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={() => { setEditingTenant(null); 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="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="p-4 border-b border-gray-100 bg-gray-50 flex gap-4">
            <div className="relative flex-1 max-w-sm">
                <input 
                  type="text" 
                  placeholder="بحث..." 
                  className="w-full pl-4 pr-10 py-2 border border-gray-200 rounded-lg focus:outline-none focus:border-primary bg-white text-gray-900" 
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
                <i className="fas fa-search absolute left-3 top-3 text-gray-400"></i>
            </div>
            <select 
              className="px-4 py-2 border border-gray-200 rounded-lg bg-white text-gray-900 focus:outline-none focus:border-primary"
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
            >
                <option value="all">كل الحالات</option>
                <option value="active">نشط</option>
                <option value="expired">منتهي</option>
            </select>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">ID</th>
                <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">الاسم / العيادة</th>
                <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">بيانات الدخول</th>
                <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">كود التفعيل</th>
                <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">الحالة</th>
                <th className="px-6 py-4 text-center text-sm font-semibold text-gray-600">إجراءات</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {filteredTenants.map((tenant) => (
                <tr key={tenant.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4 text-sm text-gray-500">#{tenant.id}</td>
                  <td className="px-6 py-4 font-medium text-gray-800">
                    <div>{tenant.name}</div>
                    <div className="text-xs text-gray-500">{tenant.clinicName} ({tenant.clinicType})</div>
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-600" dir="ltr">
                      {tenant.email}
                  </td>
                  <td className="px-6 py-4">
                     <button 
                        onClick={() => copyCode(tenant.activationCode)}
                        className="bg-gray-100 hover:bg-gray-200 text-gray-700 font-mono px-2 py-1 rounded text-sm flex items-center gap-2 group"
                        title="نسخ الكود"
                     >
                        {tenant.activationCode}
                        <i className="fas fa-copy text-gray-400 group-hover:text-gray-600"></i>
                     </button>
                  </td>
                  <td className="px-6 py-4">
                     <div className="flex flex-col gap-1">
                        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium w-fit ${
                        tenant.status === SubscriptionStatus.ACTIVE 
                            ? 'bg-green-100 text-green-800' 
                            : 'bg-red-100 text-red-800'
                        }`}>
                        {tenant.status === SubscriptionStatus.ACTIVE ? 'اشتراك نشط' : 'منتهي'}
                        </span>
                        <span className={`text-[10px] font-bold ${tenant.isActivated ? 'text-blue-600' : 'text-orange-500'}`}>
                            {tenant.isActivated ? 'الموقع مفعل' : 'بانتظار التفعيل'}
                        </span>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-center">
                    <div className="flex justify-center gap-2">
                        <button onClick={() => openSite(tenant.domain)} className="w-8 h-8 rounded-lg text-gray-400 hover:text-blue-500 hover:bg-blue-50 transition-colors flex items-center justify-center" title="زيارة الموقع"><i className="fas fa-external-link-alt"></i></button>
                        
                        <button onClick={() => handleLoginAsTenant(tenant)} className="w-8 h-8 rounded-lg text-purple-500 bg-purple-50 hover:bg-purple-100 transition-colors flex items-center justify-center" title="دخول كمدير (Login as Admin)"><i className="fas fa-sign-in-alt"></i></button>

                        <button onClick={() => handleResetPassword(tenant.email)} className="w-8 h-8 rounded-lg text-gray-400 hover:text-yellow-500 hover:bg-yellow-50 transition-colors flex items-center justify-center" title="إعادة تعيين كلمة المرور"><i className="fas fa-key"></i></button>
                        
                        <button onClick={() => openEditModal(tenant)} className="w-8 h-8 rounded-lg text-gray-400 hover:text-primary hover:bg-blue-50 transition-colors flex items-center justify-center" title="تعديل"><i className="fas fa-edit"></i></button>
                        
                        <button onClick={() => handleDelete(tenant.id)} className="w-8 h-8 rounded-lg text-gray-400 hover:text-danger hover:bg-red-50 transition-colors flex items-center justify-center" title="حذف"><i className="fas fa-trash"></i></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add/Edit Tenant Modal */}
      <Modal isOpen={isModalOpen} onClose={closeModal} title={editingTenant ? "تعديل بيانات المشترك" : "إضافة مشترك جديد (بيع نسخة)"}>
        <form className="space-y-4" onSubmit={handleSubmit}>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="md:col-span-2">
                    <label className="block text-sm font-medium text-gray-700 mb-1">اسم العميل (الطبيب/المدير)</label>
                    <input 
                        name="name" 
                        type="text" 
                        defaultValue={editingTenant?.name}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" 
                        required 
                    />
                </div>
                
                {/* Auth Section */}
                <div className="md:col-span-2 bg-blue-50 p-3 rounded-xl border border-blue-100">
                    <h4 className="text-xs font-bold text-blue-800 mb-2 uppercase flex items-center gap-1">
                        <i className="fas fa-lock"></i> بيانات تسجيل الدخول
                    </h4>
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-xs font-bold text-gray-600 mb-1">البريد الإلكتروني</label>
                            <input 
                                name="email" 
                                type="email" 
                                defaultValue={editingTenant?.email}
                                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" 
                                dir="ltr"
                                required 
                            />
                        </div>
                        <div>
                            <label className="block text-xs font-bold text-gray-600 mb-1">كلمة المرور</label>
                            <input 
                                name="password" 
                                type="password" 
                                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={editingTenant ? "اتركه فارغاً للإبقاء" : ""}
                                required={!editingTenant}
                            />
                        </div>
                    </div>
                    {editingTenant && (
                        <div className="mt-3 text-right">
                            <button 
                                type="button" 
                                onClick={() => handleResetPassword(editingTenant.email)}
                                className="text-xs text-blue-600 hover:text-blue-800 hover:underline flex items-center justify-end gap-1 w-full"
                            >
                                <i className="fas fa-key"></i> إرسال رابط إعادة تعيين كلمة المرور
                            </button>
                        </div>
                    )}
                </div>

                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">اسم العيادة</label>
                    <input 
                        name="clinicName" 
                        type="text" 
                        defaultValue={editingTenant?.clinicName}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" 
                        required 
                    />
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">نوع العيادة</label>
                    <select 
                        name="clinicType" 
                        defaultValue={editingTenant?.clinicType || 'general'}
                        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="general">طب عام</option>
                        <option value="dental">أسنان</option>
                        <option value="obgyn">نسائية وتوليد</option>
                        <option value="vet">بيطري</option>
                        <option value="ophthalmology">عيون</option>
                        <option value="orthopedics">عظام</option>
                        <option value="surgery">جراحة</option>
                        <option value="pediatrics">أطفال</option>
                        <option value="neurology">أعصاب</option>
                        <option value="dermatology">جلدية</option>
                        <option value="obstetrics">توليد</option>
                    </select>
                </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">رقم الهاتف</label>
                    <input 
                        name="phone" 
                        type="tel" 
                        defaultValue={editingTenant?.phone}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" 
                        required 
                    />
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">الدومين الفرعي</label>
                    <div className="flex text-sm border border-gray-300 rounded-lg overflow-hidden bg-white">
                        <input 
                            name="domain" 
                            type="text" 
                            defaultValue={editingTenant?.domain.split('.clinicpro')[0]}
                            className="w-full px-3 py-2 focus:outline-none bg-white text-gray-900" 
                            dir="ltr" 
                            required 
                        />
                        <span className="bg-gray-100 px-2 py-2 text-gray-500 border-r border-gray-300 text-xs flex items-center">.clinicpro.com</span>
                    </div>
                </div>
            </div>

            {/* Subscription Duration */}
            <div className="bg-green-50 p-3 rounded-xl border border-green-100">
                <div className="flex justify-between items-center mb-2">
                    <label className="text-sm font-bold text-green-800">مدة الاشتراك</label>
                    <span className="text-xs bg-white px-2 py-1 rounded border text-green-700 font-mono">
                        ينتهي في: {calculateExpiryDate(subDuration)}
                    </span>
                </div>
                <div className="flex items-center gap-3">
                    <input 
                        type="number" 
                        name="duration"
                        min="1"
                        max="60"
                        value={subDuration}
                        onChange={(e) => setSubDuration(parseInt(e.target.value) || 1)}
                        className="w-20 px-3 py-2 border border-green-300 rounded-lg focus:ring-green-500 focus:border-green-500 text-center font-bold text-gray-900 bg-white"
                    />
                    <span className="text-gray-600 font-medium">أشهر</span>
                    
                    <div className="flex-1 flex gap-2 justify-end">
                        <button type="button" onClick={() => setSubDuration(1)} className="text-xs bg-white border px-2 py-1 rounded hover:bg-gray-50">1 شهر</button>
                        <button type="button" onClick={() => setSubDuration(6)} className="text-xs bg-white border px-2 py-1 rounded hover:bg-gray-50">6 أشهر</button>
                        <button type="button" onClick={() => setSubDuration(12)} className="text-xs bg-white border px-2 py-1 rounded hover:bg-gray-50">1 سنة</button>
                    </div>
                </div>
            </div>

            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">القالب المختار</label>
                <select 
                    name="template" 
                    defaultValue={editingTenant?.template}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900"
                >
                    <optgroup label="طب عام">
                        {activeTemplates.filter(t => t.category === 'طب عام').map(t => (
                            <option key={t.id} value={t.id}>{t.name}</option>
                        ))}
                    </optgroup>
                    <optgroup label="أسنان">
                        {activeTemplates.filter(t => t.category === 'أسنان').map(t => (
                            <option key={t.id} value={t.id}>{t.name}</option>
                        ))}
                    </optgroup>
                    <optgroup label="نسائية وتوليد">
                        {activeTemplates.filter(t => t.category === 'نسائية').map(t => (
                            <option key={t.id} value={t.id}>{t.name}</option>
                        ))}
                    </optgroup>
                     <optgroup label="أخرى">
                        {activeTemplates.filter(t => !['طب عام', 'أسنان', 'نسائية'].includes(t.category)).map(t => (
                            <option key={t.id} value={t.id}>{t.name}</option>
                        ))}
                    </optgroup>
                </select>
            </div>
            
            <div className="border-t pt-4 mt-2">
                <button type="submit" className="w-full bg-primary text-white py-3 rounded-xl font-bold hover:bg-primary-dark transition-colors shadow-lg flex justify-center items-center gap-2">
                    <i className="fas fa-check-circle"></i>
                    {editingTenant ? 'حفظ التعديلات' : 'إتمام البيع وتفعيل النسخة'}
                </button>
            </div>
        </form>
      </Modal>
    </div>
  );
};
