import React, { createContext, useContext, useState, useEffect, useMemo, ReactNode } from 'react';
import type { ProductSuggestionResponse } from '../../../../api/types/inventory';
import type { ImportValidationResponse } from '../../../../api/types/dataImport';
import type { UserProgress } from '../../../../api/types/onboarding';

export type BakeryType = 'production' | 'retail' | 'mixed' | null;
export type DataSource = 'ai-assisted' | 'manual' | null;

// Inventory item structure from InventoryReviewStep
export interface InventoryItemForm {
  id: string;
  name: string;
  product_type: string;
  category: string;
  unit_of_measure: string;
  isSuggested?: boolean;
  confidence_score?: number;
  sales_data?: {
    total_quantity: number;
    total_revenue: number;
    average_price: number;
  };
}

// Child tenant interface for enterprise onboarding
export interface ChildTenantData {
  id: string;
  name: string;
  city: string;
  zone?: string;
  address: string;
  postal_code: string;
  location_code: string;
}

export interface WizardState {
  // Discovery Phase
  bakeryType: BakeryType;
  dataSource: DataSource;

  // Core Setup Data
  tenantId?: string;
  bakeryLocation?: {
    latitude: number;
    longitude: number;
  };

  // Enterprise Setup Data
  childTenants?: ChildTenantData[]; // Child tenant locations for enterprise tier
  childTenantsCompleted: boolean;

  // AI-Assisted Path Data
  uploadedFile?: File;
  uploadedFileName?: string;
  uploadedFileSize?: number;
  uploadedFileValidation?: ImportValidationResponse;
  aiSuggestions: ProductSuggestionResponse[];
  aiAnalysisComplete: boolean;
  categorizedProducts?: any[];
  productsWithStock?: any[];
  inventoryItems?: InventoryItemForm[];

  // Setup Progress
  categorizationCompleted: boolean;
  inventoryReviewCompleted: boolean;
  stockEntryCompleted: boolean;
  suppliersCompleted: boolean;
  inventorySetupCompleted: boolean;
  inventoryCompleted: boolean;
  recipesCompleted: boolean;
  processesCompleted: boolean;
  qualityCompleted: boolean;
  teamCompleted: boolean;

  // ML Training
  mlTrainingComplete: boolean;
  mlTrainingSkipped: boolean;

  // Metadata
  startedAt?: string;
  completedAt?: string;
}

export interface WizardContextValue {
  state: WizardState;
  updateBakeryType: (type: BakeryType) => void;
  updateDataSource: (source: DataSource) => void;
  updateTenantInfo: (tenantId: string, location: { latitude: number; longitude: number }) => void;
  updateLocation: (location: { latitude: number; longitude: number }) => void;
  updateTenantId: (tenantId: string) => void;
  updateChildTenants: (tenants: ChildTenantData[]) => void;
  updateAISuggestions: (suggestions: ProductSuggestionResponse[]) => void;
  updateUploadedFile: (file: File, validation: ImportValidationResponse) => void;
  setAIAnalysisComplete: (complete: boolean) => void;
  updateCategorizedProducts: (products: any[]) => void;
  updateProductsWithStock: (products: any[]) => void;
  updateInventoryItems: (items: InventoryItemForm[]) => void;
  markStepComplete: (step: keyof WizardState) => void;
  resetWizard: () => void;
}

const initialState: WizardState = {
  bakeryType: null,
  dataSource: 'ai-assisted',
  childTenants: undefined,
  childTenantsCompleted: false,
  aiSuggestions: [],
  aiAnalysisComplete: false,
  categorizedProducts: undefined,
  productsWithStock: undefined,
  categorizationCompleted: false,
  inventoryReviewCompleted: false,
  stockEntryCompleted: false,
  suppliersCompleted: false,
  inventorySetupCompleted: false,
  inventoryCompleted: false,
  recipesCompleted: false,
  processesCompleted: false,
  qualityCompleted: false,
  teamCompleted: false,
  mlTrainingComplete: false,
  mlTrainingSkipped: false,
};

const WizardContext = createContext<WizardContextValue | undefined>(undefined);

export interface WizardProviderProps {
  children: ReactNode;
  initialState?: Partial<WizardState>;
  backendProgress?: UserProgress;
}

/**
 * Derives WizardState from backend context_state.
 * This ensures conditional steps remain visible based on previous progress.
 */
function deriveStateFromBackendProgress(
  backendProgress: UserProgress | undefined,
  providedInitialState?: Partial<WizardState>
): Partial<WizardState> {
  if (!backendProgress?.context_state) {
    return providedInitialState || {};
  }

  const ctx = backendProgress.context_state;

  // Map backend context state to frontend WizardState
  const derivedState: Partial<WizardState> = {
    // Discovery Phase
    bakeryType: ctx.bakery_type as BakeryType,

    // Core Setup Data
    tenantId: ctx.tenant_id || undefined,

    // AI-Assisted Path completion flags
    aiAnalysisComplete: ctx.ai_analysis_complete,
    inventoryReviewCompleted: ctx.inventory_review_completed,
    stockEntryCompleted: ctx.stock_entry_completed,
    categorizationCompleted: ctx.categorization_completed,

    // Setup Progress
    suppliersCompleted: ctx.suppliers_completed,
    inventorySetupCompleted: ctx.inventory_setup_completed,
    recipesCompleted: ctx.recipes_completed,
    qualityCompleted: ctx.quality_completed,
    teamCompleted: ctx.team_completed,
    childTenantsCompleted: ctx.child_tenants_completed,

    // ML Training
    mlTrainingComplete: ctx.ml_training_complete,
  };

  // Merge with provided initial state (provided takes precedence for explicit overrides)
  return {
    ...derivedState,
    ...providedInitialState,
  };
}

