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

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

// Legacy AISuggestion type - kept for backward compatibility
export interface AISuggestion {
  id: string;
  name: string;
  category: string;
  confidence: number;
  suggestedUnit?: string;
  suggestedCost?: number;
  isAccepted?: boolean;
}

// 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;
  };
}

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

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

  // AI-Assisted Path Data
  uploadedFile?: File; // NEW: The actual file object needed for sales import API
  uploadedFileName?: string;
  uploadedFileSize?: number;
  uploadedFileValidation?: ImportValidationResponse; // NEW: Validation result
  aiSuggestions: ProductSuggestionResponse[]; // UPDATED: Use full ProductSuggestionResponse type
  aiAnalysisComplete: boolean;
  categorizedProducts?: any[]; // Products with type classification
  productsWithStock?: any[]; // Products with initial stock levels
  inventoryItems?: InventoryItemForm[]; // NEW: Inventory items created in InventoryReviewStep

  // Setup Progress
  categorizationCompleted: boolean;
  inventoryReviewCompleted: boolean; // NEW: Tracks completion of InventoryReviewStep
  stockEntryCompleted: boolean;
  suppliersCompleted: 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;
  updateAISuggestions: (suggestions: ProductSuggestionResponse[]) => void; // UPDATED type
  updateUploadedFile: (file: File, validation: ImportValidationResponse) => void; // UPDATED: store file object and validation
  setAIAnalysisComplete: (complete: boolean) => void;
  updateCategorizedProducts: (products: any[]) => void;
  updateProductsWithStock: (products: any[]) => void;
  updateInventoryItems: (items: InventoryItemForm[]) => void; // NEW: Store inventory items
  markStepComplete: (step: keyof WizardState) => void;
  getVisibleSteps: () => string[];
  shouldShowStep: (stepId: string) => boolean;
  resetWizard: () => void;
}

const initialState: WizardState = {
  bakeryType: null,
  dataSource: 'ai-assisted', // Only AI-assisted path supported now
  aiSuggestions: [],
  aiAnalysisComplete: false,
  categorizedProducts: undefined,
  productsWithStock: undefined,
  categorizationCompleted: false,
  inventoryReviewCompleted: false, // NEW: Initially false
  stockEntryCompleted: false,
  suppliersCompleted: 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>;
}

export const WizardProvider: React.FC<WizardProviderProps> = ({
  children,
  initialState: providedInitialState,
}) => {
  const [state, setState] = useState<WizardState>({
    ...initialState,
    ...providedInitialState,
    startedAt: providedInitialState?.startedAt || new Date().toISOString(),
  });

  // 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 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 }));
  };

  /**
   * Determines which steps should be visible based on current wizard state
   */
  const getVisibleSteps = (): string[] => {
    const steps: string[] = [];

    // Phase 1: Discovery (Always visible)
    steps.push('bakery-type-selection');

    if (!state.bakeryType) {
      return steps; // Stop here until bakery type is selected
    }

    steps.push('data-source-choice');

    if (!state.dataSource) {
      return steps; // Stop here until data source is selected
    }

    // Phase 2a: AI-Assisted Path
    if (state.dataSource === 'ai-assisted') {
      steps.push('upload-sales-data');

      if (state.uploadedFileName) {
        steps.push('ai-analysis');
      }

      if (state.aiAnalysisComplete) {
        steps.push('review-suggestions');
        steps.push('product-categorization');
      }

      if (state.categorizationCompleted) {
        steps.push('initial-stock-entry');
      }
    }

    // Phase 2b: Core Setup (Common for all paths)
    steps.push('suppliers-setup');
    steps.push('inventory-setup');

    // Conditional: Recipes vs Processes
    if (state.bakeryType === 'production' || state.bakeryType === 'mixed') {
      steps.push('recipes-setup');
    }

    if (state.bakeryType === 'retail' || state.bakeryType === 'mixed') {
      steps.push('production-processes');
    }

    // Phase 3: Advanced Features (Optional)
    steps.push('quality-setup');
    steps.push('team-setup');

    // Phase 4: ML & Finalization
    if (state.inventoryCompleted || state.aiAnalysisComplete) {
      steps.push('ml-training');
    }

    steps.push('setup-review');
    steps.push('completion');

    return steps;
  };

  /**
   * Checks if a specific step should be visible
   */
  const shouldShowStep = (stepId: string): boolean => {
    const visibleSteps = getVisibleSteps();
    return visibleSteps.includes(stepId);
  };

  /**
   * 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,
    updateAISuggestions,
    updateUploadedFile,
    setAIAnalysisComplete,
    updateCategorizedProducts,
    updateProductsWithStock,
    updateInventoryItems,
    markStepComplete,
    getVisibleSteps,
    shouldShowStep,
    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;
};

/**
 * Helper hook to get conditional visibility logic
 */
export const useStepVisibility = () => {
  const { state, shouldShowStep } = useWizardContext();

  return {
    shouldShowRecipes: state.bakeryType === 'production' || state.bakeryType === 'mixed',
    shouldShowProcesses: state.bakeryType === 'retail' || state.bakeryType === 'mixed',
    shouldShowAIPath: state.dataSource === 'ai-assisted',
    shouldShowManualPath: state.dataSource === 'manual',
    isProductionBakery: state.bakeryType === 'production',
    isRetailBakery: state.bakeryType === 'retail',
    isMixedBakery: state.bakeryType === 'mixed',
    hasAISuggestions: state.aiSuggestions.length > 0,
    shouldShowStep,
  };
};

export default WizardContext;
