import React, { useState, useEffect, useMemo } from 'react';
import { X, Save, RefreshCw, AlertCircle } from 'lucide-react';
import { useUpdateBusiness, useChangeBusinessPlan } from '../../../hooks/usePlatform';
import {
  useBillingPlans,
  useBillingFeatures,
  getActivePlanVersion,
  getBooleanFeature,
  getIntegerFeature,
} from '../../../hooks/useBillingPlans';
import { PlatformBusiness, getCustomTier, updateCustomTier, deleteCustomTier } from '../../../api/platform';
import DynamicFeaturesEditor from '../../../components/platform/DynamicFeaturesEditor';
import { TenantCustomTier } from '../../../types';
import { buildSubdomainUrl } from '../../../utils/domain';

interface BusinessEditModalProps {
  business: PlatformBusiness | null;
  isOpen: boolean;
  onClose: () => void;
}

const BusinessEditModal: React.FC<BusinessEditModalProps> = ({ business, isOpen, onClose }) => {
  const updateBusinessMutation = useUpdateBusiness();
  const changeBusinessPlanMutation = useChangeBusinessPlan();
  const { data: billingPlans, isLoading: plansLoading } = useBillingPlans();
  const { data: billingFeatures } = useBillingFeatures();

  // Track original plan to detect changes
  const [originalPlanCode, setOriginalPlanCode] = useState<string>('free');

  // Track custom tier status
  const [customTier, setCustomTier] = useState<TenantCustomTier | null>(null);
  const [loadingCustomTier, setLoadingCustomTier] = useState(false);
  const [deletingCustomTier, setDeletingCustomTier] = useState(false);

  // Core form fields (non-feature fields only)
  const [editForm, setEditForm] = useState({
    name: '',
    is_active: true,
    plan_code: 'free',
  });

  // Dynamic feature values - mapped by tenant_field_name
  // This is populated from the business and updated by DynamicFeaturesEditor
  const [featureValues, setFeatureValues] = useState<Record<string, boolean | number | null>>({});

  // Get available plan options from billing plans
  const planOptions = useMemo(() => {
    if (!billingPlans) return [];
    return billingPlans
      .filter(p => p.is_active && p.active_version)
      .map(p => ({
        code: p.code,
        name: p.name,
        displayOrder: p.display_order,
      }))
      .sort((a, b) => a.displayOrder - b.displayOrder);
  }, [billingPlans]);

  // Get defaults for a given plan code from billing plans
  // Returns feature value defaults (includes both boolean features AND integer limits)
  const getPlanDefaults = (planCode: string): Record<string, boolean | number | null> => {
    console.log('[getPlanDefaults] Called with planCode:', planCode, 'billingPlans:', billingPlans?.length, 'billingFeatures:', billingFeatures?.length);

    if (!billingPlans || !billingFeatures) {
      console.log('[getPlanDefaults] Missing billingPlans or billingFeatures');
      return {};
    }

    const planVersion = getActivePlanVersion(billingPlans, planCode);
    console.log('[getPlanDefaults] planVersion:', planVersion?.name, 'features count:', planVersion?.features?.length);

    if (!planVersion) {
      console.log('[getPlanDefaults] No active version found for plan:', planCode);
      return {};
    }

    const features = planVersion.features;

    // Build feature defaults dynamically from billing features (includes BOTH boolean AND integer features)
    const featureDefaults: Record<string, boolean | number | null> = {};
    for (const billingFeature of billingFeatures) {
      if (!billingFeature.tenant_field_name) continue;

      // Find the plan feature value for this billing feature
      const planFeature = features.find(f => f.feature.code === billingFeature.code);
      if (planFeature) {
        featureDefaults[billingFeature.tenant_field_name] = planFeature.value;
      } else {
        // Default values for features not in plan
        featureDefaults[billingFeature.tenant_field_name] =
          billingFeature.feature_type === 'boolean' ? false : 0;
      }
    }

    console.log('[getPlanDefaults] featureDefaults:', Object.keys(featureDefaults).length, 'entries');
    return featureDefaults;
  };

  // Handle plan change - auto-update limits and permissions
  const handlePlanChange = async (newPlanCode: string) => {
    // Changing plan should remove custom tier since we're resetting to plan defaults
    if (customTier && business) {
      try {
        await deleteCustomTier(business.id);
        setCustomTier(null);
      } catch (error) {
        console.error('Failed to delete custom tier on plan change:', error);
      }
    }

    const featureDefaults = getPlanDefaults(newPlanCode);
    setEditForm(prev => ({
      ...prev,
      plan_code: newPlanCode,
    }));
    // Replace all feature values with plan defaults (includes limits)
    setFeatureValues(featureDefaults);
  };

  // Reset to plan defaults button handler
  const handleResetToPlanDefaults = async () => {
    if (!business) return;

    // If custom tier exists, delete it
    if (customTier) {
      setDeletingCustomTier(true);
      try {
        await deleteCustomTier(business.id);
        setCustomTier(null);
      } catch (error) {
        console.error('Failed to delete custom tier:', error);
        setDeletingCustomTier(false);
        return;
      }
      setDeletingCustomTier(false);
    }

    // Reset all feature values to plan defaults (includes limits)
    const featureDefaults = getPlanDefaults(editForm.plan_code);
    setFeatureValues(featureDefaults);
  };

  // Map tier name/code to plan code
  // Backend returns plan name (e.g., "Pro", "Free") not code (e.g., "PRO", "FREE")
  const tierToPlanCode = (tier: string): string => {
    if (!tier) return 'free';

    const normalized = tier.toLowerCase().trim();

    // Map both names and codes to plan codes
    const mapping: Record<string, string> = {
      // Plan names (what API returns)
      'free': 'free',
      'starter': 'starter',
      'growth': 'growth',
      'pro': 'pro',
      'enterprise': 'enterprise',
      // Legacy tier codes (uppercase)
      'professional': 'pro',
    };

    return mapping[normalized] || normalized;
  };

  // Update form when business changes
  useEffect(() => {
    // Wait for both billingPlans AND billingFeatures to be loaded
    // getPlanDefaults needs both to function correctly
    if (business && billingFeatures && billingPlans) {
      const planCode = tierToPlanCode(business.tier);
      setOriginalPlanCode(planCode);

      // Set core form fields (non-feature fields only)
      setEditForm({
        name: business.name,
        is_active: business.is_active,
        plan_code: planCode,
      });

      // Load custom tier if exists (this will also set featureValues including limits)
      loadCustomTier(business.id);
    }
  }, [business, billingFeatures, billingPlans]);

  // Load custom tier and populate feature values
  const loadCustomTier = async (businessId: number) => {
    console.log('[loadCustomTier] Loading for business:', businessId);
    setLoadingCustomTier(true);
    try {
      const tier = await getCustomTier(businessId);
      console.log('[loadCustomTier] Got tier:', tier ? 'exists' : 'null');
      setCustomTier(tier);

      if (tier && billingFeatures) {
        // Custom tier exists - load features from custom tier
        console.log('[loadCustomTier] Loading from custom tier, features:', Object.keys(tier.features).length);
        const newFeatureValues: Record<string, boolean | number | null> = {};

        // Start with plan defaults, then override with custom tier values
        const planCode = tierToPlanCode(business?.tier || 'free');
        const planDefaults = getPlanDefaults(planCode);

        for (const feature of billingFeatures) {
          if (!feature.tenant_field_name) continue;

          // Get value from custom tier if available, otherwise use plan default
          const customValue = tier.features[feature.code];
          if (customValue !== undefined) {
            newFeatureValues[feature.tenant_field_name] = customValue;
          } else {
            newFeatureValues[feature.tenant_field_name] = planDefaults[feature.tenant_field_name] ??
              (feature.feature_type === 'boolean' ? false : 0);
          }
        }
        console.log('[loadCustomTier] Set featureValues:', Object.keys(newFeatureValues).length, 'entries');
        setFeatureValues(newFeatureValues);
      } else if (business) {
        // No custom tier returned - load from plan defaults
        console.log('[loadCustomTier] No custom tier, loading from plan defaults');
        const planCode = tierToPlanCode(business.tier);
        const featureDefaults = getPlanDefaults(planCode);
        console.log('[loadCustomTier] Plan defaults:', Object.keys(featureDefaults).length, 'entries');
        setFeatureValues(featureDefaults);
      }
    } catch (error) {
      // 404 means no custom tier exists - this is expected, load plan defaults
      console.log('[loadCustomTier] Error (likely 404):', error);
      setCustomTier(null);
      if (business) {
        const planCode = tierToPlanCode(business.tier);
        console.log('[loadCustomTier] Loading plan defaults for:', planCode);
        const featureDefaults = getPlanDefaults(planCode);
        console.log('[loadCustomTier] Plan defaults:', Object.keys(featureDefaults).length, 'entries');
        setFeatureValues(featureDefaults);
      }
    } finally {
      setLoadingCustomTier(false);
    }
  };


  const handleEditSave = async () => {
    if (!business) return;

    const planChanged = editForm.plan_code !== originalPlanCode;

    // If plan changed, update it via the dedicated endpoint
    if (planChanged) {
      changeBusinessPlanMutation.mutate(
        { businessId: business.id, planCode: editForm.plan_code },
        {
          onSuccess: () => {
            // After plan change, update other fields
            saveBusinessFields();
          },
          onError: (error) => {
            console.error('Failed to change plan:', error);
          },
        }
      );
    } else {
      // No plan change, just save other fields
      saveBusinessFields();
    }
  };

  const saveBusinessFields = async () => {
    if (!business || !billingFeatures) return;

    try {
      // Convert featureValues (keyed by tenant_field_name) to feature codes for the backend
      const featuresForBackend: Record<string, boolean | number | null> = {};
      for (const feature of billingFeatures) {
        if (!feature.tenant_field_name) continue;
        const value = featureValues[feature.tenant_field_name];
        if (value !== undefined) {
          // Use feature.code as the key for the backend
          featuresForBackend[feature.code] = value;
        }
      }

      // Save feature values to custom tier
      await updateCustomTier(business.id, featuresForBackend);

      // Extract only the fields that the update endpoint accepts (exclude plan_code and feature values)
      const { plan_code, ...coreFields } = editForm;

      // Update only core business fields (not features, those are in custom tier now)
      updateBusinessMutation.mutate(
        {
          businessId: business.id,
          data: coreFields,
        },
        {
          onSuccess: () => {
            onClose();
          },
        }
      );
    } catch (error) {
      console.error('Failed to save custom tier:', error);
    }
  };

  if (!isOpen || !business) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-3xl mx-4 max-h-[90vh] overflow-y-auto">
        {/* Modal Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
              Edit Business: {business.name}
            </h3>
            {loadingCustomTier ? (
              <span className="px-2 py-1 text-xs rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400">
                Loading...
              </span>
            ) : customTier ? (
              <span className="flex items-center gap-1 px-2 py-1 text-xs rounded-full bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300">
                <AlertCircle size={12} />
                Custom Tier
              </span>
            ) : (
              <span className="px-2 py-1 text-xs rounded-full bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300">
                Plan Defaults
              </span>
            )}
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
          >
            <X size={20} />
          </button>
        </div>

        {/* Modal Body */}
        <div className="p-4 space-y-4">
          {/* Business Name */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Business Name
            </label>
            <input
              type="text"
              value={editForm.name}
              onChange={(e) => setEditForm({ ...editForm, name: e.target.value })}
              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 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            />
          </div>

          {/* Status */}
          <div className="flex items-center justify-between">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                Active Status
              </label>
              <p className="text-xs text-gray-500 dark:text-gray-400">
                Inactive businesses cannot be accessed
              </p>
            </div>
            <button
              type="button"
              onClick={() => setEditForm({ ...editForm, is_active: !editForm.is_active })}
              className={`${editForm.is_active ? 'bg-green-600' : 'bg-gray-300 dark:bg-gray-600'} relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-indigo-500`}
              role="switch"
            >
              <span className={`${editForm.is_active ? 'translate-x-5' : 'translate-x-0'} pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out`} />
            </button>
          </div>

          {/* Subscription Plan */}
          <div>
            <div className="flex items-center justify-between mb-1">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                Subscription Plan
              </label>
              <button
                type="button"
                onClick={handleResetToPlanDefaults}
                disabled={plansLoading || deletingCustomTier}
                className="flex items-center gap-1 text-xs text-indigo-600 dark:text-indigo-400 hover:text-indigo-800 dark:hover:text-indigo-300 disabled:opacity-50"
              >
                <RefreshCw size={12} className={deletingCustomTier ? 'animate-spin' : ''} />
                {deletingCustomTier
                  ? 'Deleting...'
                  : customTier
                  ? 'Delete custom tier & reset to plan defaults'
                  : 'Reset to plan defaults'}
              </button>
            </div>
            <select
              value={editForm.plan_code}
              onChange={(e) => handlePlanChange(e.target.value)}
              disabled={plansLoading}
              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 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50"
            >
              {plansLoading ? (
                <option>Loading plans...</option>
              ) : planOptions.length > 0 ? (
                planOptions.map(plan => (
                  <option key={plan.code} value={plan.code}>
                    {plan.name}
                  </option>
                ))
              ) : (
                <>
                  <option value="free">Free</option>
                  <option value="starter">Starter</option>
                  <option value="growth">Growth</option>
                  <option value="pro">Pro</option>
                  <option value="enterprise">Enterprise</option>
                </>
              )}
            </select>
            <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
              {customTier
                ? 'This business has a custom tier. Feature changes will be saved to the custom tier.'
                : 'Changing plan will auto-update limits and permissions to plan defaults'}
            </p>
          </div>

          {/* Limits & Quotas - Dynamic from billing system */}
          <div className="space-y-4 pt-4 border-t border-gray-200 dark:border-gray-700">
            <DynamicFeaturesEditor
              values={featureValues}
              onChange={(fieldName, value) => {
                setFeatureValues(prev => ({ ...prev, [fieldName]: value }));
              }}
              featureType="integer"
              headerTitle="Limits & Quotas"
              showDescriptions
              columns={4}
            />
          </div>

          {/* Site Builder Access */}
          <div className="space-y-3 pt-4 border-t border-gray-200 dark:border-gray-700">
            <h3 className="text-sm font-medium text-gray-900 dark:text-white">
              Site Builder
            </h3>
            <p className="text-xs text-gray-500 dark:text-gray-400">
              Access the public-facing website builder for this business. Current limit: {(featureValues.max_public_pages === null || featureValues.max_public_pages === -1) ? 'unlimited' : (featureValues.max_public_pages ?? 0)} page{(featureValues.max_public_pages ?? 0) !== 1 ? 's' : ''}.
            </p>
            <a
              href={buildSubdomainUrl(business.subdomain, '/dashboard/site-editor')}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-2 px-4 py-2 bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 rounded-lg hover:bg-indigo-100 dark:hover:bg-indigo-900/30 font-medium text-sm transition-colors"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
              </svg>
              Open Site Builder
            </a>
          </div>

          {/* Features & Permissions - Dynamic from billing system */}
          <div className="space-y-4 pt-4 border-t border-gray-200 dark:border-gray-700">
            <DynamicFeaturesEditor
              values={featureValues}
              onChange={(fieldName, value) => {
                setFeatureValues(prev => ({ ...prev, [fieldName]: value }));
              }}
              featureType="boolean"
              headerTitle="Features & Permissions"
              showDescriptions
            />
          </div>

        </div>

        {/* Modal Footer */}
        <div className="flex items-center justify-end gap-3 p-4 border-t border-gray-200 dark:border-gray-700">
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 font-medium text-sm transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleEditSave}
            disabled={updateBusinessMutation.isPending || changeBusinessPlanMutation.isPending}
            className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-medium text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Save size={16} />
            {updateBusinessMutation.isPending || changeBusinessPlanMutation.isPending ? 'Saving...' : 'Save Changes'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default BusinessEditModal;
