// COMPLETE WORKING PROJECT STORE - Updated with Template-Manager API
import { create } from 'zustand';
import { getTemplateByType, transformFeatureData, generateSessionId, trackFeatureUsage } from '../services/api';

const useProjectStore = create((set, get) => ({
  // Step management
  currentStep: 'project-type', // Start with project-type, not features
  
  // Project basic info
  projectType: null,
  projectName: '',
  
  // Feature management
  selectedFeatures: [],
  availableSuggestions: [],
  
  // NEW: Session management for tracking
  userSession: generateSessionId(),
  
  // NEW: API state management
  isLoadingFeatures: false,
  featuresError: null,
  
  // Data flow
  projectData: {},
  finalProjectData: {},
  techStackRecommendations: null,
  businessQuestionsCompleted: false,
  
  // Architecture Design state
  architectureDesign: null,
  isGeneratingArchitecture: false,
  architectureError: null,

  // === PROJECT TYPE & NAME ACTIONS (UPDATED) ===
  setProjectType: async (type) => {
    set({ 
      projectType: type,
      isLoadingFeatures: true,
      featuresError: null,
      selectedFeatures: [], // Reset selected features
      availableSuggestions: [] // Reset suggestions
    });
    
    try {
      console.log(`🎯 Loading features for project type: ${type}`);
      
      // Fetch template with features from Template-Manager API
      const templateData = await getTemplateByType(type);
      
      if (templateData && templateData.features) {
        // Transform API features to match current format
        const transformedFeatures = transformFeatureData(templateData.features);
        
        console.log(`✅ Loaded ${transformedFeatures.length} features for ${type}:`, transformedFeatures);
        
        // Set suggestions (all features are initially suggestions)
        set({ 
          availableSuggestions: transformedFeatures,
          isLoadingFeatures: false,
          featuresError: null
        });
      } else {
        console.warn(`⚠️ No features found for project type: ${type}`);
        set({ 
          availableSuggestions: [],
          isLoadingFeatures: false,
          featuresError: null
        });
      }
      
    } catch (error) {
      console.error(`❌ Failed to load features for ${type}:`, error);
      set({ 
        availableSuggestions: [],
        isLoadingFeatures: false,
        featuresError: error.message
      });
    }
  },
  
  setProjectName: (name) => set({ projectName: name }),

  // === FEATURE MANAGEMENT ACTIONS (ENHANCED) ===
  addFeature: async (feature) => {
    set((state) => {
      // Don't add if already exists
      const exists = state.selectedFeatures.some(f => f.id === feature.id);
      if (exists) return state;
      
      // Add with proper order
      const newFeature = {
        ...feature,
        order: state.selectedFeatures.length + 1
      };
      
      // Remove from suggestions if it was a suggestion
      const newSuggestions = state.availableSuggestions.filter(s => s.id !== feature.id);
      
      // Track feature usage (non-blocking)
      const session = state.userSession;
      const projectId = `${state.projectType}_${Date.now()}`;
      
      if (feature.template_feature_id) {
        trackFeatureUsage(feature.template_feature_id, session, projectId).catch(err => {
          console.warn('⚠️ Failed to track feature usage:', err);
        });
      }
      
      console.log(`➕ Added feature: ${feature.name} (${feature.type})`);
      
      return {
        selectedFeatures: [...state.selectedFeatures, newFeature],
        availableSuggestions: newSuggestions
      };
    });
  },

  removeFeature: (featureId) => {
    set((state) => {
      const featureToRemove = state.selectedFeatures.find(f => f.id === featureId);
      const updatedFeatures = state.selectedFeatures.filter(f => f.id !== featureId);
      
      // Reorder remaining features
      const reorderedFeatures = updatedFeatures.map((feature, index) => ({
        ...feature,
        order: index + 1
      }));
      
      // Add back to suggestions if it was originally a suggestion and is a default feature
      let newSuggestions = state.availableSuggestions;
      if (featureToRemove && featureToRemove.isDefault) {
        newSuggestions = [...state.availableSuggestions, featureToRemove];
      }
      
      console.log(`➖ Removed feature: ${featureToRemove?.name}`);
      
      return {
        selectedFeatures: reorderedFeatures,
        availableSuggestions: newSuggestions
      };
    });
  },

  reorderFeatures: (startIndex, endIndex) => {
    set((state) => {
      const result = Array.from(state.selectedFeatures);
      const [removed] = result.splice(startIndex, 1);
      result.splice(endIndex, 0, removed);
      
      // Update order property
      const reorderedFeatures = result.map((feature, index) => ({
        ...feature,
        order: index + 1
      }));
      
      console.log('🔄 Features reordered');
      
      return { selectedFeatures: reorderedFeatures };
    });
  },

  // NEW: Reload features from API
  reloadFeatures: async () => {
    const state = get();
    if (state.projectType) {
      await get().setProjectType(state.projectType);
    }
  },

  // NEW: Add custom feature and save to database
  addCustomFeature: async (customFeature) => {
    try {
      console.log('🎨 Adding custom feature:', customFeature);
      
      // Add to local state immediately for better UX
      const localFeature = {
        id: `custom_${Date.now()}`,
        name: customFeature.name,
        description: customFeature.description,
        type: 'custom',
        complexity: customFeature.complexity,
        order: get().selectedFeatures.length + 1,
        isDefault: false,
        isCustom: true
      };
      
      // Add to selected features
      set((state) => ({
        selectedFeatures: [...state.selectedFeatures, localFeature]
      }));
      
      // TODO: In Phase 2, we'll save to Template-Manager API
      // const savedFeature = await addCustomFeature(templateId, customFeature);
      
      console.log('✅ Custom feature added locally');
      return localFeature;
      
    } catch (error) {
      console.error('❌ Failed to add custom feature:', error);
      throw error;
    }
  },

  // === STEP NAVIGATION ===
  setCurrentStep: (step) => set({ currentStep: step }),
  
  goToNextStep: () => {
    const current = get().currentStep;
    const steps = ['project-type', 'features', 'business-questions', 'summary', 'architecture'];
    const currentIndex = steps.indexOf(current);
    if (currentIndex < steps.length - 1) {
      set({ currentStep: steps[currentIndex + 1] });
    }
  },

  goToPreviousStep: () => {
    const current = get().currentStep;
    const steps = ['project-type', 'features', 'business-questions', 'summary', 'architecture'];
    const currentIndex = steps.indexOf(current);
    if (currentIndex > 0) {
      set({ currentStep: steps[currentIndex - 1] });
    }
  },

  // === DATA MANAGEMENT ===
  setProjectData: (data) => set({ projectData: data }),
  setFinalProjectData: (data) => set({ finalProjectData: data }),
  setTechStackRecommendations: (recommendations) => set({ 
    techStackRecommendations: recommendations 
  }),

  // === ARCHITECTURE DESIGN ACTIONS ===
  setArchitectureDesign: (design) => set({ 
    architectureDesign: design,
    architectureError: null 
  }),
  
  setGeneratingArchitecture: (isGenerating) => set({ 
    isGeneratingArchitecture: isGenerating 
  }),
  
  setArchitectureError: (error) => set({ 
    architectureError: error,
    isGeneratingArchitecture: false 
  }),
  
  clearArchitectureDesign: () => set({ 
    architectureDesign: null,
    architectureError: null,
    isGeneratingArchitecture: false 
  }),

  // === UTILITY METHODS ===
  getCompleteProjectData: () => {
    const state = get();
    return {
      projectType: state.projectType,
      projectName: state.projectName,
      selectedFeatures: state.selectedFeatures,
      projectData: state.projectData,
      finalProjectData: state.finalProjectData,
      techStackRecommendations: state.techStackRecommendations,
      architectureDesign: state.architectureDesign,
      currentStep: state.currentStep,
      userSession: state.userSession
    };
  },

  // NEW: Get project summary for API calls
  getProjectSummary: () => {
    const state = get();
    return {
      projectType: state.projectType,
      projectName: state.projectName,
      selectedFeatures: state.selectedFeatures.map(f => ({
        id: f.id,
        name: f.name,
        description: f.description,
        type: f.type,
        complexity: f.complexity,
        isCustom: f.isCustom || false
      })),
      featureCount: state.selectedFeatures.length,
      userSession: state.userSession
    };
  },

  // Reset store (useful for testing)
  resetStore: () => set({
    currentStep: 'project-type',
    projectType: null,
    projectName: '',
    selectedFeatures: [],
    availableSuggestions: [],
    userSession: generateSessionId(),
    isLoadingFeatures: false,
    featuresError: null,
    projectData: {},
    finalProjectData: {},
    techStackRecommendations: null,
    businessQuestionsCompleted: false,
    architectureDesign: null,
    isGeneratingArchitecture: false,
    architectureError: null
  })
}));

export default useProjectStore;