export const WizardProvider: React.FC<WizardProviderProps> = ({
  children,
  initialState: providedInitialState,
  backendProgress,
}) => {
  // Derive initial state from backend progress if available
  const derivedInitialState = useMemo(() => {
    const derived = deriveStateFromBackendProgress(backendProgress, providedInitialState);
    return {
      ...initialState,
      ...derived,
      startedAt: providedInitialState?.startedAt || new Date().toISOString(),
    };
  }, [backendProgress, providedInitialState]);

  const [state, setState] = useState<WizardState>(derivedInitialState);

  // Update state when backend progress changes (e.g., on refetch)
  useEffect(() => {
    if (backendProgress?.context_state) {
      const derived = deriveStateFromBackendProgress(backendProgress, providedInitialState);
      setState(prev => ({
        ...prev,
        ...derived,
      }));
    }
  }, [backendProgress, providedInitialState]);

  // SECURITY: Removed localStorage persistence for wizard state
  // All onboarding progress is now tracked exclusively via backend API
  // (services/auth/app/api/onboarding_progress.py) to ensure data security
  // and consistency across sessions. No wizard data is stored locally.

  // Clean up any old wizardState data on mount (security fix)
  useEffect(() => {
    try {
      localStorage.removeItem('wizardState');
      localStorage.removeItem('registration_progress');
    } catch (err) {
      console.error('Error cleaning up old localStorage data:', err);
    }
  }, []);

  const updateBakeryType = (type: BakeryType) => {
    setState(prev => ({ ...prev, bakeryType: type }));
  };

  const updateDataSource = (source: DataSource) => {
    setState(prev => ({ ...prev, dataSource: source }));
  };

  const updateTenantInfo = (tenantId: string, location: { latitude: number; longitude: number }) => {
    setState(prev => ({ 
      ...prev, 
      tenantId,
      bakeryLocation: location
    }));
  };
  
  const updateLocation = (location: { latitude: number; longitude: number }) => {
    setState(prev => ({ 
      ...prev, 
      bakeryLocation: location
    }));
  };
  
  const updateTenantId = (tenantId: string) => {
    setState(prev => ({
      ...prev,
      tenantId
    }));
  };

  const updateChildTenants = (tenants: ChildTenantData[]) => {
    setState(prev => ({ ...prev, childTenants: tenants }));
  };

  const updateAISuggestions = (suggestions: ProductSuggestionResponse[]) => {
    setState(prev => ({ ...prev, aiSuggestions: suggestions }));
  };

  const updateUploadedFile = (file: File, validation: ImportValidationResponse) => {
    setState(prev => ({
      ...prev,
      uploadedFile: file,
      uploadedFileName: file.name,
      uploadedFileSize: file.size,
      uploadedFileValidation: validation,
    }));
  };

  const setAIAnalysisComplete = (complete: boolean) => {
    setState(prev => ({ ...prev, aiAnalysisComplete: complete }));
  };

  const updateCategorizedProducts = (products: any[]) => {
    setState(prev => ({ ...prev, categorizedProducts: products }));
  };

  const updateProductsWithStock = (products: any[]) => {
    setState(prev => ({ ...prev, productsWithStock: products }));
  };

  const updateInventoryItems = (items: InventoryItemForm[]) => {
    setState(prev => ({ ...prev, inventoryItems: items }));
  };

  const markStepComplete = (step: keyof WizardState) => {
    setState(prev => ({ ...prev, [step]: true }));
  };

  /**
   * Resets wizard state to initial values
   */
  const resetWizard = () => {
    setState({
      ...initialState,
      startedAt: new Date().toISOString(),
    });
    // No localStorage cleanup needed - we don't store wizard state locally anymore
  };

  const value: WizardContextValue = {
    state,
    updateBakeryType,
    updateDataSource,
    updateTenantInfo,
    updateLocation,
    updateTenantId,
    updateChildTenants,
    updateAISuggestions,
    updateUploadedFile,
    setAIAnalysisComplete,
    updateCategorizedProducts,
    updateProductsWithStock,
    updateInventoryItems,
    markStepComplete,
    resetWizard,
  };

  return (
    <WizardContext.Provider value={value}>
      {children}
    </WizardContext.Provider>
  );
};

/**
 * Hook to access wizard context
 */
export const useWizardContext = (): WizardContextValue => {
  const context = useContext(WizardContext);
  if (!context) {
    throw new Error('useWizardContext must be used within a WizardProvider');
  }
  return context;
};

export default WizardContext;
