import { InteractionManager } from '../interaction-framework/interaction-manager.js';
import { QuestionStep, ConfirmationStep, ReviewStep } from '../interaction-framework/types.js';
import { BusinessPlan } from './types.js';

export class BusinessPlanWizard {
  private interactionManager: InteractionManager;

  constructor() {
    this.interactionManager = new InteractionManager();
  }

  startBusinessPlanCreation() {
    const steps = [
      // Step 1: Business Concept
      {
        id: 'businessIdea',
        type: 'question',
        questionType: 'text',
        prompt: '💡 What is your business idea?',
        helpText: 'Describe your product or service in 1-2 sentences. What problem does it solve?',
        required: true,
        validation: (value: string) => {
          if (!value || value.trim().length < 10) {
            return 'Please provide a meaningful business idea (at least 10 characters)';
          }
          if (value.length > 500) {
            return 'Please keep your business idea concise (under 500 characters)';
          }
          return true;
        }
      } as QuestionStep,

      // Step 2: Problem Statement
      {
        id: 'problemStatement',
        type: 'question',
        questionType: 'text',
        prompt: '🎯 What problem are you solving?',
        helpText: 'Describe the specific pain point or challenge your target customers face',
        required: true,
        validation: (value: string) => {
          if (!value || value.trim().length < 20) {
            return 'Please describe the problem in detail (at least 20 characters)';
          }
          return true;
        }
      } as QuestionStep,

      // Step 3: Target Market
      {
        id: 'targetMarket',
        type: 'question',
        questionType: 'text',
        prompt: '👥 Who is your target market?',
        helpText: 'Describe your ideal customer. Be specific about demographics, behaviors, and needs',
        required: true
      } as QuestionStep,

      // Step 4: Market Size
      {
        id: 'marketSize',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '📊 How large is your addressable market?',
        helpText: 'Estimate the total addressable market (TAM) for your business',
        options: [
          'Less than $10M',
          '$10M - $100M',
          '$100M - $1B',
          '$1B - $10B',
          'More than $10B',
          'Not sure yet'
        ],
        required: true
      } as QuestionStep,

      // Step 5: Business Model
      {
        id: 'businessModel',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '💰 What is your primary business model?',
        helpText: 'How will you generate revenue?',
        options: [
          'SaaS (Software as a Service)',
          'Marketplace',
          'E-commerce',
          'Subscription',
          'Freemium',
          'Advertising',
          'Consulting/Services',
          'Product Sales',
          'Other'
        ],
        defaultValue: 'SaaS',
        required: true
      } as QuestionStep,

      // Step 6: Revenue Streams
      {
        id: 'revenueStreams',
        type: 'question',
        questionType: 'text',
        prompt: '💵 What are your revenue streams?',
        helpText: 'List your primary ways of making money (separate with semicolons)',
        required: true
      } as QuestionStep,

      // Step 7: Competitive Advantage
      {
        id: 'competitiveAdvantage',
        type: 'question',
        questionType: 'text',
        prompt: '🏆 What is your competitive advantage?',
        helpText: 'What makes you different or better than existing solutions?',
        required: true
      } as QuestionStep,

      // Step 8: Key Metrics
      {
        id: 'keyMetrics',
        type: 'question',
        questionType: 'text',
        prompt: '📈 What are your key success metrics?',
        helpText: 'List 3-5 metrics you will track (e.g., MRR, user growth, retention rate)',
        required: true
      } as QuestionStep,

      // Step 9: Funding Needs
      {
        id: 'fundingNeeds',
        type: 'question',
        questionType: 'yesNo',
        prompt: '💸 Do you need external funding?',
        defaultValue: false
      } as QuestionStep,

      // Step 10: Funding Details (conditional)
      {
        id: 'fundingDetails',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '💰 How much funding are you seeking?',
        helpText: 'Rough estimate for planning purposes',
        options: [
          'Less than $100K',
          '$100K - $500K',
          '$500K - $1M',
          '$1M - $5M',
          '$5M - $10M',
          'More than $10M'
        ],
        required: false
      } as QuestionStep,

      // Step 11: Timeline
      {
        id: 'timeline',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '⏱️ What is your go-to-market timeline?',
        helpText: 'When do you plan to launch?',
        options: [
          'Already launched',
          'Within 3 months',
          '3-6 months',
          '6-12 months',
          'More than 12 months'
        ],
        required: true
      } as QuestionStep,

      // Step 12: Team
      {
        id: 'teamSize',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '👥 What is your current team size?',
        options: [
          'Solo founder',
          '2-3 people',
          '4-10 people',
          '11-25 people',
          'More than 25 people'
        ],
        defaultValue: 'Solo founder'
      } as QuestionStep,

      // Step 13: Key Risks
      {
        id: 'keyRisks',
        type: 'question',
        questionType: 'text',
        prompt: '⚠️ What are the main risks to your business?',
        helpText: 'List technical, market, regulatory, or competitive risks',
        required: false
      } as QuestionStep,

      // Step 14: Financial Projections
      {
        id: 'includeFinancials',
        type: 'question',
        questionType: 'yesNo',
        prompt: '📊 Would you like to include financial projections?',
        helpText: 'We can help you create basic revenue and expense projections',
        defaultValue: true
      } as QuestionStep,

      // Step 15: Plan Template
      {
        id: 'template',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '📄 Which business plan template would you prefer?',
        options: [
          'Lean Canvas (1-page overview)',
          'Traditional (comprehensive)',
          'Investor-focused (pitch-ready)',
          'One-page executive summary'
        ],
        defaultValue: 'Lean Canvas (1-page overview)'
      } as QuestionStep,

      // Step 16: Review
      {
        id: 'review',
        type: 'review',
        prompt: '📋 Please review your business plan inputs',
        sections: [] // Will be populated dynamically
      } as ReviewStep,

      // Step 17: Confirmation
      {
        id: 'confirmation',
        type: 'confirmation',
        prompt: '✅ Ready to generate your business plan?',
        summary: {}, // Will be populated dynamically
        editableFields: ['businessIdea', 'targetMarket', 'businessModel']
      } as ConfirmationStep
    ];

    const workflow = this.interactionManager.createWorkflow(
      'Business Plan Creation Wizard',
      'Interactive business plan generation with market insights',
      steps
    );

    return workflow;
  }

