
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { StatCard } from '../../components/StatCard';
import { useData } from '../../context/DataContext';
import { SubscriptionStatus } from '../../types';
import { useToast } from '../../context/ToastContext';

export const AdminDashboard: React.FC = () => {
  const { tenants, updateTenant } = useData();
  const navigate = useNavigate();
  const { addToast } = useToast();

  const totalTenants = tenants.length;
  const activeTenants = tenants.filter(t => t.status === SubscriptionStatus.ACTIVE).length;
  const expiredTenants = tenants.filter(t => t.status === SubscriptionStatus.EXPIRED).length;
  const totalRevenue = activeTenants * 10000; // Simulated revenue

  const handleToggleStatus = (id: string, currentStatus: SubscriptionStatus) => {
      const tenant = tenants.find(t => t.id === id);
      if (tenant) {
          const newStatus = currentStatus === SubscriptionStatus.ACTIVE ? SubscriptionStatus.EXPIRED : SubscriptionStatus.ACTIVE;
          updateTenant({ ...tenant, status: newStatus });
          addToast(newStatus === SubscriptionStatus.ACTIVE ? 'تم تفعيل حساب المشترك' : 'تم إيقاف حساب المشترك', 'info');
      }
  };

  return (
    <div className="space-y-6">
      <header 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={() => navigate('/admin/tenants')}
            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>
      </header>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard title="إجمالي المشتركين" value={totalTenants} icon="fa-users" color="primary" trend="+5 هذا الشهر" />
        <StatCard title="الاشتراكات النشطة" value={activeTenants} icon="fa-check-circle" color="success" />
        <StatCard title="الاشتراكات المنتهية" value={expiredTenants} icon="fa-exclamation-circle" color="danger" />
        <StatCard title="الدخل المتوقع" value={`${totalRevenue.toLocaleString()} $`} icon="fa-wallet" color="warning" trend="+12% نمو" />
      </div>

      {/* Recent Subscribers Table */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="p-6 border-b border-gray-100 flex justify-between items-center">
          <h3 className="text-lg font-bold text-gray-800">آخر المشتركين</h3>
          <button 
            onClick={() => navigate('/admin/tenants')}
            className="text-primary text-sm font-semibold hover:underline"
          >
              عرض الكل
          </button>
        </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">العميل</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>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {tenants.slice(0, 5).map((tenant) => (
                <tr key={tenant.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-primary font-bold">
                        {tenant.name.charAt(0)}
                      </div>
                      <div>
                        <p className="font-semibold text-gray-800">{tenant.name}</p>
                        <p className="text-xs text-gray-500">{tenant.clinicName}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
                      {tenant.plan === 'yearly' ? 'سنوي' : 'شهري'}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                      tenant.status === SubscriptionStatus.ACTIVE 
                        ? 'bg-green-100 text-green-800' 
                        : 'bg-red-100 text-red-800'
                    }`}>
                      {tenant.status === SubscriptionStatus.ACTIVE ? 'نشط' : 'منتهي'}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-600">{tenant.expiryDate}</td>
                  <td className="px-6 py-4">
                    <div className="flex gap-2">
                      <button 
                        onClick={() => navigate('/admin/tenants')}
                        className="w-8 h-8 rounded-lg bg-gray-100 text-gray-600 hover:bg-primary hover:text-white flex items-center justify-center transition-colors"
                        title="تعديل في صفحة المشتركين"
                      >
                        <i className="fas fa-edit"></i>
                      </button>
                      <button 
                        onClick={() => handleToggleStatus(tenant.id, tenant.status)}
                        className={`w-8 h-8 rounded-lg flex items-center justify-center transition-colors ${
                            tenant.status === SubscriptionStatus.ACTIVE 
                            ? 'bg-red-50 text-danger hover:bg-danger hover:text-white' 
                            : 'bg-green-50 text-success hover:bg-success hover:text-white'
                        }`}
                        title={tenant.status === SubscriptionStatus.ACTIVE ? 'إيقاف' : 'تفعيل'}
                      >
                        <i className={`fas ${tenant.status === SubscriptionStatus.ACTIVE ? 'fa-ban' : 'fa-check'}`}></i>
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};
