'use client';

import { useState, useRef, useEffect, useCallback } from 'react';
import DashboardShell from '../components/DashboardShell';
import { useApi } from '@/hooks/useApi';

// ─── Types ────────────────────────────────────────────────────────────────────

interface SubscriberListItem {
  id: number;
  display_code: string;
  status: 'active' | 'inactive' | 'suspended';
  start_date: string;
  end_date: string;
  week_days: string[];
  price: number;
  user: { id: number; name: string; phone: string; image: string } | null;
  path: { id: number; description: string; bus: { id: number; display_code: string; plate: string } };
  plan: { id: number; name: string; duration_type: string; duration_days: number };
}

interface SubscriberDetail {
  id: number;
  status: string;
  payment_status: string;
  start_date: string;
  end_date: string;
  week_days: string[];
  price: number;
  user: { id: number; name: string; phone: string; country_code: string; image: string } | null;
  path: { id: number; description: string; bus: { id: number; plate: string; capacity: number } };
  plan: { id: number; name: string; duration_days: number };
  pickup_station: { id: number; address: string; lat: number; lng: number; city: { id: number; name: string } };
  drop_station: { id: number; address: string; lat: number; lng: number; city: { id: number; name: string } };
  created_at: string;
}

interface PaginationMeta {
  total_items: number;
  count_items: number;
  per_page: number;
  total_pages: number;
  current_page: number;
  next_page_url: string;
  perv_page_url: string;
}

interface ListResponse {
  key: string;
  msg: string;
  data: {
    data: SubscriberListItem[];
    pagination: PaginationMeta;
  };
}

interface DetailResponse {
  key: string;
  msg: string;
  data: SubscriberDetail;
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

const STATUS_MAP: Record<string, { label: string; color: string; bg: string }> = {
  active:    { label: 'نشط',     color: '#059669', bg: '#DCFCE7' },
  inactive:  { label: 'منتهي',  color: '#EF4444', bg: '#FEE2E2' },
  suspended: { label: 'معلق',   color: '#D97706', bg: '#FEF3C7' },
};

const WEEK_DAY_MAP: Record<string, string> = {
  sun: 'الأحد', mon: 'الإثنين', tue: 'الثلاثاء',
  wed: 'الأربعاء', thu: 'الخميس', fri: 'الجمعة', sat: 'السبت',
};

const ALL_WEEK_DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];

function fmtDate(iso: string) {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleDateString('ar-SA', { year: 'numeric', month: 'long', day: 'numeric' });
}

function avatarFallback(name: string) {
  return name?.charAt(0) ?? '?';
}

// ─── Skeleton Row ─────────────────────────────────────────────────────────────

function SkeletonRow() {
  return (
    <tr className="border-t animate-pulse" style={{ borderColor: '#F8FAFC' }}>
      {[120, 90, 130, 130, 80, 70, 100, 70, 60].map((w, i) => (
        <td key={i} className="px-5 py-4">
          <div className="h-3 rounded-full bg-slate-100" style={{ width: w }} />
          {i === 0 && <div className="h-2.5 rounded-full bg-slate-100 mt-2" style={{ width: 60 }} />}
        </td>
      ))}
    </tr>
  );
}

// ─── Detail Modal ─────────────────────────────────────────────────────────────

