'use client';

import { useState, useEffect, useCallback } from 'react';
import { subscriptionService, type SubscriptionPlan, type Subscription, type SubscriptionStatus, type SubscriptionStats, type CreateSubscriptionPlanDto } from '@/services/subscription.service';
import { adminService } from '@/services/admin.service';
import type { UserProfile } from '@/types/admin.types';
import { getErrorMessage } from '@/lib/errors';
import { cn } from '@/lib/utils';
import { useSystemConfig } from '@/hooks/useSystemConfig';
import { TableSkeleton } from '@/components/priority/skeletons';
import { SortableTable, type SortableColumn } from '@/components/tables/SortableTable';
import EmptyState from '@/components/EmptyState';
import {
  Search, X, Plus, Pencil, Trash2, Eye, RefreshCw, CheckCircle2, XCircle, AlertTriangle,
  Package, Users, DollarSign, Clock, ArrowRightLeft,
} from 'lucide-react';

type Tab = 'plans' | 'subscriptions';
type PlanStatusFilter = 'ALL' | 'ACTIVE' | 'INACTIVE';
type SubStatusFilter = 'ALL' | SubscriptionStatus;

const SUB_STATUS_COLORS: Record<string, string> = {
  ACTIVE: 'bg-emerald-500/20 text-emerald-300',
  EXPIRED: 'bg-slate-500/20 text-slate-300',
  TERMINATED: 'bg-red-500/20 text-red-300',
  GRACE: 'bg-amber-500/20 text-amber-300',
  CANCELLED: 'bg-red-500/20 text-red-300',
};

function ConfirmDialog({
  title, description, confirmLabel, onConfirm, onClose, loading, reason, setReason,
}: {
  title: string;
  description: string;
  confirmLabel: string;
  onConfirm: (reason: string) => void;
  onClose: () => void;
  loading?: boolean;
  reason: string;
  setReason: (r: string) => void;
}) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={onClose}>
      <div className="w-full max-w-lg rounded-xl border border-white/10 bg-slate-900 shadow-2xl" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-white/10 p-5">
          <h2 className="text-lg font-semibold text-white">{title}</h2>
          <button onClick={onClose} className="rounded-lg p-1 text-slate-400 hover:text-white"><X className="h-5 w-5" /></button>
        </div>
        <div className="p-5 space-y-4">
          <p className="text-sm text-slate-400">{description}</p>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-300">Reason <span className="text-red-400">*</span></label>
            <textarea
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              placeholder="Provide a reason..."
              rows={3}
              className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none resize-none"
            />
          </div>
        </div>
        <div className="flex justify-end gap-3 border-t border-white/10 p-5">
          <button onClick={onClose} className="rounded-lg border border-white/10 px-4 py-2 text-sm text-slate-300 hover:bg-white/5">Cancel</button>
          <button onClick={() => onConfirm(reason)} disabled={Boolean(loading || !reason.trim())} className="rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white hover:bg-red-700 disabled:opacity-50">
            {loading ? 'Processing...' : confirmLabel}
          </button>
        </div>
      </div>
    </div>
  );
}