  async processWorkflowResponse(workflowId: string, response: any) {
    const workflow = this.interactionManager.getWorkflow(workflowId);
    if (!workflow) {
      throw new Error('Workflow not found');
    }

    const currentStep = this.interactionManager.getCurrentStep(workflowId);
    
    // Skip funding details if no funding needed
    if (currentStep?.id === 'fundingNeeds' && response === false) {
      workflow.responses['fundingDetails'] = 'N/A';
      workflow.currentStep++; // Skip the next step
    }

    // Process the response
    const result = await this.interactionManager.processResponse(workflowId, response);
    
    // Update review/confirmation steps with collected data
    if (result.nextStep?.id === 'review') {
      this.updateReviewStep(workflow);
    } else if (result.nextStep?.id === 'confirmation') {
      this.updateConfirmationStep(workflow);
    }

    return result;
  }

  private updateReviewStep(workflow: any) {
    const reviewStep = workflow.steps.find((s: any) => s.id === 'review') as ReviewStep;
    const responses = workflow.responses;

    reviewStep.sections = [
      {
        title: '💡 Business Concept',
        content: `**Idea**: ${responses.businessIdea}
**Problem**: ${responses.problemStatement}
**Competitive Advantage**: ${responses.competitiveAdvantage}`,
        editable: true
      },
      {
        title: '📊 Market Analysis',
        content: `**Target Market**: ${responses.targetMarket}
**Market Size**: ${responses.marketSize}
**Business Model**: ${responses.businessModel}`,
        editable: true
      },
      {
        title: '💰 Financial Plan',
        content: `**Revenue Streams**: ${responses.revenueStreams}
**Funding Needed**: ${responses.fundingNeeds ? 'Yes' : 'No'}
${responses.fundingDetails && responses.fundingDetails !== 'N/A' ? `**Funding Amount**: ${responses.fundingDetails}` : ''}`,
        editable: false
      },
      {
        title: '📈 Execution Plan',
        content: `**Key Metrics**: ${responses.keyMetrics}
**Timeline**: ${responses.timeline}
**Team Size**: ${responses.teamSize}`,
        editable: false
      }
    ];

    if (responses.keyRisks) {
      reviewStep.sections.push({
        title: '⚠️ Risk Assessment',
        content: responses.keyRisks,
        editable: true
      });
    }
  }