function DetailModal({ subscriberId, onClose }: { subscriberId: number; onClose: () => void }) {
  const { data, loading, error, request } = useApi<DetailResponse>();

  useEffect(() => {
    request(`/subscribers/${subscriberId}`);
  }, [subscriberId]);

  const sub = data?.data;
  const statusInfo = sub ? (STATUS_MAP[sub.status] ?? { label: sub.status, color: '#64748b', bg: '#F1F5F9' }) : null;

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6" onClick={onClose}>
      <div className="bg-white rounded-3xl p-7 w-full max-w-md shadow-2xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-5">
          <h2 className="text-lg font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>بيانات المشترك</h2>
          <button onClick={onClose} className="w-9 h-9 bg-slate-100 rounded-xl flex items-center justify-center cursor-pointer">
            <i className="ri-close-line text-slate-500 text-lg" />
          </button>
        </div>

        {loading && (
          <div className="space-y-4 animate-pulse">
            <div className="flex items-center gap-4 p-4 rounded-2xl bg-slate-50">
              <div className="w-16 h-16 rounded-2xl bg-slate-200 flex-shrink-0" />
              <div className="flex-1 space-y-2">
                <div className="h-4 bg-slate-200 rounded-full w-3/4" />
                <div className="h-3 bg-slate-100 rounded-full w-1/3" />
              </div>
            </div>
            {[1,2,3,4,5,6].map(i => (
              <div key={i} className="flex items-center gap-3">
                <div className="w-8 h-8 rounded-xl bg-slate-100 flex-shrink-0" />
                <div className="flex-1 space-y-1">
                  <div className="h-2.5 bg-slate-100 rounded-full w-1/4" />
                  <div className="h-3.5 bg-slate-200 rounded-full w-1/2" />
                </div>
              </div>
            ))}
          </div>
        )}

        {error && (
          <div className="text-center py-8">
            <div className="w-12 h-12 rounded-2xl bg-red-50 flex items-center justify-center mx-auto mb-3">
              <i className="ri-error-warning-line text-red-400 text-xl" />
            </div>
            <p className="text-sm text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{error}</p>
          </div>
        )}

        {sub && statusInfo && (
          <>
            <div className="flex items-center gap-4 mb-5 p-4 rounded-2xl" style={{ background: '#F8FAFC' }}>
              {sub.user?.image ? (
                <img src={sub.user.image} alt={sub.user?.name ?? 'مستخدم غير متاح'} className="w-16 h-16 rounded-2xl object-cover object-top flex-shrink-0" />
              ) : (
                <div className="w-16 h-16 rounded-2xl flex items-center justify-center flex-shrink-0 text-2xl font-black text-white" style={{ background: '#1E3A8A' }}>
                  {avatarFallback(sub.user?.name ?? 'مستخدم غير متاح')}
                </div>
              )}
              <div>
                <p className="text-lg font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{sub.user?.name ?? 'مستخدم غير متاح'}</p>
                <p className="text-sm text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>#{sub.id}</p>
                <span className="inline-block mt-1 px-2.5 py-0.5 rounded-full text-xs font-bold" style={{ background: statusInfo.bg, color: statusInfo.color, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                  {statusInfo.label}
                </span>
              </div>
            </div>

            <div className="space-y-3">
              {/* Pickup station */}
              <div className="flex items-start gap-3 p-3 rounded-xl" style={{ background: '#F0FDF4', border: '1px solid #BBF7D0' }}>
                <div className="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#DCFCE7' }}>
                  <i className="ri-map-pin-2-fill text-sm" style={{ color: '#059669' }} />
                </div>
                <div className="flex-1">
                  <p className="text-[10px] text-slate-400 mb-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>محطة الصعود</p>
                  <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{sub.pickup_station.address}</p>
                  <p className="text-xs text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{sub.pickup_station.city.name}</p>
                </div>
              </div>

              {/* Drop station */}
              <div className="flex items-start gap-3 p-3 rounded-xl" style={{ background: '#FFF1F2', border: '1px solid #FECDD3' }}>
                <div className="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#FEE2E2' }}>
                  <i className="ri-map-pin-fill text-sm" style={{ color: '#EF4444' }} />
                </div>
                <div className="flex-1">
                  <p className="text-[10px] text-slate-400 mb-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>محطة النزول</p>
                  <p className="text-sm font-bold text-slate-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{sub.drop_station.address}</p>
                  <p className="text-xs text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{sub.drop_station.city.name}</p>
                </div>
              </div>

              {[
                { icon: 'ri-phone-line',             label: 'الجوال',          val: sub.user ? `+${sub.user.country_code} ${sub.user.phone}` : 'غير متاح' },
                { icon: 'ri-bus-2-line',             label: 'الباص',           val: `${sub.path.bus.plate} — ${sub.path.description}` },
                { icon: 'ri-vip-crown-line',         label: 'خطة الاشتراك',    val: sub.plan.name },
                { icon: 'ri-money-dollar-circle-line', label: 'المبلغ',         val: `${sub.price} ر.س` },
                { icon: 'ri-calendar-line',          label: 'تاريخ البداية',   val: fmtDate(sub.start_date) },
                { icon: 'ri-calendar-check-line',    label: 'تاريخ الانتهاء',  val: fmtDate(sub.end_date) },
                { icon: 'ri-shield-check-line',      label: 'حالة الدفع',      val: sub.payment_status === 'paid' ? 'مدفوع' : sub.payment_status },
              ].map((row, i) => (
                <div key={i} className="flex items-center gap-3">
                  <div className="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#EEF2FF' }}>
                    <i className={`${row.icon} text-sm`} style={{ color: '#1E3A8A' }} />
                  </div>
                  <div>
                    <p className="text-[10px] text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{row.label}</p>
                    <p className="text-sm text-slate-700 font-semibold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{row.val}</p>
                  </div>
                </div>
              ))}

              {/* Week days */}
              <div className="flex items-start gap-3">
                <div className="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#EEF2FF' }}>
                  <i className="ri-calendar-2-line text-sm" style={{ color: '#1E3A8A' }} />
                </div>
                <div>
                  <p className="text-[10px] text-slate-400 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>أيام الاشتراك</p>
                  <div className="flex flex-wrap gap-1.5">
                    {sub.week_days.map(d => (
                      <span key={d} className="px-2 py-0.5 rounded-full text-[10px] font-bold" style={{ background: '#EEF2FF', color: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {WEEK_DAY_MAP[d] ?? d}
                      </span>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className="flex gap-3 mt-6">
              <button className="flex-1 h-10 bg-slate-100 rounded-xl font-bold text-sm text-slate-600 cursor-pointer" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }} onClick={onClose}>إغلاق</button>
              <button className="flex-1 h-10 rounded-xl font-bold text-sm text-white cursor-pointer" style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تجديد الاشتراك</button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ─── Edit Modal ───────────────────────────────────────────────────────────────

function EditModal({
  sub,
  onClose,
  onSaved,
}: {
  sub: SubscriberListItem;
  onClose: () => void;
  onSaved: () => void;
}) {
  const { loading, error, request } = useApi();
  const userName = sub.user?.name ?? 'مستخدم غير متاح';

  const [endDate, setEndDate]     = useState(sub.end_date ? sub.end_date.slice(0, 10) : '');
  const [weekDays, setWeekDays]   = useState<string[]>(sub.week_days ?? []);
  const [formError, setFormError] = useState('');

  const toggleDay = (d: string) =>
    setWeekDays(prev => prev.includes(d) ? prev.filter(x => x !== d) : [...prev, d]);

  const handleSave = async () => {
    if (!endDate && weekDays.length === 0) {
      setFormError('يجب تحديد تاريخ الانتهاء أو أيام الأسبوع على الأقل');
      return;
    }
    setFormError('');

    const body: Record<string, unknown> = {};
    if (endDate)            body['end_date']   = endDate;
    if (weekDays.length > 0) body['week_days[]'] = weekDays;

    // Build FormData so array params are sent correctly
    const fd = new FormData();
    if (endDate) fd.append('end_date', endDate);
    weekDays.forEach(d => fd.append('week_days[]', d));

    const res = await request(`/subscribers/${sub.id}/update`, { method: 'POST', body: fd });
    if (res !== null) onSaved();
  };

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-6" onClick={onClose}>
      <div className="bg-white rounded-3xl p-7 w-full max-w-md shadow-2xl" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-6">
          <div>
            <h2 className="text-lg font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>تعديل بيانات المشترك</h2>
            <p className="text-xs text-slate-400 mt-0.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{userName} — {sub.display_code}</p>
          </div>
          <button onClick={onClose} className="w-9 h-9 bg-slate-100 rounded-xl flex items-center justify-center cursor-pointer">
            <i className="ri-close-line text-slate-500 text-lg" />
          </button>
        </div>

        <div className="space-y-5">
          {/* End date */}
          <div>
            <label className="block text-sm font-bold text-slate-600 mb-1.5" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
              تاريخ الانتهاء
            </label>
            <input
              type="date"
              value={endDate}
              onChange={e => setEndDate(e.target.value)}
              className="w-full h-11 bg-slate-50 border border-slate-200 rounded-xl px-4 text-sm outline-none text-slate-700"
              style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            />
          </div>

          {/* Week days */}
          <div>
            <label className="block text-sm font-bold text-slate-600 mb-2" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
              أيام الاشتراك
            </label>
            <div className="flex flex-wrap gap-2">
              {ALL_WEEK_DAYS.map(d => {
                const active = weekDays.includes(d);
                return (
                  <button
                    key={d}
                    type="button"
                    onClick={() => toggleDay(d)}
                    className="px-3 py-2 rounded-xl text-xs font-bold cursor-pointer transition-all"
                    style={{
                      background: active ? '#1E3A8A' : '#F1F5F9',
                      color: active ? 'white' : '#64748b',
                      border: `1px solid ${active ? '#1E3A8A' : '#E2E8F0'}`,
                      fontFamily: '"IBM Plex Sans Arabic", sans-serif',
                    }}
                  >
                    {WEEK_DAY_MAP[d]}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Preview route */}
          <div className="bg-blue-50 rounded-xl px-4 py-3 flex items-center gap-2" style={{ border: '1px solid #BFDBFE' }}>
            <i className="ri-route-line text-xs flex-shrink-0" style={{ color: '#1E3A8A' }} />
            <span className="text-xs font-bold text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
              {sub.path.description}
            </span>
          </div>

          {(formError || error) && (
            <p className="text-xs text-red-500 font-semibold" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
              {formError || error}
            </p>
          )}
        </div>

        <div className="flex gap-3 mt-6">
          <button onClick={onClose} className="flex-1 h-11 bg-slate-100 rounded-xl font-bold text-sm text-slate-600 cursor-pointer" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>إلغاء</button>
          <button
            onClick={handleSave}
            disabled={loading}
            className="flex-1 h-11 rounded-xl font-bold text-sm text-white cursor-pointer flex items-center justify-center gap-2"
            style={{ background: '#1E3A8A', fontFamily: '"IBM Plex Sans Arabic", sans-serif', opacity: loading ? 0.7 : 1 }}
          >
            {loading && <i className="ri-loader-4-line animate-spin text-base" />}
            {loading ? 'جاري الحفظ...' : 'حفظ التعديلات'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Pagination ───────────────────────────────────────────────────────────────

function Pagination({ meta, onPageChange }: { meta: PaginationMeta; onPageChange: (p: number) => void }) {
  const { current_page, total_pages, total_items, per_page } = meta;
  if (total_pages <= 1) return null;

  const pages: (number | '...')[] = [];
  if (total_pages <= 7) {
    for (let i = 1; i <= total_pages; i++) pages.push(i);
  } else {
    pages.push(1);
    if (current_page > 3) pages.push('...');
    for (let i = Math.max(2, current_page - 1); i <= Math.min(total_pages - 1, current_page + 1); i++) pages.push(i);
    if (current_page < total_pages - 2) pages.push('...');
    pages.push(total_pages);
  }

  const from = (current_page - 1) * per_page + 1;
  const to   = Math.min(current_page * per_page, total_items);

  return (
    <div className="flex items-center justify-between mt-5 px-1">
      <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
        عرض {from}–{to} من {total_items} مشترك
      </p>
      <div className="flex items-center gap-1.5">
        <button
          onClick={() => onPageChange(current_page - 1)}
          disabled={current_page === 1}
          className="w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer transition-colors"
          style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', opacity: current_page === 1 ? 0.4 : 1 }}
        >
          <i className="ri-arrow-right-s-line text-slate-500 text-sm" />
        </button>
        {pages.map((p, i) =>
          p === '...' ? (
            <span key={`dots-${i}`} className="w-8 h-8 flex items-center justify-center text-xs text-slate-400">…</span>
          ) : (
            <button
              key={p}
              onClick={() => onPageChange(p as number)}
              className="w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold cursor-pointer transition-all"
              style={{
                background: p === current_page ? '#1E3A8A' : '#F8FAFC',
                color: p === current_page ? 'white' : '#475569',
                border: `1px solid ${p === current_page ? '#1E3A8A' : '#E2E8F0'}`,
                fontFamily: '"IBM Plex Sans Arabic", sans-serif',
              }}
            >
              {p}
            </button>
          )
        )}
        <button
          onClick={() => onPageChange(current_page + 1)}
          disabled={current_page === total_pages}
          className="w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer transition-colors"
          style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', opacity: current_page === total_pages ? 0.4 : 1 }}
        >
          <i className="ri-arrow-left-s-line text-slate-500 text-sm" />
        </button>
      </div>
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────

export default function SubscribersPage() {
  const [search, setSearch]           = useState('');
  const [statusFilter, setStatusFilter] = useState('الكل');
  const [planFilter, setPlanFilter]   = useState('الكل');
  const [currentPage, setCurrentPage] = useState(1);

  const [selectedId, setSelectedId]   = useState<number | null>(null);
  const [editSub, setEditSub]         = useState<SubscriberListItem | null>(null);
  const [successMsg, setSuccessMsg]   = useState('');

  const { data, loading, error, request } = useApi<ListResponse>();

  const subscribers  = data?.data?.data ?? [];
  const pagination   = data?.data?.pagination ?? null;
  const totalItems   = pagination?.total_items ?? 0;

  // ── stats derived from current page (full stats would need a separate endpoint)
  const activeCount   = subscribers.filter(s => s.status === 'active').length;
  const inactiveCount = subscribers.filter(s => s.status === 'inactive').length;
  const suspendedCount = subscribers.filter(s => s.status === 'suspended').length;

  const fetchSubscribers = useCallback(
    (page = 1) => {
      const params = new URLSearchParams({ paginate: '15', page: String(page) });
      if (statusFilter !== 'الكل') {
        const statusVal = statusFilter === 'نشط' ? 'active' : statusFilter === 'منتهي' ? 'inactive' : 'suspended';
        params.set('status', statusVal);
      }
      if (planFilter !== 'الكل') {
        const planVal = planFilter === 'شهري' ? 'monthly' : planFilter === 'فصلي' ? 'quarterly' : 'yearly';
        params.set('plan_type', planVal);
      }
      if (search.trim()) params.set('search', search.trim());
      request(`/subscribers?${params.toString()}`);
    },
    [request, statusFilter, planFilter, search],
  );

  // re-fetch whenever filters change (debounce search)
  useEffect(() => {
    const t = setTimeout(() => { setCurrentPage(1); fetchSubscribers(1); }, search ? 400 : 0);
    return () => clearTimeout(t);
  }, [search, statusFilter, planFilter]);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    fetchSubscribers(page);
  };

  const showSuccess = (msg: string) => {
    setSuccessMsg(msg);
    setTimeout(() => setSuccessMsg(''), 3000);
  };

  return (
    <DashboardShell title="إدارة المشتركين" subtitle={`${totalItems} مشترك مسجل`}>

      {/* Toast */}
      {successMsg && (
        <div className="fixed top-6 left-1/2 -translate-x-1/2 z-[100] px-6 py-3 rounded-2xl shadow-xl flex items-center gap-3" style={{ background: '#DCFCE7', border: '1px solid #86EFAC' }}>
          <i className="ri-checkbox-circle-fill text-green-600 text-lg" />
          <span className="text-sm font-bold text-green-800" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{successMsg}</span>
        </div>
      )}

      {/* Stats */}
      <div className="grid grid-cols-4 gap-4 mb-6">
        {[
          { label: 'إجمالي المشتركين', value: totalItems,      icon: 'ri-group-fill',         color: '#1E3A8A', bg: '#EEF2FF' },
          { label: 'اشتراكات نشطة',    value: activeCount,     icon: 'ri-checkbox-circle-fill', color: '#059669', bg: '#DCFCE7' },
          { label: 'منتهية الصلاحية',  value: inactiveCount,  icon: 'ri-time-fill',           color: '#EF4444', bg: '#FEE2E2' },
          { label: 'بانتظار التفعيل',  value: suspendedCount, icon: 'ri-loader-4-fill',       color: '#D97706', bg: '#FEF3C7' },
        ].map((s, i) => (
          <div key={i} className="bg-white rounded-2xl p-4 flex items-center gap-3" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
            <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: s.bg }}>
              <i className={`${s.icon} text-xl`} style={{ color: s.color }} />
            </div>
            <div>
              <p className="text-2xl font-black text-slate-900" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.value}</p>
              <p className="text-xs text-slate-500" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.label}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-3 flex-wrap">
          <div className="relative">
            <input
              type="text"
              placeholder="بحث بالاسم أو الجوال أو الرقم..."
              value={search}
              onChange={e => setSearch(e.target.value)}
              className="h-10 bg-white border border-slate-200 rounded-xl pr-10 pl-4 text-sm outline-none text-slate-700"
              style={{ width: '280px', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}
            />
            <div className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center">
              <i className="ri-search-line text-slate-400 text-sm" />
            </div>
          </div>

          {['الكل', 'نشط', 'منتهي', 'معلق'].map(s => (
            <button key={s} onClick={() => setStatusFilter(s)}
              className="px-3 py-2 rounded-xl text-xs font-bold cursor-pointer transition-all whitespace-nowrap"
              style={{ background: statusFilter === s ? '#1E3A8A' : 'white', color: statusFilter === s ? 'white' : '#64748b', border: `1px solid ${statusFilter === s ? '#1E3A8A' : '#E2E8F0'}`, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
              {s}
            </button>
          ))}

          {['الكل', 'شهري', 'فصلي', 'سنوي'].map(p => (
            <button key={p} onClick={() => setPlanFilter(p)}
              className="px-3 py-2 rounded-xl text-xs font-bold cursor-pointer transition-all whitespace-nowrap"
              style={{ background: planFilter === p ? '#0F172A' : 'white', color: planFilter === p ? 'white' : '#64748b', border: `1px solid ${planFilter === p ? '#0F172A' : '#E2E8F0'}`, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
              {p}
            </button>
          ))}
        </div>
      </div>

      {/* Table */}
      <div className="bg-white rounded-2xl overflow-hidden" style={{ border: '1px solid #F1F5F9', boxShadow: '0 1px 4px rgba(0,0,0,0.04)' }}>
        <table className="w-full">
          <thead>
            <tr style={{ background: '#F8FAFC' }}>
              {['المشترك', 'الجوال', 'المسار', 'الباص', 'الخطة', 'المبلغ', 'تاريخ الانتهاء', 'الحالة', ''].map(h => (
                <th key={h} className="text-right px-5 py-3 text-xs font-bold text-slate-500 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {loading
              ? Array.from({ length: 8 }).map((_, i) => <SkeletonRow key={i} />)
              : subscribers.length === 0
              ? (
                <tr>
                  <td colSpan={9} className="text-center py-16">
                    <div className="flex flex-col items-center gap-3">
                      <div className="w-14 h-14 rounded-2xl bg-slate-50 flex items-center justify-center">
                        <i className="ri-group-line text-2xl text-slate-300" />
                      </div>
                      <p className="text-sm text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {error ? error : 'لا توجد نتائج'}
                      </p>
                    </div>
                  </td>
                </tr>
              )
              : subscribers.map((s, i) => {
                const statusInfo = STATUS_MAP[s.status] ?? { label: s.status, color: '#64748b', bg: '#F1F5F9' };
                const userName = s.user?.name ?? 'مستخدم غير متاح';
                const userPhone = s.user?.phone ?? 'غير متاح';
                return (
                  <tr
                    key={s.id}
                    className="border-t hover:bg-slate-50 transition-colors cursor-pointer"
                    style={{ borderColor: '#F8FAFC' }}
                    onClick={() => setSelectedId(s.id)}
                  >
                    <td className="px-5 py-3.5">
                      <div className="flex items-center gap-3">
                        {s.user?.image ? (
                          <img src={s.user.image} alt={userName} className="w-9 h-9 rounded-xl object-cover object-top flex-shrink-0" />
                        ) : (
                          <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 text-sm font-black text-white" style={{ background: '#1E3A8A' }}>
                            {avatarFallback(userName)}
                          </div>
                        )}
                        <div>
                          <p className="text-sm font-bold text-slate-800 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{userName}</p>
                          <p className="text-xs text-slate-400" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.display_code}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-5 py-3.5"><span className="text-xs font-mono text-slate-600">{userPhone}</span></td>
                    <td className="px-5 py-3.5">
                      <p className="text-xs font-bold text-slate-700 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.path.description}</p>
                    </td>
                    <td className="px-5 py-3.5">
                      <span className="text-xs text-slate-500 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.path.bus.display_code}</span>
                    </td>
                    <td className="px-5 py-3.5">
                      <span className="px-2.5 py-1 rounded-full text-xs font-bold whitespace-nowrap" style={{ background: '#F1F5F9', color: '#475569', fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {s.plan.name}
                      </span>
                    </td>
                    <td className="px-5 py-3.5"><span className="text-xs font-bold text-slate-700" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{s.price} ر.س</span></td>
                    <td className="px-5 py-3.5"><span className="text-xs text-slate-500 whitespace-nowrap" style={{ fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>{fmtDate(s.end_date)}</span></td>
                    <td className="px-5 py-3.5">
                      <span className="px-2.5 py-1 rounded-full text-xs font-bold whitespace-nowrap" style={{ background: statusInfo.bg, color: statusInfo.color, fontFamily: '"IBM Plex Sans Arabic", sans-serif' }}>
                        {statusInfo.label}
                      </span>
                    </td>
                    <td className="px-5 py-3.5" onClick={e => e.stopPropagation()}>
                      <div className="flex items-center gap-1">
                        <button onClick={() => setEditSub(s)} className="w-7 h-7 rounded-lg flex items-center justify-center cursor-pointer hover:bg-blue-50">
                          <i className="ri-edit-line text-blue-400 text-sm" />
                        </button>
                        <button className="w-7 h-7 rounded-lg flex items-center justify-center cursor-pointer hover:bg-red-50">
                          <i className="ri-delete-bin-line text-red-400 text-sm" />
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })
            }
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {pagination && <Pagination meta={pagination} onPageChange={handlePageChange} />}

      {/* Detail Modal */}
      {selectedId !== null && (
        <DetailModal subscriberId={selectedId} onClose={() => setSelectedId(null)} />
      )}

      {/* Edit Modal */}
      {editSub && (
        <EditModal
          sub={editSub}
          onClose={() => setEditSub(null)}
          onSaved={() => {
            setEditSub(null);
            showSuccess('تم حفظ التعديلات بنجاح');
            fetchSubscribers(currentPage);
          }}
        />
      )}
    </DashboardShell>
  );
}