function PlanFormDialog({ plan, onClose, onSuccess }: { plan?: SubscriptionPlan; onClose: () => void; onSuccess: () => void }) {
  const sysConfig = useSystemConfig();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [form, setForm] = useState({
    name: plan?.name || '',
    description: plan?.description || '',
    price: plan?.price || '',
    currency: plan?.currency || sysConfig.currency,
    durationDays: plan?.durationDays || 30,
    gracePeriodDays: plan?.gracePeriodDays || 7,
    isActive: plan?.isActive ?? true,
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    if (!form.name || !form.price || !form.durationDays) {
      setError('Name, price, and duration are required');
      return;
    }
    setLoading(true);
    try {
      if (plan) {
        await subscriptionService.updateSubscriptionPlan(plan.id, form);
      } else {
        await subscriptionService.createSubscriptionPlan(form as CreateSubscriptionPlanDto);
      }
      onSuccess();
      onClose();
    } catch (err: any) {
      setError(getErrorMessage(err));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={onClose}>
      <div className="w-full max-w-lg rounded-xl border border-white/10 bg-slate-900 shadow-2xl" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-white/10 p-5">
          <h2 className="text-lg font-semibold text-white">{plan ? 'Edit Plan' : 'Create New Plan'}</h2>
          <button onClick={onClose} className="rounded-lg p-1 text-slate-400 hover:text-white"><X className="h-5 w-5" /></button>
        </div>
        <form onSubmit={handleSubmit} className="p-5 space-y-4">
          {error && <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">{error}</div>}
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-300">Plan Name <span className="text-red-400">*</span></label>
            <input type="text" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="e.g. Premium Monthly" className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none" />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-slate-300">Description</label>
            <textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="Plan description..." rows={2} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none resize-none" />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-300">Price <span className="text-red-400">*</span></label>
              <input type="number" step="0.01" value={form.price} onChange={(e) => setForm({ ...form, price: e.target.value })} placeholder="0.00" className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none" />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-300">Currency</label>
              <input type="text" value={form.currency} onChange={(e) => setForm({ ...form, currency: e.target.value })} placeholder={sysConfig.currency} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none" />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-300">Duration (days) <span className="text-red-400">*</span></label>
              <input type="number" value={form.durationDays} onChange={(e) => setForm({ ...form, durationDays: parseInt(e.target.value) || 0 })} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white focus:border-blue-500 focus:outline-none" />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-300">Grace Period (days)</label>
              <input type="number" value={form.gracePeriodDays} onChange={(e) => setForm({ ...form, gracePeriodDays: parseInt(e.target.value) || 0 })} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white focus:border-blue-500 focus:outline-none" />
            </div>
          </div>
          <div className="flex items-center gap-2">
            <input type="checkbox" id="isActive" checked={form.isActive} onChange={(e) => setForm({ ...form, isActive: e.target.checked })} className="h-4 w-4 rounded border-white/10 bg-white/5" />
            <label htmlFor="isActive" className="text-sm text-slate-300">Active</label>
          </div>
          <div className="flex justify-end gap-3 border-t border-white/10 pt-4">
            <button type="button" onClick={onClose} className="rounded-lg border border-white/10 px-4 py-2 text-sm text-slate-300 hover:bg-white/5">Cancel</button>
            <button type="submit" disabled={loading} className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-50">{loading ? 'Saving...' : plan ? 'Update Plan' : 'Create Plan'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function SubscriptionDetailModal({ subscription, onClose, onRefresh }: { subscription: Subscription; onClose: () => void; onRefresh: () => void }) {
  const [actionLoading, setActionLoading] = useState(false);
  const [actionError, setActionError] = useState<string | null>(null);
  const [showConfirm, setShowConfirm] = useState<'extend' | 'terminate' | null>(null);
  const [confirmReason, setConfirmReason] = useState('');
  const [extendDays, setExtendDays] = useState(30);

  const handleAction = async () => {
    if (!showConfirm) return;
    setActionLoading(true);
    setActionError(null);
    try {
      if (showConfirm === 'extend') {
        await subscriptionService.extendUserSubscription(subscription.id, extendDays, confirmReason);
      } else {
        await subscriptionService.terminateUserSubscription(subscription.id, confirmReason);
      }
      onRefresh();
      onClose();
    } catch (err: any) {
      setActionError(getErrorMessage(err));
    } finally {
      setActionLoading(false);
      setShowConfirm(null);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={onClose}>
      <div className="w-full max-w-2xl rounded-xl border border-white/10 bg-slate-900 shadow-2xl max-h-[90vh] overflow-hidden flex flex-col" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-white/10 p-5 shrink-0">
          <div>
            <h2 className="text-lg font-semibold text-white">Subscription Details</h2>
            <p className="text-sm text-slate-400">ID: {subscription.id}</p>
          </div>
          <div className="flex items-center gap-2">
            {(subscription.status === 'ACTIVE' || subscription.status === 'GRACE') && (
              <>
                <button onClick={() => setShowConfirm('extend')} className="rounded-lg border border-blue-500/30 bg-blue-500/10 px-3 py-2 text-xs font-medium text-blue-300 hover:bg-blue-500/20 flex items-center gap-1.5">
                  <ArrowRightLeft className="h-4 w-4" /> Extend
                </button>
                <button onClick={() => setShowConfirm('terminate')} className="rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-xs font-medium text-red-300 hover:bg-red-500/20 flex items-center gap-1.5">
                  <XCircle className="h-4 w-4" /> Terminate
                </button>
              </>
            )}
            <button onClick={onClose} className="rounded-lg p-1 text-slate-400 hover:text-white"><X className="h-5 w-5" /></button>
          </div>
        </div>
        <div className="flex-1 overflow-y-auto p-5 space-y-4">
          {actionError && <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">{actionError}</div>}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <DetailField label="User" value={`${subscription.user?.firstName || ''} ${subscription.user?.lastName || ''}`.trim() || subscription.userId} />
            <DetailField label="Email" value={subscription.user?.email || 'N/A'} />
            <DetailField label="Plan" value={subscription.plan?.name || subscription.planId} />
            <DetailField label="Status" value={subscription.status} />
            <DetailField label="Start Date" value={new Date(subscription.startDate).toLocaleDateString()} />
            <DetailField label="End Date" value={new Date(subscription.endDate).toLocaleDateString()} />
            <DetailField label="Grace Period End" value={subscription.gracePeriodEnd ? new Date(subscription.gracePeriodEnd).toLocaleDateString() : 'N/A'} />
            <DetailField label="Renewals" value={String(subscription.renewalCount)} />
            <DetailField label="Cancelled At" value={subscription.cancelledAt ? new Date(subscription.cancelledAt).toLocaleString() : 'N/A'} />
            <DetailField label="Created" value={new Date(subscription.createdAt).toLocaleString()} />
          </div>
        </div>
        {showConfirm && (
          <div className="border-t border-white/10 p-5">
            {showConfirm === 'extend' && (
              <div className="space-y-3">
                <label className="block text-sm font-medium text-slate-300">Extend by (days)</label>
                <input type="number" value={extendDays} onChange={(e) => setExtendDays(parseInt(e.target.value) || 0)} className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white focus:border-blue-500 focus:outline-none" />
              </div>
            )}
            <ConfirmDialog
              title={showConfirm === 'extend' ? 'Extend Subscription' : 'Terminate Subscription'}
              description={showConfirm === 'extend' ? 'Enter the number of days to extend this subscription.' : 'Are you sure you want to terminate this subscription? This action cannot be undone.'}
              confirmLabel={showConfirm === 'extend' ? 'Extend' : 'Terminate'}
              onConfirm={handleAction}
              onClose={() => setShowConfirm(null)}
              loading={actionLoading}
              reason={confirmReason}
              setReason={setConfirmReason}
            />
          </div>
        )}
      </div>
    </div>
  );
}

function DetailField({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-lg border border-white/10 bg-white/5 p-3">
      <p className="text-xs font-medium uppercase text-slate-400 mb-1">{label}</p>
      <p className="text-sm text-white">{value || 'N/A'}</p>
    </div>
  );
}

export default function SuperAdminSubscriptionsPage() {
  const sysConfig = useSystemConfig();
  const [tab, setTab] = useState<Tab>('plans');
  const [plans, setPlans] = useState<SubscriptionPlan[]>([]);
  const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);
  const [stats, setStats] = useState<SubscriptionStats | null>(null);
  const [users, setUsers] = useState<UserProfile[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [planStatusFilter, setPlanStatusFilter] = useState<PlanStatusFilter>('ALL');
  const [subStatusFilter, setSubStatusFilter] = useState<SubStatusFilter>('ALL');
  const [subSearchQuery, setSubSearchQuery] = useState('');
  const [selectedPlan, setSelectedPlan] = useState<SubscriptionPlan | null>(null);
  const [selectedSubscription, setSelectedSubscription] = useState<Subscription | null>(null);
  const [showPlanForm, setShowPlanForm] = useState(false);
  const [planToDelete, setPlanToDelete] = useState<SubscriptionPlan | null>(null);
  const [planDeleteConfirm, setPlanDeleteConfirm] = useState('');
  const [planDeleteLoading, setPlanDeleteLoading] = useState(false);
  const [sortBy, setSortBy] = useState<string | null>(null);
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc' | null>(null);

  const loadPlans = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await subscriptionService.listSubscriptionPlans({
        isActive: planStatusFilter === 'ALL' ? undefined : planStatusFilter === 'ACTIVE',
      });
      setPlans(res.data || []);
    } catch (err: any) {
      setError(err?.message || 'Failed to load plans');
      setPlans([]);
    } finally {
      setLoading(false);
    }
  }, [planStatusFilter]);

  const loadSubscriptions = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await subscriptionService.listUserSubscriptions({
        status: subStatusFilter === 'ALL' ? undefined : subStatusFilter,
        sortBy: sortBy ?? undefined,
        sortOrder: sortOrder ?? undefined,
      });
      setSubscriptions(res.data || []);
    } catch (err: any) {
      setError(err?.message || 'Failed to load subscriptions');
      setSubscriptions([]);
    } finally {
      setLoading(false);
    }
  }, [subStatusFilter, sortBy, sortOrder]);

  const loadStats = useCallback(async () => {
    try {
      const res = await subscriptionService.getSubscriptionStats();
      setStats(res);
    } catch {
      // silently ignore stats errors
    }
  }, []);

  useEffect(() => {
    if (tab === 'plans') loadPlans();
    else loadSubscriptions();
    loadStats();
  }, [tab, loadPlans, loadSubscriptions, loadStats]);

  useEffect(() => {
    adminService.listUsers({ page: 1, limit: 100 }).then((r: any) => setUsers(r.data || [])).catch(() => setUsers([]));
  }, []);

  const filteredSubscriptions = (subscriptions || []).filter((s) => {
    if (!subSearchQuery) return true;
    const q = subSearchQuery.toLowerCase();
    return (
      (s.userId || '').toLowerCase().includes(q) ||
      (s.user?.email || '').toLowerCase().includes(q) ||
      (s.plan?.name || '').toLowerCase().includes(q)
    );
  });

  const tableData = filteredSubscriptions.map((s) => ({
    ...s,
    userEmail: s.user?.email || s.userId,
    userName: s.user ? `${s.user.firstName || ''} ${s.user.lastName || ''}`.trim() : s.userId,
    planName: s.plan?.name || s.planId,
  }));

  const columns: SortableColumn[] = [
    {
      key: 'userEmail',
      label: 'User',
      sortable: true,
      render: (val: any, row: any) => (
        <div>
          <p className="text-white">{row.userName}</p>
          <p className="text-xs text-slate-400">{val}</p>
        </div>
      ),
    },
    {
      key: 'planName',
      label: 'Plan',
      sortable: true,
      render: (val: any) => <span className="text-slate-300">{val}</span>,
    },
    {
      key: 'status',
      label: 'Status',
      sortable: true,
      render: (val: any) => (
        <span className={`rounded-full px-2 py-1 text-xs font-medium ${SUB_STATUS_COLORS[val] || 'bg-slate-500/20 text-slate-300'}`}>
          {val}
        </span>
      ),
    },
    {
      key: 'startDate',
      label: 'Start Date',
      sortable: true,
      render: (val: any) => <span className="whitespace-nowrap">{new Date(val).toLocaleDateString()}</span>,
    },
    {
      key: 'endDate',
      label: 'End Date',
      sortable: true,
      render: (val: any) => <span className="whitespace-nowrap">{new Date(val).toLocaleDateString()}</span>,
    },
    {
      key: 'renewalCount',
      label: 'Renewal Count',
      sortable: true,
      render: (val: any) => <span className="text-slate-300">{val}</span>,
    },
    {
      key: 'createdAt',
      label: 'Created At',
      sortable: true,
      render: (val: any) => <span className="whitespace-nowrap">{new Date(val).toLocaleDateString()}</span>,
    },
    {
      key: 'actions',
      label: 'Actions',
      sortable: false,
      render: (_: any, row: any) => (
        <div onClick={(e) => e.stopPropagation()}>
          <button
            onClick={() => setSelectedSubscription(row)}
            className="rounded-lg border border-white/10 px-2.5 py-1 text-xs text-slate-300 hover:bg-white/5"
          >
            View Details
          </button>
        </div>
      ),
    },
  ];

  const handleSortChange = (key: string, order: 'asc' | 'desc' | null) => {
    setSortBy(key);
    setSortOrder(order);
  };

  const planStatCards = stats ? [
    { label: 'Active', value: stats.totalActive, color: 'text-emerald-400', bg: 'bg-emerald-500/10' },
    { label: 'Expired', value: stats.totalExpired, color: 'text-slate-400', bg: 'bg-slate-500/10' },
    { label: 'Grace', value: stats.totalGrace, color: 'text-amber-400', bg: 'bg-amber-500/10' },
    { label: 'Revenue', value: `$${Number(stats.totalRevenue).toFixed(2)}`, color: 'text-blue-400', bg: 'bg-blue-500/10' },
  ] : [];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Subscriptions Management</h1>
          <p className="text-slate-400">Manage subscription plans and user subscriptions.</p>
        </div>
        {tab === 'plans' && (
          <button onClick={() => { setSelectedPlan(null); setShowPlanForm(true); }} className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700">
            <Plus className="h-4 w-4" /> Create Plan
          </button>
        )}
      </div>

      {error && (
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">
          {error}
          <button onClick={tab === 'plans' ? loadPlans : loadSubscriptions} className="ml-4 underline">Retry</button>
        </div>
      )}

      {planStatCards.length > 0 && (
        <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
          {planStatCards.map((s) => (
            <div key={s.label} className={`rounded-xl border border-white/10 ${s.bg} p-4`}>
              <p className="text-xs font-medium text-slate-400 uppercase">{s.label}</p>
              <p className={`text-xl font-bold ${s.color}`}>{s.value}</p>
            </div>
          ))}
        </div>
      )}

      <div className="flex items-center gap-2 border-b border-white/10">
        {[
          { key: 'plans', label: 'Plans', icon: Package },
          { key: 'subscriptions', label: 'User Subscriptions', icon: Users },
        ].map((t) => (
          <button
            key={t.key}
            onClick={() => { setTab(t.key as Tab); setSelectedSubscription(null); }}
            className={cn(
              'flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors',
              tab === t.key ? 'border-blue-500 text-blue-300' : 'border-transparent text-slate-400 hover:text-white',
            )}
          >
            <t.icon className="h-4 w-4" /> {t.label}
          </button>
        ))}
      </div>

      {tab === 'plans' && (
        <>
          <div className="flex items-center gap-3">
            <select
              value={planStatusFilter}
              onChange={(e) => setPlanStatusFilter(e.target.value as PlanStatusFilter)}
              className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
            >
              <option value="ALL">All Statuses</option>
              <option value="ACTIVE">Active</option>
              <option value="INACTIVE">Inactive</option>
            </select>
            <button onClick={loadPlans} className="flex items-center gap-2 rounded-lg border border-white/10 px-3 py-2 text-sm text-slate-400 hover:bg-white/5">
              <RefreshCw className="h-4 w-4" /> Refresh
            </button>
          </div>

          {loading ? (
            <TableSkeleton rows={5} />
          ) : (plans || []).length === 0 ? (
            <EmptyState message="No plans found" description="Create your first subscription plan." />
          ) : (
            <div className="overflow-x-auto rounded-xl border border-white/10">
              <table className="w-full text-left text-sm">
                <thead className="bg-white/5 text-xs uppercase text-slate-400">
                  <tr>
                    <th className="px-4 py-3">Name</th>
                    <th className="px-4 py-3">Price</th>
                    <th className="px-4 py-3">Duration</th>
                    <th className="px-4 py-3">Grace Period</th>
                    <th className="px-4 py-3">Status</th>
                    <th className="px-4 py-3 text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {plans.map((plan) => (
                    <tr key={plan.id} className="hover:bg-white/5">
                      <td className="px-4 py-3 text-white">{plan.name}</td>
                      <td className="px-4 py-3 text-slate-300">${Number(plan.price).toFixed(2)}</td>
                      <td className="px-4 py-3 text-slate-300">{plan.durationDays} days</td>
                      <td className="px-4 py-3 text-slate-300">{plan.gracePeriodDays} days</td>
                      <td className="px-4 py-3">
                        <span className={`rounded-full px-2 py-1 text-xs font-medium ${plan.isActive ? 'bg-emerald-500/20 text-emerald-300' : 'bg-red-500/20 text-red-300'}`}>
                          {plan.isActive ? 'Active' : 'Inactive'}
                        </span>
                      </td>
                        <td className="px-4 py-3 text-right">
                          <div className="flex items-center justify-end gap-1">
                            <button onClick={() => setSelectedPlan(plan)} className="rounded p-1.5 text-blue-400 hover:bg-blue-500/20" title="View"><Eye className="h-4 w-4" /></button>
                            <button onClick={() => { setSelectedPlan(plan); setShowPlanForm(true); }} className="rounded p-1.5 text-amber-400 hover:bg-amber-500/20" title="Edit"><Pencil className="h-4 w-4" /></button>
                            <button onClick={() => { setPlanDeleteConfirm(''); setPlanToDelete(plan); }} className="rounded p-1.5 text-red-400 hover:bg-red-500/20" title="Delete"><Trash2 className="h-4 w-4" /></button>
                          </div>
                        </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </>
      )}

      {tab === 'subscriptions' && (
        <>
          <div className="flex flex-col gap-3 md:flex-row md:items-center">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
              <input
                type="text"
                placeholder="Search by user or plan..."
                value={subSearchQuery}
                onChange={(e) => setSubSearchQuery(e.target.value)}
                className="w-full rounded-lg border border-white/10 bg-white/5 pl-9 pr-4 py-2 text-sm text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none"
              />
            </div>
            <select
              value={subStatusFilter}
              onChange={(e) => setSubStatusFilter(e.target.value as SubStatusFilter)}
              className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
            >
              <option value="ALL">All Statuses</option>
              <option value="ACTIVE">Active</option>
              <option value="EXPIRED">Expired</option>
              <option value="TERMINATED">Terminated</option>
              <option value="GRACE">Grace</option>
              <option value="CANCELLED">Cancelled</option>
            </select>
            <button onClick={loadSubscriptions} className="flex items-center gap-2 rounded-lg border border-white/10 px-3 py-2 text-sm text-slate-400 hover:bg-white/5">
              <RefreshCw className="h-4 w-4" /> Refresh
            </button>
          </div>

          {loading ? (
            <TableSkeleton rows={5} />
          ) : tableData.length === 0 ? (
            <EmptyState message="No subscriptions found" description="No subscriptions match the current filters." />
          ) : (
            <SortableTable
              data={tableData}
              columns={columns}
              onRowClick={(sub) => setSelectedSubscription(sub)}
              sortBy={sortBy}
              sortOrder={sortOrder}
              onSortChange={handleSortChange}
            />
          )}
        </>
      )}

      {showPlanForm && (
        <PlanFormDialog
          plan={selectedPlan || undefined}
          onClose={() => { setShowPlanForm(false); setSelectedPlan(null); }}
          onSuccess={tab === 'plans' ? loadPlans : loadSubscriptions}
        />
      )}

      {selectedSubscription && (
        <SubscriptionDetailModal subscription={selectedSubscription} onClose={() => setSelectedSubscription(null)} onRefresh={loadSubscriptions} />
      )}

      {planToDelete && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={() => setPlanToDelete(null)}>
          <div className="w-full max-w-lg rounded-xl border border-white/10 bg-slate-900 shadow-2xl" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between border-b border-white/10 p-5">
              <h2 className="text-lg font-semibold text-white">Delete Plan</h2>
              <button onClick={() => setPlanToDelete(null)} className="rounded-lg p-1 text-slate-400 hover:text-white"><X className="h-5 w-5" /></button>
            </div>
            <div className="p-5 space-y-4">
              <p className="text-sm text-slate-400">
                Type <strong>"{planToDelete.name}"</strong> to confirm deletion. This action cannot be undone.
              </p>
              <input
                type="text"
                value={planDeleteConfirm}
                onChange={(e) => setPlanDeleteConfirm(e.target.value)}
                placeholder="Type plan name to confirm..."
                className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-red-500 focus:outline-none"
              />
            </div>
            <div className="flex justify-end gap-3 border-t border-white/10 p-5">
              <button onClick={() => setPlanToDelete(null)} className="rounded-lg border border-white/10 px-4 py-2 text-sm text-slate-300 hover:bg-white/5">Cancel</button>
              <button
                onClick={async () => {
                  if (planDeleteConfirm !== planToDelete.name) return;
                  setPlanDeleteLoading(true);
                  try {
                    await subscriptionService.deleteSubscriptionPlan(planToDelete.id);
                    loadPlans();
                    setPlanToDelete(null);
                    setPlanDeleteConfirm('');
                  } catch (err: any) {
                    // Handle error if needed - you could add an error state here
                  } finally {
                    setPlanDeleteLoading(false);
                  }
                }}
                disabled={planDeleteLoading || planDeleteConfirm !== planToDelete.name}
                className="rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white hover:bg-red-700 disabled:opacity-50"
              >
                {planDeleteLoading ? 'Deleting...' : 'Delete Plan'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