  private updateConfirmationStep(workflow: any) {
    const confirmStep = workflow.steps.find((s: any) => s.id === 'confirmation') as ConfirmationStep;
    const responses = workflow.responses;

    confirmStep.summary = {
      'Business Idea': responses.businessIdea,
      'Target Market': responses.targetMarket,
      'Market Size': responses.marketSize,
      'Business Model': responses.businessModel,
      'Timeline': responses.timeline,
      'Template': this.mapTemplateChoice(responses.template),
      'Include Financials': responses.includeFinancials ? 'Yes' : 'No'
    };
  }

  private mapTemplateChoice(template: string): string {
    const templateMap: Record<string, string> = {
      'Lean Canvas (1-page overview)': 'lean_canvas',
      'Traditional (comprehensive)': 'traditional',
      'Investor-focused (pitch-ready)': 'investor',
      'One-page executive summary': 'one_page'
    };
    return templateMap[template] || 'lean_canvas';
  }

  completeWorkflow(workflowId: string): any {
    const result = this.interactionManager.completeWorkflow(workflowId);
    if (!result || !result.completed) return undefined;

    const responses = result.responses;
    
    // Map template choice
    const template = this.mapTemplateChoice(responses.template);
    
    // Parse revenue streams
    const revenueStreams = responses.revenueStreams
      .split(';')
      .map((stream: string) => stream.trim())
      .filter((stream: string) => stream.length > 0);

    // Parse key metrics
    const keyMetrics = responses.keyMetrics
      .split(/[,;]/)
      .map((metric: string) => metric.trim())
      .filter((metric: string) => metric.length > 0);

    return {
      businessIdea: responses.businessIdea,
      problemStatement: responses.problemStatement,
      targetMarket: responses.targetMarket,
      marketSize: responses.marketSize,
      businessModel: responses.businessModel,
      revenueStreams,
      competitiveAdvantage: responses.competitiveAdvantage,
      keyMetrics,
      fundingNeeds: responses.fundingNeeds,
      fundingAmount: responses.fundingDetails !== 'N/A' ? responses.fundingDetails : undefined,
      timeline: responses.timeline,
      teamSize: responses.teamSize,
      keyRisks: responses.keyRisks,
      includeFinancials: responses.includeFinancials,
      template,
      metadata: {
        createdVia: 'interactive-wizard',
        wizardVersion: '1.0'
      }
    };
  }

  formatCurrentStep(workflowId: string): string {
    const workflow = this.interactionManager.getWorkflow(workflowId);
    if (!workflow) return 'Workflow not found';

    const currentStep = this.interactionManager.getCurrentStep(workflowId);
    if (!currentStep) return 'No current step';

    const progress = `Step ${workflow.currentStep + 1} of ${workflow.steps.length}`;
    const prompt = this.interactionManager.formatStepPrompt(currentStep);

    return `${progress}\n\n${prompt}`;
  }

  cancelWorkflow(workflowId: string): boolean {
    return this.interactionManager.cancelWorkflow(workflowId);
  }
}