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

export class EpicCreationWizard {
  private interactionManager: InteractionManager;

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

  startEpicCreation() {
    const steps = [
      // Step 1: Basic Information
      {
        id: 'title',
        type: 'question',
        questionType: 'text',
        prompt: '📚 What is the title of your epic?',
        helpText: 'Choose a clear, concise title that describes the major feature or initiative',
        required: true,
        validation: (value: string) => {
          if (!value || value.trim().length < 3) {
            return 'Title must be at least 3 characters long';
          }
          if (value.length > 100) {
            return 'Title must be less than 100 characters';
          }
          return true;
        }
      } as QuestionStep,

      // Step 2: Business Value
      {
        id: 'businessValue',
        type: 'question',
        questionType: 'text',
        prompt: '💼 What business value will this epic deliver?',
        helpText: 'Describe the impact on users, revenue, or strategic goals',
        required: true,
        validation: (value: string) => {
          if (!value || value.trim().length < 10) {
            return 'Please provide a meaningful description of business value (at least 10 characters)';
          }
          return true;
        }
      } as QuestionStep,

      // Step 3: Target Users
      {
        id: 'targetUsers',
        type: 'question',
        questionType: 'text',
        prompt: '👥 Who are the target users or beneficiaries?',
        helpText: 'Identify specific user groups, personas, or stakeholders',
        required: true
      } as QuestionStep,

      // Step 4: Success Criteria
      {
        id: 'successCriteria',
        type: 'question',
        questionType: 'text',
        prompt: '✅ How will you measure success?',
        helpText: 'Define specific, measurable outcomes or KPIs. Separate multiple criteria with semicolons (;)',
        required: true
      } as QuestionStep,

      // Step 5: Priority
      {
        id: 'priority',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '🎯 What is the priority level of this epic?',
        helpText: 'Consider business impact, urgency, and dependencies',
        options: ['Critical', 'High', 'Medium', 'Low'],
        defaultValue: 'Medium',
        required: true
      } as QuestionStep,

      // Step 6: Estimated Effort
      {
        id: 'estimatedEffort',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '⏱️ What is the estimated effort for this epic?',
        helpText: 'Rough estimate to help with planning',
        options: [
          'Small (1-2 sprints)',
          'Medium (3-4 sprints)',
          'Large (5-8 sprints)',
          'Extra Large (9+ sprints)',
          'Unknown'
        ],
        defaultValue: 'Unknown'
      } as QuestionStep,

      // Step 7: Dependencies
      {
        id: 'dependencies',
        type: 'question',
        questionType: 'yesNo',
        prompt: '🔗 Does this epic have dependencies on other work?',
        defaultValue: false
      } as QuestionStep,

      // Step 8: Dependencies Details (conditional)
      {
        id: 'dependencyDetails',
        type: 'question',
        questionType: 'text',
        prompt: '📝 Please describe the dependencies',
        helpText: 'List other epics, external systems, or prerequisites',
        required: false,
        validation: (value: any, responses: any) => {
          // Only validate if user said yes to dependencies
          if (responses.dependencies === true && (!value || value.trim().length === 0)) {
            return 'Please describe the dependencies';
          }
          return true;
        }
      } as QuestionStep,

      // Step 9: Risks
      {
        id: 'risks',
        type: 'question',
        questionType: 'text',
        prompt: '⚠️ What are the main risks or challenges?',
        helpText: 'Identify technical, business, or resource risks',
        required: false
      } as QuestionStep,

      // Step 10: Initial User Stories
      {
        id: 'userStories',
        type: 'question',
        questionType: 'yesNo',
        prompt: '📖 Would you like to define initial user stories now?',
        helpText: 'You can always add more stories later',
        defaultValue: true
      } as QuestionStep,

      // Step 11: Review and Confirmation
      {
        id: 'review',
        type: 'review',
        prompt: '📋 Please review your epic details',
        sections: []  // Will be populated dynamically
      } as ReviewStep,

      // Step 12: Final Confirmation
      {
        id: 'confirmation',
        type: 'confirmation',
        prompt: '✅ Ready to create the epic?',
        summary: {},  // Will be populated dynamically
        editableFields: ['title', 'priority', 'estimatedEffort']
      } as ConfirmationStep
    ];

    // Filter out conditional steps based on responses
    const workflow = this.interactionManager.createWorkflow(
      'Epic Creation Wizard',
      'Interactive epic creation with business context',
      steps
    );

    return workflow;
  }

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

    // Handle conditional logic
    const currentStep = this.interactionManager.getCurrentStep(workflowId);
    
    // Skip dependency details if no dependencies
    if (currentStep?.id === 'dependencies' && response === false) {
      // Mark dependency details as skipped
      workflow.responses['dependencyDetails'] = '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: '📚 Epic Overview',
        content: `**Title**: ${responses.title}
**Priority**: ${responses.priority}
**Estimated Effort**: ${responses.estimatedEffort}`,
        editable: true
      },
      {
        title: '💼 Business Context',
        content: `**Business Value**: ${responses.businessValue}
**Target Users**: ${responses.targetUsers}
**Success Criteria**: ${responses.successCriteria}`,
        editable: false
      }
    ];

    if (responses.risks) {
      reviewStep.sections.push({
        title: '⚠️ Risks & Challenges',
        content: responses.risks,
        editable: true
      });
    }

    if (responses.dependencies === true && responses.dependencyDetails) {
      reviewStep.sections.push({
        title: '🔗 Dependencies',
        content: responses.dependencyDetails,
        editable: true
      });
    }
  }

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

    confirmStep.summary = {
      'Title': responses.title,
      'Priority': responses.priority,
      'Business Value': responses.businessValue,
      'Target Users': responses.targetUsers,
      'Success Criteria': responses.successCriteria,
      'Estimated Effort': responses.estimatedEffort,
      'Has Dependencies': responses.dependencies ? 'Yes' : 'No'
    };

    if (responses.risks) {
      confirmStep.summary['Risks'] = responses.risks;
    }
  }

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

    const responses = result.responses;
    
    // Parse success criteria
    const goals = responses.successCriteria
      .split(';')
      .map((criterion: string) => criterion.trim())
      .filter((criterion: string) => criterion.length > 0);

    // Create the epic
    const epic: Epic = {
      id: `epic-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      title: responses.title,
      description: `Business Value: ${responses.businessValue}\n\nTarget Users: ${responses.targetUsers}`,
      goals,
      priority: responses.priority.toLowerCase() as 'low' | 'medium' | 'high' | 'critical',
      status: 'planned',
      stories: [],
      storyIds: [],
      progress: 0,
      metadata: {
        estimatedEffort: responses.estimatedEffort,
        hasDependencies: responses.dependencies,
        dependencyDetails: responses.dependencyDetails,
        risks: responses.risks,
        targetUsers: responses.targetUsers,
        businessValue: responses.businessValue,
        createdVia: 'interactive-wizard'
      },
      createdAt: new Date(),
      updatedAt: new Date()
    };

    return epic;
  }

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

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