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

interface SidebarProps {
  role: UserRole;
  isOpen: boolean;
  activePage: string;
  onNavigate: (page: string) => void;
  onLogout: () => void;
  onCloseMobile: () => void;
}

export const Sidebar: React.FC<SidebarProps> = ({ role, isOpen, activePage, onNavigate, onLogout, onCloseMobile }) => {
  const { clinicType, modules, dynamicPages } = useData();
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  // Monitor Network Status
  useEffect(() => {
    const handleOnline = () => setIsOnline(true);
    const handleOffline = () => setIsOnline(false);

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  const adminLinks = [
    { id: 'admin-dashboard', label: 'لوحة القيادة', icon: 'fa-chart-line' },
    { id: 'admin-reports', label: 'التقارير', icon: 'fa-chart-pie' },
    { id: 'admin-tenants', label: 'إدارة المشتركين', icon: 'fa-users-cog' },
    { id: 'admin-plans', label: 'الاشتراكات', icon: 'fa-money-bill-wave' },
    { id: 'admin-templates', label: 'قوالب المواقع', icon: 'fa-layer-group' },
    { id: 'admin-form-builder', label: 'منشئ النماذج', icon: 'fa-tasks' },
    { id: 'admin-features', label: 'إدارة الميزات', icon: 'fa-toggle-on' },
    { id: 'admin-roles', label: 'الصلاحيات', icon: 'fa-user-lock' },
    { id: 'admin-support', label: 'الدعم الفني', icon: 'fa-headset' },
    { id: 'admin-audit', label: 'سجل النشاطات', icon: 'fa-shield-alt' },
    { id: 'admin-settings', label: 'الإعدادات العامة', icon: 'fa-cogs' },
  ];

  let doctorLinks: any[] = [];

  // Base Dashboard
  doctorLinks.push({ id: 'doctor-dashboard', label: 'الرئيسية', icon: 'fa-th-large' });

  // Standard Modules
  doctorLinks.push({ id: 'doctor-patients', label: 'سجل المرضى', icon: 'fa-users' });
  doctorLinks.push({ id: 'doctor-appointments', label: 'المواعيد', icon: 'fa-calendar-alt' });
  
  // New Modules
  doctorLinks.push({ id: 'doctor-prescriptions', label: 'الوصفات الطبية', icon: 'fa-file-prescription' });
  doctorLinks.push({ id: 'doctor-reports', label: 'التقارير الطبية', icon: 'fa-file-medical-alt' });
  doctorLinks.push({ id: 'doctor-inventory', label: 'المخزون', icon: 'fa-boxes' });
  doctorLinks.push({ id: 'doctor-staff', label: 'طاقم العمل', icon: 'fa-user-nurse' });

  // 1. Dynamic Modules (Filtered by clinic type and enabled status)
  const myModules = modules.filter(m => m.isEnabled && m.clinicTypes.includes(clinicType));
  
  myModules.forEach(mod => {
      // Avoid duplicates for base modules
      if (['patients', 'appointments'].includes(mod.key)) return;

      // Map legacy keys to routes or use generic structure
      let route = `doctor-${mod.key}`;
      if(mod.key === 'dental_chart') route = 'dental-lab'; // Or chart
      if(mod.key === 'pregnancy') route = 'birth-log';
      if(mod.key === 'lab') route = 'dental-lab';

      // Use module label (custom or default)
      doctorLinks.push({ 
          id: route, 
          label: mod.customName || mod.defaultName, 
          icon: mod.icon 
      });
  });

  // 2. Dynamic Custom Pages
  const myPages = dynamicPages
        .filter(p => p.isVisible && (p.clinicType === 'all' || p.clinicType === clinicType))
        .sort((a, b) => a.order - b.order);

  myPages.forEach(page => {
      doctorLinks.push({
          id: `page-${page.id}`,
          label: page.title,
          icon: page.icon,
          isDynamic: true // Flag to handle routing differently
      });
  });

  // 3. Fixed Bottom Links
  doctorLinks.push({ id: 'doctor-field-manager', label: 'إدارة الحقول', icon: 'fa-list-alt' });
  doctorLinks.push({ id: 'doctor-site-editor', label: 'محرر الموقع', icon: 'fa-edit' });
  doctorLinks.push({ id: 'doctor-forms', label: 'تخصيص النماذج', icon: 'fa-sliders-h' });
  doctorLinks.push({ id: 'doctor-finance', label: 'المحاسبة', icon: 'fa-wallet' });
  doctorLinks.push({ id: 'doctor-settings', label: 'إعدادات العيادة', icon: 'fa-clinic-medical' });


  const links = role === UserRole.SUPER_ADMIN ? adminLinks : doctorLinks;

  // Theme Configuration based on ClinicType
  const getTheme = () => {
    if (role === UserRole.SUPER_ADMIN) return { bg: 'bg-dark', text: 'text-white', icon: 'fa-shield-alt', active: 'bg-primary' };
    switch (clinicType) {
        case 'dental': return { bg: 'bg-emerald-600', text: 'text-white', icon: 'fa-tooth', active: 'bg-white/20' };
        case 'obgyn': return { bg: 'bg-rose-500', text: 'text-white', icon: 'fa-baby', active: 'bg-white/20' };
        case 'vet': return { bg: 'bg-amber-600', text: 'text-white', icon: 'fa-paw', active: 'bg-white/20' };
        case 'ophthalmology': return { bg: 'bg-indigo-600', text: 'text-white', icon: 'fa-eye', active: 'bg-white/20' };
        default: return { bg: 'bg-primary', text: 'text-white', icon: 'fa-stethoscope', active: 'bg-white/20' };
    }
  };
  
  const theme = getTheme();

  return (
    <>
      {/* Mobile Overlay */}
      <div 
        className={`fixed inset-0 bg-black bg-opacity-50 z-20 lg:hidden transition-opacity ${isOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}
        onClick={onCloseMobile}
      ></div>

      {/* Sidebar Content */}
      <aside className={`fixed top-0 right-0 h-full w-64 bg-white shadow-lg z-30 transform transition-transform duration-300 lg:translate-x-0 lg:static ${isOpen ? 'translate-x-0' : 'translate-x-full'}`}>
        <div className="flex flex-col h-full">
          {/* Header */}
          <div className={`${theme.bg} p-6 flex justify-center items-center flex-col text-white transition-colors duration-300 relative overflow-hidden`}>
            
            {/* Real Network Sync Status */}
            <div className={`absolute top-2 left-2 flex items-center gap-1 px-2 py-0.5 rounded text-[10px] shadow-sm font-bold ${isOnline ? 'bg-green-500 text-white' : 'bg-red-500 text-white animate-pulse'}`}>
                <div className={`w-2 h-2 rounded-full bg-white`}></div>
                <span>{isOnline ? 'متصل' : 'أوفلاين'}</span>
            </div>

            <div className="w-14 h-14 bg-white/20 backdrop-blur-sm rounded-full flex items-center justify-center text-white text-2xl mb-3 shadow-inner border border-white/30">
              <i className={`fas ${theme.icon}`}></i>
            </div>
            <h1 className="text-lg font-bold tracking-wide text-center leading-tight">
              {role === UserRole.SUPER_ADMIN ? 'لوحة خالد قصرين' : 'نظام خالد قصرين'}
            </h1>
            <span className="text-xs text-white/80 mt-1 font-medium bg-black/10 px-2 py-0.5 rounded-full uppercase">
                {role === UserRole.SUPER_ADMIN ? 'الإدارة العليا' : clinicType}
            </span>
          </div>

          <nav className="flex-1 p-4 overflow-y-auto">
            <ul className="space-y-2">
              {links.map((link) => (
                <li key={link.id}>
                  <button
                    onClick={() => {
                      onNavigate(link.id);
                      onCloseMobile();
                    }}
                    className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 ${
                      activePage === link.id || (link.isDynamic && activePage.includes(link.id))
                        ? `${theme.bg} text-white shadow-md transform scale-105` 
                        : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'
                    }`}
                  >
                    <i className={`fas ${link.icon} w-5 text-center`}></i>
                    <span className="font-semibold">{link.label}</span>
                  </button>
                </li>
              ))}
            </ul>
          </nav>

          <div className="p-4 border-t border-gray-100">
            <button 
              onClick={onLogout}
              className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-gray-50 text-gray-600 rounded-xl hover:bg-red-50 hover:text-danger transition-colors font-medium group"
            >
              <i className="fas fa-sign-out-alt group-hover:rotate-180 transition-transform duration-300"></i>
              <span>تسجيل الخروج</span>
            </button>
          </div>
        </div>
      </aside>
    </>
  );
};
