/**
 * Billing Plans Tab
 *
 * Redesigned subscription plans management with versioning support.
 * Uses the commerce.billing system for grandfathering.
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Plus,
  Pencil,
  Trash2,
  Loader2,
  AlertCircle,
  DollarSign,
  Users,
  Clock,
  ChevronDown,
  ChevronRight,
  Archive,
  X,
  Check,
  Package,
  MessageSquare,
  CreditCard,
  Sliders,
  Star,
  Puzzle,
} from 'lucide-react';
import {
  usePlans,
  useFeatures,
  useAddOnProducts,
  useCreatePlan,
  useUpdatePlan,
  useDeletePlan,
  useCreatePlanVersion,
  useUpdatePlanVersion,
  useDeletePlanVersion,
  useCreateFeature,
  useUpdateFeature,
  useDeleteFeature,
  useCreateAddOnProduct,
  useUpdateAddOnProduct,
  useDeleteAddOnProduct,
  isGrandfatheringResponse,
  formatCentsToDollars,
  dollarsToCents,
  type PlanWithVersions,
  type PlanVersion,
  type Feature,
  type AddOnProduct,
  type PlanCreate,
  type PlanVersionCreate,
  type PlanVersionUpdate,
  type FeatureCreate,
  type AddOnProductCreate,
  type PlanFeatureWrite,
} from '../../../hooks/useBillingAdmin';
import { Modal, ModalFooter, Alert, ErrorMessage, Badge } from '../../../components/ui';

// =============================================================================
// Main Component
// =============================================================================

const BillingPlansTab: React.FC = () => {
  const { t } = useTranslation();
  const [activeSection, setActiveSection] = useState<'plans' | 'features' | 'addons'>('plans');

  return (
    <div className="space-y-6">
      {/* Section Tabs */}
      <div className="flex gap-2 border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={() => setActiveSection('plans')}
          className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px ${
            activeSection === 'plans'
              ? 'border-blue-600 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400'
          }`}
        >
          Plans & Versions
        </button>
        <button
          onClick={() => setActiveSection('features')}
          className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px ${
            activeSection === 'features'
              ? 'border-blue-600 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400'
          }`}
        >
          Features Library
        </button>
        <button
          onClick={() => setActiveSection('addons')}
          className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px ${
            activeSection === 'addons'
              ? 'border-blue-600 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400'
          }`}
        >
          Add-ons
        </button>
      </div>

      {/* Section Content */}
      {activeSection === 'plans' && <PlansSection />}
      {activeSection === 'features' && <FeaturesSection />}
      {activeSection === 'addons' && <AddOnsSection />}
    </div>
  );
};

// =============================================================================
// Plans Section
// =============================================================================

const PlansSection: React.FC = () => {
  const { data: plans, isLoading, error } = usePlans();
  const createPlanMutation = useCreatePlan();
  const [showPlanModal, setShowPlanModal] = useState(false);
  const [editingPlan, setEditingPlan] = useState<PlanWithVersions | null>(null);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  if (error) {
    return <ErrorMessage message="Failed to load plans" />;
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
            Subscription Plans
          </h2>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            Manage pricing tiers with version history for grandfathering
          </p>
        </div>
        <button
          onClick={() => {
            setEditingPlan(null);
            setShowPlanModal(true);
          }}
          className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
        >
          <Plus className="w-4 h-4" />
          Add Plan
        </button>
      </div>

      {/* Info Banner */}
      <Alert
        variant="info"
        message={
          <>
            <strong>Grandfathering enabled:</strong> When you edit a plan version that has active subscribers,
            a new version is created automatically. Existing subscribers keep their current plan terms.
          </>
        }
      />

      {/* Plans List */}
      <div className="space-y-4">
        {plans?.length === 0 ? (
          <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-8 text-center text-gray-500 dark:text-gray-400">
            No plans configured. Click "Add Plan" to create one.
          </div>
        ) : (
          plans?.map((plan) => (
            <PlanCard
              key={plan.id}
              plan={plan}
              onEdit={() => {
                setEditingPlan(plan);
                setShowPlanModal(true);
              }}
            />
          ))
        )}
      </div>

      {/* Plan Modal */}
      {showPlanModal && (
        <PlanModal
          plan={editingPlan}
          onClose={() => {
            setShowPlanModal(false);
            setEditingPlan(null);
          }}
        />
      )}
    </div>
  );
};

// =============================================================================
// Plan Card Component
// =============================================================================

interface PlanCardProps {
  plan: PlanWithVersions;
  onEdit: () => void;
}

const PlanCard: React.FC<PlanCardProps> = ({ plan, onEdit }) => {
  const [expanded, setExpanded] = useState(false);
  const [showVersionModal, setShowVersionModal] = useState(false);
  const [editingVersion, setEditingVersion] = useState<PlanVersion | null>(null);
  const deletePlanMutation = useDeletePlan();

  const activeVersion = plan.active_version;
  const legacyVersions = plan.versions.filter((v) => v.is_legacy);

  const handleDeletePlan = async () => {
    if (plan.total_subscribers > 0) {
      alert('Cannot delete a plan with active subscribers. Mark versions as legacy instead.');
      return;
    }
    if (confirm(`Are you sure you want to delete the "${plan.name}" plan?`)) {
      await deletePlanMutation.mutateAsync(plan.id);
    }
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
      {/* Plan Header */}
      <div className="px-6 py-4 flex items-center justify-between">
        <div className="flex items-center gap-4">
          <button
            onClick={() => setExpanded(!expanded)}
            className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            {expanded ? <ChevronDown className="w-5 h-5" /> : <ChevronRight className="w-5 h-5" />}
          </button>
          <div>
            <div className="flex items-center gap-3">
              <h3 className="font-semibold text-gray-900 dark:text-white">{plan.name}</h3>
              <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded">
                {plan.code}
              </span>
              {!plan.is_active && (
                <Badge variant="warning">Inactive</Badge>
              )}
            </div>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">{plan.description}</p>
          </div>
        </div>

        <div className="flex items-center gap-6">
          {/* Active Version Summary */}
          {activeVersion && (
            <div className="text-right">
              <div className="flex items-center gap-2 text-sm">
                <DollarSign className="w-4 h-4 text-gray-400" />
                <span className="font-medium text-gray-900 dark:text-white">
                  ${formatCentsToDollars(activeVersion.price_monthly_cents)}/mo
                </span>
              </div>
              <div className="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
                <Users className="w-3 h-3" />
                <span>{plan.total_subscribers} subscriber(s)</span>
              </div>
            </div>
          )}

          {/* Actions */}
          <div className="flex items-center gap-2">
            <button
              onClick={onEdit}
              className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
              title="Edit plan"
            >
              <Pencil className="w-4 h-4" />
            </button>
            <button
              onClick={handleDeletePlan}
              className="p-2 text-gray-400 hover:text-red-600 dark:hover:text-red-400"
              title="Delete plan"
            >
              <Trash2 className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* Expanded Content - Versions */}
      {expanded && (
        <div className="border-t border-gray-200 dark:border-gray-700 px-6 py-4">
          <div className="flex justify-between items-center mb-4">
            <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300">
              Plan Versions
            </h4>
            <button
              onClick={() => {
                setEditingVersion(null);
                setShowVersionModal(true);
              }}
              className="inline-flex items-center gap-1 px-3 py-1 text-xs font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400"
            >
              <Plus className="w-3 h-3" />
              New Version
            </button>
          </div>

          {/* Active Version */}
          {activeVersion && (
            <div className="mb-4">
              <h5 className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase mb-2">
                Active Version
              </h5>
              <VersionRow
                version={activeVersion}
                onEdit={() => {
                  setEditingVersion(activeVersion);
                  setShowVersionModal(true);
                }}
              />
            </div>
          )}

          {/* Legacy Versions */}
          {legacyVersions.length > 0 && (
            <div>
              <h5 className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase mb-2">
                Legacy Versions ({legacyVersions.length})
              </h5>
              <div className="space-y-2">
                {legacyVersions.map((version) => (
                  <VersionRow
                    key={version.id}
                    version={version}
                    onEdit={() => {
                      setEditingVersion(version);
                      setShowVersionModal(true);
                    }}
                  />
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Version Modal */}
      {showVersionModal && (
        <VersionModal
          planCode={plan.code}
          version={editingVersion}
          onClose={() => {
            setShowVersionModal(false);
            setEditingVersion(null);
          }}
        />
      )}
    </div>
  );
};

// =============================================================================
// Version Row Component
// =============================================================================

interface VersionRowProps {
  version: PlanVersion;
  onEdit: () => void;
}

const VersionRow: React.FC<VersionRowProps> = ({ version, onEdit }) => {
  const deleteVersionMutation = useDeletePlanVersion();

  const handleDelete = async () => {
    if (version.subscriber_count > 0) {
      alert('Cannot delete a version with active subscribers.');
      return;
    }
    if (confirm(`Are you sure you want to delete version ${version.version}?`)) {
      await deleteVersionMutation.mutateAsync(version.id);
    }
  };

  return (
    <div className={`flex items-center justify-between p-3 rounded-lg ${
      version.is_legacy
        ? 'bg-gray-50 dark:bg-gray-700/50'
        : 'bg-blue-50 dark:bg-blue-900/20'
    }`}>
      <div className="flex items-center gap-4">
        <div>
          <div className="flex items-center gap-2">
            <span className="font-medium text-gray-900 dark:text-white">
              v{version.version}
            </span>
            <span className="text-gray-500 dark:text-gray-400">
              {version.name}
            </span>
            {version.is_legacy && (
              <span className="px-2 py-0.5 text-xs font-medium bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-400 rounded">
                Legacy
              </span>
            )}
            {!version.is_public && !version.is_legacy && (
              <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 dark:bg-gray-600 text-gray-600 dark:text-gray-300 rounded">
                Hidden
              </span>
            )}
          </div>
          <div className="flex items-center gap-4 mt-1 text-xs text-gray-500 dark:text-gray-400">
            <span className="flex items-center gap-1">
              <DollarSign className="w-3 h-3" />
              ${formatCentsToDollars(version.price_monthly_cents)}/mo
            </span>
            <span className="flex items-center gap-1">
              <Users className="w-3 h-3" />
              {version.subscriber_count} subscriber(s)
            </span>
            <span className="flex items-center gap-1">
              <Package className="w-3 h-3" />
              {version.features.length} features
            </span>
          </div>
        </div>
      </div>

      <div className="flex items-center gap-2">
        <button
          onClick={onEdit}
          className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          title="Edit version"
        >
          <Pencil className="w-4 h-4" />
        </button>
        {version.subscriber_count === 0 && (
          <button
            onClick={handleDelete}
            className="p-1 text-gray-400 hover:text-red-600 dark:hover:text-red-400"
            title="Delete version"
          >
            <Trash2 className="w-4 h-4" />
          </button>
        )}
      </div>
    </div>
  );
};

// =============================================================================
// Plan Wizard Component (Unified Plan + Version Creation)
// =============================================================================

interface PlanModalProps {
  plan: PlanWithVersions | null;
  onClose: () => void;
}

type WizardStep = 'basics' | 'pricing' | 'features' | 'addons' | 'display';

const PlanModal: React.FC<PlanModalProps> = ({ plan, onClose }) => {
  const { data: features } = useFeatures();
  const { data: addons } = useAddOnProducts();
  const createPlanMutation = useCreatePlan();
  const updatePlanMutation = useUpdatePlan();
  const createVersionMutation = useCreatePlanVersion();

  const isNewPlan = !plan;
  const [currentStep, setCurrentStep] = useState<WizardStep>('basics');
  const [newMarketingFeature, setNewMarketingFeature] = useState('');

  // Combined form data for Plan + PlanVersion
  const [formData, setFormData] = useState({
    // Plan fields
    code: plan?.code || '',
    name: plan?.name || '',
    description: plan?.description || '',
    display_order: plan?.display_order || 0,
    is_active: plan?.is_active ?? true,
    // PlanVersion fields (for new plans)
    version_name: plan?.active_version?.name || '',
    price_monthly_cents: plan?.active_version?.price_monthly_cents || 0,
    price_yearly_cents: plan?.active_version?.price_yearly_cents || 0,
    transaction_fee_percent: plan?.active_version?.transaction_fee_percent ? parseFloat(plan.active_version.transaction_fee_percent) : 4.0,
    transaction_fee_fixed_cents: plan?.active_version?.transaction_fee_fixed_cents || 40,
    trial_days: plan?.active_version?.trial_days || 14,
    // Communication pricing
    sms_price_per_message_cents: plan?.active_version?.sms_price_per_message_cents || 3,
    masked_calling_price_per_minute_cents: plan?.active_version?.masked_calling_price_per_minute_cents || 5,
    proxy_number_monthly_fee_cents: plan?.active_version?.proxy_number_monthly_fee_cents || 200,
    // Credit settings
    default_auto_reload_enabled: plan?.active_version?.default_auto_reload_enabled || false,
    default_auto_reload_threshold_cents: plan?.active_version?.default_auto_reload_threshold_cents || 1000,
    default_auto_reload_amount_cents: plan?.active_version?.default_auto_reload_amount_cents || 2500,
    // Display settings
    is_public: plan?.active_version?.is_public ?? true,
    is_most_popular: plan?.active_version?.is_most_popular || false,
    show_price: plan?.active_version?.show_price ?? true,
    marketing_features: plan?.active_version?.marketing_features || [],
    // Stripe
    stripe_product_id: plan?.active_version?.stripe_product_id || '',
    stripe_price_id_monthly: plan?.active_version?.stripe_price_id_monthly || '',
    stripe_price_id_yearly: plan?.active_version?.stripe_price_id_yearly || '',
    // Features
    selectedFeatures: plan?.active_version?.features.map((f) => ({
      feature_code: f.feature.code,
      bool_value: f.bool_value,
      int_value: f.int_value,
    })) || [] as PlanFeatureWrite[],
    // Suggested Add-ons (codes of add-ons recommended for this plan)
    suggestedAddons: [] as string[],
  });

  const steps: { id: WizardStep; label: string; icon: React.ElementType }[] = [
    { id: 'basics', label: 'Basics', icon: Package },
    { id: 'pricing', label: 'Pricing', icon: DollarSign },
    { id: 'features', label: 'Features', icon: Check },
    { id: 'addons', label: 'Add-ons', icon: Puzzle },
    { id: 'display', label: 'Display', icon: Star },
  ];

  const currentStepIndex = steps.findIndex((s) => s.id === currentStep);
  const isFirstStep = currentStepIndex === 0;
  const isLastStep = currentStepIndex === steps.length - 1;

  const goNext = () => {
    if (!isLastStep) {
      setCurrentStep(steps[currentStepIndex + 1].id);
    }
  };

  const goPrev = () => {
    if (!isFirstStep) {
      setCurrentStep(steps[currentStepIndex - 1].id);
    }
  };

  // Feature helpers
  const booleanFeatures = features?.filter((f) => f.feature_type === 'boolean') || [];
  const integerFeatures = features?.filter((f) => f.feature_type === 'integer') || [];

  const toggleFeature = (code: string, type: string) => {
    setFormData((prev) => {
      const exists = prev.selectedFeatures.find((f) => f.feature_code === code);
      if (exists) {
        return {
          ...prev,
          selectedFeatures: prev.selectedFeatures.filter((f) => f.feature_code !== code),
        };
      } else {
        return {
          ...prev,
          selectedFeatures: [
            ...prev.selectedFeatures,
            {
              feature_code: code,
              bool_value: type === 'boolean' ? true : null,
              int_value: type === 'integer' ? 0 : null,
            },
          ],
        };
      }
    });
  };

  const updateFeatureValue = (code: string, value: number) => {
    setFormData((prev) => ({
      ...prev,
      selectedFeatures: prev.selectedFeatures.map((f) =>
        f.feature_code === code ? { ...f, int_value: value } : f
      ),
    }));
  };

  const toggleSuggestedAddon = (code: string) => {
    setFormData((prev) => {
      const exists = prev.suggestedAddons.includes(code);
      return {
        ...prev,
        suggestedAddons: exists
          ? prev.suggestedAddons.filter((c) => c !== code)
          : [...prev.suggestedAddons, code],
      };
    });
  };

  const handleAddMarketingFeature = () => {
    if (newMarketingFeature.trim()) {
      setFormData((prev) => ({
        ...prev,
        marketing_features: [...prev.marketing_features, newMarketingFeature.trim()],
      }));
      setNewMarketingFeature('');
    }
  };

  const handleRemoveMarketingFeature = (index: number) => {
    setFormData((prev) => ({
      ...prev,
      marketing_features: prev.marketing_features.filter((_, i) => i !== index),
    }));
  };

  const handleSubmit = async () => {
    if (isNewPlan) {
      // Create Plan first, then create first PlanVersion
      const newPlan = await createPlanMutation.mutateAsync({
        code: formData.code,
        name: formData.name,
        description: formData.description,
        display_order: formData.display_order,
        is_active: formData.is_active,
      });

      // Create the first version
      await createVersionMutation.mutateAsync({
        plan_code: formData.code,
        name: formData.version_name || `${formData.name} v1`,
        is_public: formData.is_public,
        price_monthly_cents: formData.price_monthly_cents,
        price_yearly_cents: formData.price_yearly_cents,
        transaction_fee_percent: formData.transaction_fee_percent,
        transaction_fee_fixed_cents: formData.transaction_fee_fixed_cents,
        trial_days: formData.trial_days,
        sms_price_per_message_cents: formData.sms_price_per_message_cents,
        masked_calling_price_per_minute_cents: formData.masked_calling_price_per_minute_cents,
        proxy_number_monthly_fee_cents: formData.proxy_number_monthly_fee_cents,
        default_auto_reload_enabled: formData.default_auto_reload_enabled,
        default_auto_reload_threshold_cents: formData.default_auto_reload_threshold_cents,
        default_auto_reload_amount_cents: formData.default_auto_reload_amount_cents,
        is_most_popular: formData.is_most_popular,
        show_price: formData.show_price,
        marketing_features: formData.marketing_features,
        stripe_product_id: formData.stripe_product_id,
        stripe_price_id_monthly: formData.stripe_price_id_monthly,
        stripe_price_id_yearly: formData.stripe_price_id_yearly,
        features: formData.selectedFeatures,
      });
    } else {
      // Just update the plan details
      await updatePlanMutation.mutateAsync({
        id: plan.id,
        name: formData.name,
        description: formData.description,
        display_order: formData.display_order,
        is_active: formData.is_active,
      });
    }
    onClose();
  };

  const isLoading = createPlanMutation.isPending || updatePlanMutation.isPending || createVersionMutation.isPending;

  return (
    <Modal
      isOpen
      onClose={onClose}
      title={isNewPlan ? 'Create New Plan' : `Edit ${plan.name}`}
      size="xl"
    >
      {/* Step Indicator */}
      {isNewPlan && (
        <div className="flex items-center justify-center gap-2 mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
          {steps.map((step, index) => {
            const isActive = step.id === currentStep;
            const isCompleted = index < currentStepIndex;
            const StepIcon = step.icon;
            return (
              <React.Fragment key={step.id}>
                {index > 0 && (
                  <div className={`h-px w-8 ${isCompleted ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'}`} />
                )}
                <button
                  type="button"
                  onClick={() => setCurrentStep(step.id)}
                  className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${
                    isActive
                      ? 'bg-blue-600 text-white'
                      : isCompleted
                      ? 'bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400'
                      : 'bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400'
                  }`}
                >
                  <StepIcon className="w-4 h-4" />
                  <span className="hidden sm:inline">{step.label}</span>
                </button>
              </React.Fragment>
            );
          })}
        </div>
      )}

      <div className="max-h-[60vh] overflow-y-auto">
        {/* Step 1: Basics */}
        {currentStep === 'basics' && (
          <div className="space-y-4 p-1">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Plan Code *
                </label>
                <input
                  type="text"
                  value={formData.code}
                  onChange={(e) => setFormData((prev) => ({ ...prev, code: e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, '') }))}
                  required
                  disabled={!isNewPlan}
                  placeholder="e.g., starter, pro, enterprise"
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50"
                />
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  Unique identifier (lowercase, no spaces)
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Display Name *
                </label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
                  required
                  placeholder="e.g., Starter, Professional, Enterprise"
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Description
              </label>
              <textarea
                value={formData.description}
                onChange={(e) => setFormData((prev) => ({ ...prev, description: e.target.value }))}
                rows={2}
                placeholder="Brief description of this plan..."
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              />
            </div>

            {isNewPlan && (
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Display Order
                </label>
                <input
                  type="number"
                  value={formData.display_order}
                  onChange={(e) => setFormData((prev) => ({ ...prev, display_order: parseInt(e.target.value) || 0 }))}
                  className="w-32 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  Lower numbers appear first on pricing page
                </p>
              </div>
            )}

            <div className="flex items-center gap-4 pt-2">
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={formData.is_active}
                  onChange={(e) => setFormData((prev) => ({ ...prev, is_active: e.target.checked }))}
                  className="rounded border-gray-300 dark:border-gray-600"
                />
                <span className="text-sm text-gray-700 dark:text-gray-300">Active (available for purchase)</span>
              </label>
            </div>
          </div>
        )}

        {/* Step 2: Pricing */}
        {currentStep === 'pricing' && (
          <div className="space-y-6 p-1">
            <div>
              <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                <DollarSign className="w-4 h-4" /> Subscription Pricing
              </h4>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Monthly Price ($)
                  </label>
                  <input
                    type="number"
                    step="0.01"
                    min="0"
                    value={formData.price_monthly_cents / 100}
                    onChange={(e) =>
                      setFormData((prev) => ({
                        ...prev,
                        price_monthly_cents: dollarsToCents(parseFloat(e.target.value) || 0),
                      }))
                    }
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Yearly Price ($)
                  </label>
                  <input
                    type="number"
                    step="0.01"
                    min="0"
                    value={formData.price_yearly_cents / 100}
                    onChange={(e) =>
                      setFormData((prev) => ({
                        ...prev,
                        price_yearly_cents: dollarsToCents(parseFloat(e.target.value) || 0),
                      }))
                    }
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Trial Days
                  </label>
                  <input
                    type="number"
                    min="0"
                    value={formData.trial_days}
                    onChange={(e) => setFormData((prev) => ({ ...prev, trial_days: parseInt(e.target.value) || 0 }))}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
              </div>
            </div>

            <div>
              <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                <CreditCard className="w-4 h-4" /> Transaction Fees
              </h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Fee Percentage (%)
                  </label>
                  <input
                    type="number"
                    step="0.1"
                    min="0"
                    value={formData.transaction_fee_percent}
                    onChange={(e) =>
                      setFormData((prev) => ({ ...prev, transaction_fee_percent: parseFloat(e.target.value) || 0 }))
                    }
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Fixed Fee (cents)
                  </label>
                  <input
                    type="number"
                    min="0"
                    value={formData.transaction_fee_fixed_cents}
                    onChange={(e) =>
                      setFormData((prev) => ({ ...prev, transaction_fee_fixed_cents: parseInt(e.target.value) || 0 }))
                    }
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
              </div>
              <p className="text-xs text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 p-2 rounded mt-2">
                Stripe charges 2.9% + $0.30. Suggested: Starter 4%+40¢, Pro 3.5%+35¢, Enterprise 3%+30¢
              </p>
            </div>

            <div>
              <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                <MessageSquare className="w-4 h-4" /> Communication Pricing
              </h4>
              <p className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                Costs when communication features are enabled. Enable features in the next step.
              </p>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    SMS (¢/msg)
                  </label>
                  <input
                    type="number"
                    min="0"
                    value={formData.sms_price_per_message_cents}
                    onChange={(e) =>
                      setFormData((prev) => ({ ...prev, sms_price_per_message_cents: parseInt(e.target.value) || 0 }))
                    }
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Calling (¢/min)
                  </label>
                  <input
                    type="number"
                    min="0"
                    value={formData.masked_calling_price_per_minute_cents}
                    onChange={(e) =>
                      setFormData((prev) => ({ ...prev, masked_calling_price_per_minute_cents: parseInt(e.target.value) || 0 }))
                    }
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Proxy # (¢/mo)
                  </label>
                  <input
                    type="number"
                    min="0"
                    value={formData.proxy_number_monthly_fee_cents}
                    onChange={(e) =>
                      setFormData((prev) => ({ ...prev, proxy_number_monthly_fee_cents: parseInt(e.target.value) || 0 }))
                    }
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Step 3: Features */}
        {currentStep === 'features' && (
          <div className="space-y-6 p-1">
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Select which features to include in this plan. Check to enable, set limits for quota features.
            </p>

            {/* Boolean Features */}
            {booleanFeatures.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                  <Check className="w-4 h-4" /> Capabilities
                </h4>
                <div className="grid grid-cols-2 gap-2">
                  {booleanFeatures.map((feature) => {
                    const selected = formData.selectedFeatures.find((f) => f.feature_code === feature.code);
                    return (
                      <label
                        key={feature.id}
                        className={`flex items-start gap-3 p-3 border rounded-lg cursor-pointer transition-colors ${
                          selected
                            ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                            : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
                        }`}
                      >
                        <input
                          type="checkbox"
                          checked={!!selected}
                          onChange={() => toggleFeature(feature.code, feature.feature_type)}
                          className="mt-0.5 rounded border-gray-300 dark:border-gray-600"
                        />
                        <div className="flex-1 min-w-0">
                          <span className="text-sm font-medium text-gray-900 dark:text-white block">
                            {feature.name}
                          </span>
                          {feature.description && (
                            <span className="text-xs text-gray-500 dark:text-gray-400 block mt-0.5">
                              {feature.description}
                            </span>
                          )}
                        </div>
                      </label>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Integer Features */}
            {integerFeatures.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                  <Sliders className="w-4 h-4" /> Limits & Quotas
                </h4>
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                  Set to 0 for unlimited. Uncheck to exclude from plan.
                </p>
                <div className="grid grid-cols-2 gap-3">
                  {integerFeatures.map((feature) => {
                    const selected = formData.selectedFeatures.find((f) => f.feature_code === feature.code);
                    return (
                      <div
                        key={feature.id}
                        className={`flex items-center gap-3 p-3 border rounded-lg ${
                          selected
                            ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                            : 'border-gray-200 dark:border-gray-700'
                        }`}
                      >
                        <input
                          type="checkbox"
                          checked={!!selected}
                          onChange={() => toggleFeature(feature.code, feature.feature_type)}
                          className="rounded border-gray-300 dark:border-gray-600"
                        />
                        <div className="flex-1 min-w-0">
                          <span className="text-sm font-medium text-gray-900 dark:text-white block truncate">
                            {feature.name}
                          </span>
                        </div>
                        {selected && (
                          <input
                            type="number"
                            min="0"
                            value={selected.int_value || 0}
                            onChange={(e) => updateFeatureValue(feature.code, parseInt(e.target.value) || 0)}
                            className="w-20 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                            placeholder="0"
                          />
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            {(!features || features.length === 0) && (
              <div className="p-8 text-center text-gray-500 dark:text-gray-400 border border-dashed border-gray-300 dark:border-gray-600 rounded-lg">
                <Package className="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>No features defined yet.</p>
                <p className="text-xs mt-1">Add features in the Features Library tab first.</p>
              </div>
            )}
          </div>
        )}

        {/* Step 4: Add-ons */}
        {currentStep === 'addons' && (
          <div className="space-y-6 p-1">
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Select add-on products that complement this plan. Customers will see these as recommended add-ons when subscribing.
            </p>

            {addons && addons.length > 0 ? (
              <div className="space-y-3">
                {addons.filter((addon) => addon.is_active).map((addon) => {
                  const isSelected = formData.suggestedAddons.includes(addon.code);
                  return (
                    <label
                      key={addon.id}
                      className={`flex items-start gap-4 p-4 border rounded-lg cursor-pointer transition-colors ${
                        isSelected
                          ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                          : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
                      }`}
                    >
                      <input
                        type="checkbox"
                        checked={isSelected}
                        onChange={() => toggleSuggestedAddon(addon.code)}
                        className="mt-1 rounded border-gray-300 dark:border-gray-600"
                      />
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="font-medium text-gray-900 dark:text-white">{addon.name}</span>
                          <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded">
                            {addon.code}
                          </span>
                        </div>
                        {addon.description && (
                          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                            {addon.description}
                          </p>
                        )}
                        <div className="flex items-center gap-4 mt-2 text-sm">
                          {addon.price_monthly_cents > 0 && (
                            <span className="text-green-600 dark:text-green-400 font-medium">
                              ${formatCentsToDollars(addon.price_monthly_cents)}/mo
                            </span>
                          )}
                          {addon.price_one_time_cents > 0 && (
                            <span className="text-blue-600 dark:text-blue-400 font-medium">
                              ${formatCentsToDollars(addon.price_one_time_cents)} one-time
                            </span>
                          )}
                        </div>
                      </div>
                      {isSelected && (
                        <Check className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0" />
                      )}
                    </label>
                  );
                })}
              </div>
            ) : (
              <div className="p-8 text-center text-gray-500 dark:text-gray-400 border border-dashed border-gray-300 dark:border-gray-600 rounded-lg">
                <Puzzle className="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>No add-on products available yet.</p>
                <p className="text-xs mt-1">Add products in the Add-ons tab first.</p>
              </div>
            )}

            {formData.suggestedAddons.length > 0 && (
              <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                <h5 className="text-sm font-medium text-blue-900 dark:text-blue-300 mb-2">
                  Selected Add-ons ({formData.suggestedAddons.length})
                </h5>
                <div className="flex flex-wrap gap-2">
                  {formData.suggestedAddons.map((code) => {
                    const addon = addons?.find((a) => a.code === code);
                    return (
                      <span
                        key={code}
                        className="inline-flex items-center gap-1 px-3 py-1 bg-blue-100 dark:bg-blue-800 text-blue-800 dark:text-blue-200 text-sm rounded-full"
                      >
                        {addon?.name || code}
                        <button
                          type="button"
                          onClick={() => toggleSuggestedAddon(code)}
                          className="ml-1 hover:text-blue-600 dark:hover:text-blue-300"
                        >
                          <X className="w-3 h-3" />
                        </button>
                      </span>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        )}

        {/* Step 5: Display */}
        {currentStep === 'display' && (
          <div className="space-y-6 p-1">
            <div>
              <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                <Star className="w-4 h-4" /> Visibility Settings
              </h4>
              <div className="flex flex-wrap gap-6">
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={formData.is_public}
                    onChange={(e) => setFormData((prev) => ({ ...prev, is_public: e.target.checked }))}
                    className="rounded border-gray-300"
                  />
                  <span className="text-sm text-gray-700 dark:text-gray-300">Show on pricing page</span>
                </label>
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={formData.is_most_popular}
                    onChange={(e) => setFormData((prev) => ({ ...prev, is_most_popular: e.target.checked }))}
                    className="rounded border-gray-300"
                  />
                  <span className="text-sm text-gray-700 dark:text-gray-300">"Most Popular" badge</span>
                </label>
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={formData.show_price}
                    onChange={(e) => setFormData((prev) => ({ ...prev, show_price: e.target.checked }))}
                    className="rounded border-gray-300"
                  />
                  <span className="text-sm text-gray-700 dark:text-gray-300">Display price</span>
                </label>
              </div>
            </div>

            <div>
              <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3">Marketing Feature List</h4>
              <p className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                Bullet points shown on pricing page. These are separate from actual feature access.
              </p>
              <div className="space-y-2">
                {formData.marketing_features.map((feature, index) => (
                  <div key={index} className="flex items-center gap-2">
                    <Check className="w-4 h-4 text-green-500 flex-shrink-0" />
                    <span className="flex-1 text-sm text-gray-700 dark:text-gray-300">{feature}</span>
                    <button
                      type="button"
                      onClick={() => handleRemoveMarketingFeature(index)}
                      className="text-gray-400 hover:text-red-500 p-1"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  </div>
                ))}
                <div className="flex gap-2">
                  <input
                    type="text"
                    value={newMarketingFeature}
                    onChange={(e) => setNewMarketingFeature(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddMarketingFeature())}
                    placeholder="e.g., Unlimited appointments"
                    className="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                  />
                  <button
                    type="button"
                    onClick={handleAddMarketingFeature}
                    className="px-3 py-2 text-sm font-medium text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg"
                  >
                    Add
                  </button>
                </div>
              </div>
            </div>

            <div>
              <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3">Stripe Integration</h4>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Product ID
                  </label>
                  <input
                    type="text"
                    value={formData.stripe_product_id}
                    onChange={(e) => setFormData((prev) => ({ ...prev, stripe_product_id: e.target.value }))}
                    placeholder="prod_..."
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Monthly Price ID
                  </label>
                  <input
                    type="text"
                    value={formData.stripe_price_id_monthly}
                    onChange={(e) => setFormData((prev) => ({ ...prev, stripe_price_id_monthly: e.target.value }))}
                    placeholder="price_..."
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Yearly Price ID
                  </label>
                  <input
                    type="text"
                    value={formData.stripe_price_id_yearly}
                    onChange={(e) => setFormData((prev) => ({ ...prev, stripe_price_id_yearly: e.target.value }))}
                    placeholder="price_..."
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                  />
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Footer */}
      <div className="flex justify-between items-center pt-4 mt-4 border-t border-gray-200 dark:border-gray-700">
        <div>
          {!isFirstStep && isNewPlan && (
            <button
              type="button"
              onClick={goPrev}
              className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
            >
              Back
            </button>
          )}
        </div>
        <div className="flex gap-3">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
          >
            Cancel
          </button>
          {isNewPlan && !isLastStep ? (
            <button
              type="button"
              onClick={goNext}
              disabled={currentStep === 'basics' && (!formData.code || !formData.name)}
              className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Next
            </button>
          ) : (
            <button
              type="button"
              onClick={handleSubmit}
              disabled={isLoading || !formData.code || !formData.name}
              className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isLoading && <Loader2 className="w-4 h-4 animate-spin" />}
              {isNewPlan ? 'Create Plan' : 'Save Changes'}
            </button>
          )}
        </div>
      </div>
    </Modal>
  );
};

// =============================================================================
// Version Modal Component
// =============================================================================

interface VersionModalProps {
  planCode: string;
  version: PlanVersion | null;
  onClose: () => void;
}

const VersionModal: React.FC<VersionModalProps> = ({ planCode, version, onClose }) => {
  const { data: features } = useFeatures();
  const createMutation = useCreatePlanVersion();
  const updateMutation = useUpdatePlanVersion();

  const [grandfatheringMessage, setGrandfatheringMessage] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'basic' | 'features' | 'display'>('basic');
  const [newMarketingFeature, setNewMarketingFeature] = useState('');

  const [formData, setFormData] = useState({
    // Basic
    name: version?.name || `${planCode} Plan`,
    is_public: version?.is_public ?? true,
    // Pricing
    price_monthly_cents: version?.price_monthly_cents || 0,
    price_yearly_cents: version?.price_yearly_cents || 0,
    transaction_fee_percent: version?.transaction_fee_percent ? parseFloat(version.transaction_fee_percent) : 4.0,
    transaction_fee_fixed_cents: version?.transaction_fee_fixed_cents || 40,
    trial_days: version?.trial_days || 0,
    // Communication pricing (costs when feature is enabled via Features)
    sms_price_per_message_cents: version?.sms_price_per_message_cents || 3,
    masked_calling_price_per_minute_cents: version?.masked_calling_price_per_minute_cents || 5,
    proxy_number_monthly_fee_cents: version?.proxy_number_monthly_fee_cents || 200,
    // Credit settings
    default_auto_reload_enabled: version?.default_auto_reload_enabled || false,
    default_auto_reload_threshold_cents: version?.default_auto_reload_threshold_cents || 1000,
    default_auto_reload_amount_cents: version?.default_auto_reload_amount_cents || 2500,
    // Display settings
    is_most_popular: version?.is_most_popular || false,
    show_price: version?.show_price ?? true,
    marketing_features: version?.marketing_features || [],
    // Stripe
    stripe_product_id: version?.stripe_product_id || '',
    stripe_price_id_monthly: version?.stripe_price_id_monthly || '',
    stripe_price_id_yearly: version?.stripe_price_id_yearly || '',
    // Features (M2M via PlanFeature - all permissions & limits managed here)
    selectedFeatures: version?.features.map((f) => ({
      feature_code: f.feature.code,
      bool_value: f.bool_value,
      int_value: f.int_value,
    })) || [] as PlanFeatureWrite[],
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const payload = {
      name: formData.name,
      is_public: formData.is_public,
      price_monthly_cents: formData.price_monthly_cents,
      price_yearly_cents: formData.price_yearly_cents,
      transaction_fee_percent: formData.transaction_fee_percent,
      transaction_fee_fixed_cents: formData.transaction_fee_fixed_cents,
      trial_days: formData.trial_days,
      // Communication pricing (costs when feature is enabled)
      sms_price_per_message_cents: formData.sms_price_per_message_cents,
      masked_calling_price_per_minute_cents: formData.masked_calling_price_per_minute_cents,
      proxy_number_monthly_fee_cents: formData.proxy_number_monthly_fee_cents,
      // Credit settings
      default_auto_reload_enabled: formData.default_auto_reload_enabled,
      default_auto_reload_threshold_cents: formData.default_auto_reload_threshold_cents,
      default_auto_reload_amount_cents: formData.default_auto_reload_amount_cents,
      // Display settings
      is_most_popular: formData.is_most_popular,
      show_price: formData.show_price,
      marketing_features: formData.marketing_features,
      // Stripe
      stripe_product_id: formData.stripe_product_id,
      stripe_price_id_monthly: formData.stripe_price_id_monthly,
      stripe_price_id_yearly: formData.stripe_price_id_yearly,
      // Features (M2M via PlanFeature - all permissions & limits managed here)
      features: formData.selectedFeatures,
    };

    if (version) {
      const result = await updateMutation.mutateAsync({ id: version.id, ...payload });
      if (isGrandfatheringResponse(result)) {
        setGrandfatheringMessage(result.message);
        setTimeout(onClose, 3000);
        return;
      }
    } else {
      await createMutation.mutateAsync({ plan_code: planCode, ...payload });
    }
    onClose();
  };

  const handleAddMarketingFeature = () => {
    if (newMarketingFeature.trim()) {
      setFormData((prev) => ({
        ...prev,
        marketing_features: [...prev.marketing_features, newMarketingFeature.trim()],
      }));
      setNewMarketingFeature('');
    }
  };

  const handleRemoveMarketingFeature = (index: number) => {
    setFormData((prev) => ({
      ...prev,
      marketing_features: prev.marketing_features.filter((_, i) => i !== index),
    }));
  };

  const toggleFeature = (featureCode: string, featureType: 'boolean' | 'integer') => {
    setFormData((prev) => {
      const existing = prev.selectedFeatures.find((f) => f.feature_code === featureCode);
      if (existing) {
        return {
          ...prev,
          selectedFeatures: prev.selectedFeatures.filter((f) => f.feature_code !== featureCode),
        };
      }
      return {
        ...prev,
        selectedFeatures: [
          ...prev.selectedFeatures,
          {
            feature_code: featureCode,
            bool_value: featureType === 'boolean' ? true : null,
            int_value: featureType === 'integer' ? 0 : null,
          },
        ],
      };
    });
  };

  const updateFeatureValue = (featureCode: string, value: number) => {
    setFormData((prev) => ({
      ...prev,
      selectedFeatures: prev.selectedFeatures.map((f) =>
        f.feature_code === featureCode ? { ...f, int_value: value } : f
      ),
    }));
  };

  const isLoading = createMutation.isPending || updateMutation.isPending;

  // Group features by type for better UX
  const booleanFeatures = features?.filter((f) => f.feature_type === 'boolean') || [];
  const integerFeatures = features?.filter((f) => f.feature_type === 'integer') || [];

  const tabs = [
    { id: 'basic', label: 'Pricing & Settings', icon: DollarSign },
    { id: 'features', label: 'Features & Limits', icon: Package },
    { id: 'display', label: 'Marketing Display', icon: Star },
  ] as const;

  return (
    <Modal
      isOpen
      onClose={onClose}
      title={version ? `Edit Version v${version.version}` : 'Create New Version'}
      size="xl"
    >
      {grandfatheringMessage && (
        <Alert variant="success" message={grandfatheringMessage} className="mb-4" />
      )}

      {version && version.subscriber_count > 0 && !grandfatheringMessage && (
        <Alert
          variant="warning"
          className="mb-4"
          message={
            <>
              This version has <strong>{version.subscriber_count}</strong> active subscriber(s).
              Saving changes will create a new version and mark this one as legacy.
              Existing subscribers will keep their current plan.
            </>
          }
        />
      )}

      <form onSubmit={handleSubmit} className="space-y-4">
        {/* Tabs */}
        <div className="flex gap-1 border-b border-gray-200 dark:border-gray-700 overflow-x-auto">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              type="button"
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-4 py-2 text-sm font-medium whitespace-nowrap border-b-2 -mb-px ${
                activeTab === tab.id
                  ? 'border-blue-600 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400'
              }`}
            >
              <tab.icon className="w-4 h-4" />
              {tab.label}
            </button>
          ))}
        </div>

        {/* Tab Content */}
        <div className="max-h-[60vh] overflow-y-auto">
          {/* Basic & Pricing Tab */}
          {activeTab === 'basic' && (
            <div className="space-y-6 p-1">
              {/* Basic Info */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Version Name
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
                    required
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Trial Days
                  </label>
                  <input
                    type="number"
                    min="0"
                    value={formData.trial_days}
                    onChange={(e) => setFormData((prev) => ({ ...prev, trial_days: parseInt(e.target.value) || 0 }))}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
              </div>

              {/* Pricing */}
              <div>
                <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                  <DollarSign className="w-4 h-4" /> Subscription Pricing
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Monthly Price ($)
                    </label>
                    <input
                      type="number"
                      step="0.01"
                      value={formData.price_monthly_cents / 100}
                      onChange={(e) =>
                        setFormData((prev) => ({
                          ...prev,
                          price_monthly_cents: dollarsToCents(parseFloat(e.target.value) || 0),
                        }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Yearly Price ($)
                    </label>
                    <input
                      type="number"
                      step="0.01"
                      value={formData.price_yearly_cents / 100}
                      onChange={(e) =>
                        setFormData((prev) => ({
                          ...prev,
                          price_yearly_cents: dollarsToCents(parseFloat(e.target.value) || 0),
                        }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  </div>
                </div>
              </div>

              {/* Transaction Fees */}
              <div>
                <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                  <CreditCard className="w-4 h-4" /> Transaction Fees
                </h4>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Transaction Fee (%)
                    </label>
                    <input
                      type="number"
                      step="0.01"
                      value={formData.transaction_fee_percent}
                      onChange={(e) =>
                        setFormData((prev) => ({ ...prev, transaction_fee_percent: parseFloat(e.target.value) || 0 }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Fixed Fee (cents)
                    </label>
                    <input
                      type="number"
                      value={formData.transaction_fee_fixed_cents}
                      onChange={(e) =>
                        setFormData((prev) => ({ ...prev, transaction_fee_fixed_cents: parseInt(e.target.value) || 0 }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  </div>
                </div>
                <p className="text-xs text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 p-2 rounded mt-2">
                  Stripe charges 2.9% + $0.30 per transaction. Recommended: STARTER 4%+40¢, PROFESSIONAL 3.5%+35¢, ENTERPRISE 3%+30¢.
                </p>
              </div>

              {/* Communication Pricing */}
              <div>
                <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                  <MessageSquare className="w-4 h-4" /> Communication Pricing
                </h4>
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                  Set pricing for communication features. Enable the features in the "Features & Limits" tab.
                </p>
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      SMS (cents/msg)
                    </label>
                    <input
                      type="number"
                      min="0"
                      value={formData.sms_price_per_message_cents}
                      onChange={(e) =>
                        setFormData((prev) => ({ ...prev, sms_price_per_message_cents: parseInt(e.target.value) || 0 }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Calling (cents/min)
                    </label>
                    <input
                      type="number"
                      min="0"
                      value={formData.masked_calling_price_per_minute_cents}
                      onChange={(e) =>
                        setFormData((prev) => ({ ...prev, masked_calling_price_per_minute_cents: parseInt(e.target.value) || 0 }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Proxy # (cents/mo)
                    </label>
                    <input
                      type="number"
                      min="0"
                      value={formData.proxy_number_monthly_fee_cents}
                      onChange={(e) =>
                        setFormData((prev) => ({ ...prev, proxy_number_monthly_fee_cents: parseInt(e.target.value) || 0 }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  </div>
                </div>
              </div>

              {/* Credit Settings */}
              <div>
                <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                  <CreditCard className="w-4 h-4" /> Default Credit Settings
                </h4>
                <div className="space-y-4">
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={formData.default_auto_reload_enabled}
                      onChange={(e) => setFormData((prev) => ({ ...prev, default_auto_reload_enabled: e.target.checked }))}
                      className="rounded border-gray-300"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-300">Auto-reload enabled by default</span>
                  </label>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        Reload threshold (cents)
                      </label>
                      <input
                        type="number"
                        min="0"
                        step="100"
                        value={formData.default_auto_reload_threshold_cents}
                        onChange={(e) =>
                          setFormData((prev) => ({ ...prev, default_auto_reload_threshold_cents: parseInt(e.target.value) || 0 }))
                        }
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        Reload amount (cents)
                      </label>
                      <input
                        type="number"
                        min="0"
                        step="100"
                        value={formData.default_auto_reload_amount_cents}
                        onChange={(e) =>
                          setFormData((prev) => ({ ...prev, default_auto_reload_amount_cents: parseInt(e.target.value) || 0 }))
                        }
                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                      />
                    </div>
                  </div>
                </div>
              </div>

              {/* Stripe IDs */}
              <div>
                <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3">Stripe Integration</h4>
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Product ID
                    </label>
                    <input
                      type="text"
                      value={formData.stripe_product_id}
                      onChange={(e) => setFormData((prev) => ({ ...prev, stripe_product_id: e.target.value }))}
                      placeholder="prod_..."
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Monthly Price ID
                    </label>
                    <input
                      type="text"
                      value={formData.stripe_price_id_monthly}
                      onChange={(e) => setFormData((prev) => ({ ...prev, stripe_price_id_monthly: e.target.value }))}
                      placeholder="price_..."
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Yearly Price ID
                    </label>
                    <input
                      type="text"
                      value={formData.stripe_price_id_yearly}
                      onChange={(e) => setFormData((prev) => ({ ...prev, stripe_price_id_yearly: e.target.value }))}
                      placeholder="price_..."
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                    />
                  </div>
                </div>
              </div>

            </div>
          )}

          {/* Features & Limits Tab */}
          {activeTab === 'features' && (
            <div className="space-y-6 p-1">
              <p className="text-sm text-gray-500 dark:text-gray-400">
                Select features and set limits for this plan. Boolean features can be enabled/disabled.
                Integer features have limits (use 0 for unlimited).
              </p>

              {/* Boolean Features */}
              {booleanFeatures.length > 0 && (
                <div>
                  <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                    <Check className="w-4 h-4" /> Capabilities
                  </h4>
                  <div className="grid grid-cols-2 gap-2">
                    {booleanFeatures.map((feature) => {
                      const selected = formData.selectedFeatures.find((f) => f.feature_code === feature.code);
                      return (
                        <label
                          key={feature.id}
                          className="flex items-start gap-3 p-3 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700/50 cursor-pointer"
                        >
                          <input
                            type="checkbox"
                            checked={!!selected}
                            onChange={() => toggleFeature(feature.code, feature.feature_type)}
                            className="mt-0.5 rounded border-gray-300 dark:border-gray-600"
                          />
                          <div className="flex-1 min-w-0">
                            <span className="text-sm font-medium text-gray-900 dark:text-white block">
                              {feature.name}
                            </span>
                            {feature.description && (
                              <span className="text-xs text-gray-500 dark:text-gray-400 block mt-0.5 truncate">
                                {feature.description}
                              </span>
                            )}
                          </div>
                        </label>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Integer Features (Limits) */}
              {integerFeatures.length > 0 && (
                <div>
                  <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                    <Sliders className="w-4 h-4" /> Limits & Quotas
                  </h4>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                    Set to 0 for unlimited. Leave unchecked to exclude from plan.
                  </p>
                  <div className="grid grid-cols-2 gap-3">
                    {integerFeatures.map((feature) => {
                      const selected = formData.selectedFeatures.find((f) => f.feature_code === feature.code);
                      return (
                        <div
                          key={feature.id}
                          className="flex items-center gap-3 p-3 border border-gray-200 dark:border-gray-700 rounded-lg"
                        >
                          <input
                            type="checkbox"
                            checked={!!selected}
                            onChange={() => toggleFeature(feature.code, feature.feature_type)}
                            className="rounded border-gray-300 dark:border-gray-600"
                          />
                          <div className="flex-1 min-w-0">
                            <span className="text-sm font-medium text-gray-900 dark:text-white block truncate">
                              {feature.name}
                            </span>
                          </div>
                          {selected && (
                            <input
                              type="number"
                              min="0"
                              value={selected.int_value || 0}
                              onChange={(e) => updateFeatureValue(feature.code, parseInt(e.target.value) || 0)}
                              className="w-20 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                              placeholder="0"
                            />
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {(!features || features.length === 0) && (
                <div className="p-8 text-center text-gray-500 dark:text-gray-400 border border-dashed border-gray-300 dark:border-gray-600 rounded-lg">
                  <Package className="w-8 h-8 mx-auto mb-2 opacity-50" />
                  <p>No features defined yet.</p>
                  <p className="text-xs mt-1">Add features in the Features Library tab first.</p>
                </div>
              )}
            </div>
          )}

          {/* Marketing Display Tab */}
          {activeTab === 'display' && (
            <div className="space-y-6 p-1">
              {/* Display Settings */}
              <div>
                <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2">
                  <Star className="w-4 h-4" /> Display Settings
                </h4>
                <div className="flex flex-wrap gap-6">
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={formData.is_public}
                      onChange={(e) => setFormData((prev) => ({ ...prev, is_public: e.target.checked }))}
                      className="rounded border-gray-300"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-300">Public (show on pricing page)</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={formData.is_most_popular}
                      onChange={(e) => setFormData((prev) => ({ ...prev, is_most_popular: e.target.checked }))}
                      className="rounded border-gray-300"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-300">Most Popular Badge</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      checked={formData.show_price}
                      onChange={(e) => setFormData((prev) => ({ ...prev, show_price: e.target.checked }))}
                      className="rounded border-gray-300"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-300">Show Price on Marketing</span>
                  </label>
                </div>
              </div>

              {/* Marketing Features List */}
              <div>
                <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-3">Marketing Feature List</h4>
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                  These bullet points appear on the pricing page. They're separate from actual features.
                </p>
                <div className="space-y-2">
                  {formData.marketing_features.map((feature, index) => (
                    <div key={index} className="flex items-center gap-2">
                      <Check className="w-4 h-4 text-green-500" />
                      <span className="flex-1 text-sm text-gray-700 dark:text-gray-300">{feature}</span>
                      <button
                        type="button"
                        onClick={() => handleRemoveMarketingFeature(index)}
                        className="text-gray-400 hover:text-red-500"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </div>
                  ))}
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={newMarketingFeature}
                      onChange={(e) => setNewMarketingFeature(e.target.value)}
                      onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddMarketingFeature())}
                      placeholder="Add a marketing bullet point..."
                      className="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                    />
                    <button
                      type="button"
                      onClick={handleAddMarketingFeature}
                      className="px-3 py-2 text-sm font-medium text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg"
                    >
                      Add
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        <ModalFooter
          onCancel={onClose}
          submitText={version ? 'Save Version' : 'Create Version'}
          isLoading={isLoading}
        />
      </form>
    </Modal>
  );
};

// =============================================================================
// Features Section
// =============================================================================

const FeaturesSection: React.FC = () => {
  const { data: features, isLoading, error } = useFeatures();
  const createMutation = useCreateFeature();
  const deleteMutation = useDeleteFeature();
  const [showModal, setShowModal] = useState(false);
  const [editingFeature, setEditingFeature] = useState<Feature | null>(null);

  const [newFeature, setNewFeature] = useState<FeatureCreate>({
    code: '',
    name: '',
    description: '',
    feature_type: 'boolean',
  });

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    await createMutation.mutateAsync(newFeature);
    setNewFeature({ code: '', name: '', description: '', feature_type: 'boolean' });
    setShowModal(false);
  };

  const handleDelete = async (id: number) => {
    if (confirm('Are you sure you want to delete this feature?')) {
      await deleteMutation.mutateAsync(id);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  if (error) {
    return <ErrorMessage message="Failed to load features" />;
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
            Features Library
          </h2>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            Reusable features that can be assigned to plan versions
          </p>
        </div>
        <button
          onClick={() => setShowModal(true)}
          className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
        >
          <Plus className="w-4 h-4" />
          Add Feature
        </button>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 divide-y divide-gray-200 dark:divide-gray-700">
        {features?.length === 0 ? (
          <div className="p-8 text-center text-gray-500 dark:text-gray-400">
            No features configured.
          </div>
        ) : (
          features?.map((feature) => (
            <div key={feature.id} className="px-6 py-4 flex items-center justify-between">
              <div>
                <div className="flex items-center gap-3">
                  <span className="font-medium text-gray-900 dark:text-white">{feature.name}</span>
                  <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded">
                    {feature.code}
                  </span>
                  <span className={`px-2 py-0.5 text-xs font-medium rounded ${
                    feature.feature_type === 'boolean'
                      ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400'
                      : 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400'
                  }`}>
                    {feature.feature_type}
                  </span>
                </div>
                {feature.description && (
                  <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    {feature.description}
                  </p>
                )}
              </div>
              <button
                onClick={() => handleDelete(feature.id)}
                className="p-2 text-gray-400 hover:text-red-600 dark:hover:text-red-400"
              >
                <Trash2 className="w-4 h-4" />
              </button>
            </div>
          ))
        )}
      </div>

      {/* Add Feature Modal */}
      {showModal && (
        <Modal isOpen onClose={() => setShowModal(false)} title="Add Feature" size="md">
          <form onSubmit={handleCreate} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Code
                </label>
                <input
                  type="text"
                  value={newFeature.code}
                  onChange={(e) => setNewFeature((prev) => ({ ...prev, code: e.target.value }))}
                  required
                  placeholder="e.g., max_users"
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Type
                </label>
                <select
                  value={newFeature.feature_type}
                  onChange={(e) =>
                    setNewFeature((prev) => ({
                      ...prev,
                      feature_type: e.target.value as 'boolean' | 'integer',
                    }))
                  }
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                >
                  <option value="boolean">Boolean (on/off)</option>
                  <option value="integer">Integer (limit)</option>
                </select>
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Name
              </label>
              <input
                type="text"
                value={newFeature.name}
                onChange={(e) => setNewFeature((prev) => ({ ...prev, name: e.target.value }))}
                required
                placeholder="e.g., Maximum Users"
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Description
              </label>
              <textarea
                value={newFeature.description}
                onChange={(e) => setNewFeature((prev) => ({ ...prev, description: e.target.value }))}
                rows={2}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              />
            </div>
            <ModalFooter
              onCancel={() => setShowModal(false)}
              submitText="Create Feature"
              isLoading={createMutation.isPending}
            />
          </form>
        </Modal>
      )}
    </div>
  );
};

// =============================================================================
// Add-ons Section
// =============================================================================

const AddOnsSection: React.FC = () => {
  const { data: addons, isLoading, error } = useAddOnProducts();
  const createMutation = useCreateAddOnProduct();
  const deleteMutation = useDeleteAddOnProduct();
  const [showModal, setShowModal] = useState(false);

  const [newAddon, setNewAddon] = useState<AddOnProductCreate>({
    code: '',
    name: '',
    description: '',
    price_monthly_cents: 0,
    price_one_time_cents: 0,
    is_active: true,
  });

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    await createMutation.mutateAsync(newAddon);
    setNewAddon({
      code: '',
      name: '',
      description: '',
      price_monthly_cents: 0,
      price_one_time_cents: 0,
      is_active: true,
    });
    setShowModal(false);
  };

  const handleDelete = async (id: number) => {
    if (confirm('Are you sure you want to delete this add-on?')) {
      await deleteMutation.mutateAsync(id);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  if (error) {
    return <ErrorMessage message="Failed to load add-ons" />;
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Add-on Products</h2>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            Additional products that can be purchased alongside plans
          </p>
        </div>
        <button
          onClick={() => setShowModal(true)}
          className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
        >
          <Plus className="w-4 h-4" />
          Add Product
        </button>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 divide-y divide-gray-200 dark:divide-gray-700">
        {addons?.length === 0 ? (
          <div className="p-8 text-center text-gray-500 dark:text-gray-400">
            No add-on products configured.
          </div>
        ) : (
          addons?.map((addon) => (
            <div key={addon.id} className="px-6 py-4 flex items-center justify-between">
              <div>
                <div className="flex items-center gap-3">
                  <span className="font-medium text-gray-900 dark:text-white">{addon.name}</span>
                  <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded">
                    {addon.code}
                  </span>
                  {!addon.is_active && <Badge variant="warning">Inactive</Badge>}
                </div>
                <div className="flex items-center gap-4 mt-1 text-sm text-gray-500 dark:text-gray-400">
                  {addon.price_monthly_cents > 0 && (
                    <span>${formatCentsToDollars(addon.price_monthly_cents)}/mo</span>
                  )}
                  {addon.price_one_time_cents > 0 && (
                    <span>${formatCentsToDollars(addon.price_one_time_cents)} one-time</span>
                  )}
                </div>
              </div>
              <button
                onClick={() => handleDelete(addon.id)}
                className="p-2 text-gray-400 hover:text-red-600 dark:hover:text-red-400"
              >
                <Trash2 className="w-4 h-4" />
              </button>
            </div>
          ))
        )}
      </div>

      {/* Add Add-on Modal */}
      {showModal && (
        <Modal isOpen onClose={() => setShowModal(false)} title="Add Product" size="md">
          <form onSubmit={handleCreate} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Code
                </label>
                <input
                  type="text"
                  value={newAddon.code}
                  onChange={(e) => setNewAddon((prev) => ({ ...prev, code: e.target.value }))}
                  required
                  placeholder="e.g., extra_users"
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Name
                </label>
                <input
                  type="text"
                  value={newAddon.name}
                  onChange={(e) => setNewAddon((prev) => ({ ...prev, name: e.target.value }))}
                  required
                  placeholder="e.g., Extra Users"
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Description
              </label>
              <textarea
                value={newAddon.description}
                onChange={(e) => setNewAddon((prev) => ({ ...prev, description: e.target.value }))}
                rows={2}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Monthly Price ($)
                </label>
                <input
                  type="number"
                  step="0.01"
                  value={(newAddon.price_monthly_cents || 0) / 100}
                  onChange={(e) =>
                    setNewAddon((prev) => ({
                      ...prev,
                      price_monthly_cents: dollarsToCents(parseFloat(e.target.value) || 0),
                    }))
                  }
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  One-time Price ($)
                </label>
                <input
                  type="number"
                  step="0.01"
                  value={(newAddon.price_one_time_cents || 0) / 100}
                  onChange={(e) =>
                    setNewAddon((prev) => ({
                      ...prev,
                      price_one_time_cents: dollarsToCents(parseFloat(e.target.value) || 0),
                    }))
                  }
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
            </div>
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={newAddon.is_active}
                onChange={(e) => setNewAddon((prev) => ({ ...prev, is_active: e.target.checked }))}
                className="rounded border-gray-300 dark:border-gray-600"
              />
              <span className="text-sm text-gray-700 dark:text-gray-300">Active</span>
            </label>
            <ModalFooter
              onCancel={() => setShowModal(false)}
              submitText="Create Add-on"
              isLoading={createMutation.isPending}
            />
          </form>
        </Modal>
      )}
    </div>
  );
};

export default BillingPlansTab;
