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

export class SprintPlanningWizard {
  private interactionManager: InteractionManager;

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

  startSprintPlanning(existingStories: Story[] = []) {
    const backlogStories = existingStories.filter(s => !s.sprintId && s.status === 'todo');
    
    const steps = [
      // Step 1: Sprint Name
      {
        id: 'sprintName',
        type: 'question',
        questionType: 'text',
        prompt: '📋 What would you like to name this sprint?',
        helpText: 'Choose a meaningful name that reflects the sprint goal (e.g., "User Authentication Sprint")',
        required: true,
        validation: (value: string) => {
          if (!value || value.trim().length < 3) {
            return 'Sprint name must be at least 3 characters long';
          }
          return true;
        }
      } as QuestionStep,

      // Step 2: Sprint Goal
      {
        id: 'sprintGoal',
        type: 'question',
        questionType: 'text',
        prompt: '🎯 What is the main goal of this sprint?',
        helpText: 'Define a clear, achievable objective that the team will work towards',
        required: true,
        validation: (value: string) => {
          if (!value || value.trim().length < 10) {
            return 'Please provide a meaningful sprint goal (at least 10 characters)';
          }
          return true;
        }
      } as QuestionStep,

      // Step 3: Sprint Duration
      {
        id: 'duration',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '⏱️ How long will this sprint be?',
        helpText: 'Most teams use 2-week sprints, but choose what works for your team',
        options: [
          '1 week',
          '2 weeks (recommended)',
          '3 weeks',
          '4 weeks'
        ],
        defaultValue: '2 weeks (recommended)',
        required: true
      } as QuestionStep,

      // Step 4: Team Size
      {
        id: 'teamSize',
        type: 'question',
        questionType: 'number',
        prompt: '👥 How many team members will participate in this sprint?',
        helpText: 'Include all developers, designers, and other contributors',
        required: true,
        validation: (value: number) => {
          if (!value || value < 1) {
            return 'Team size must be at least 1';
          }
          if (value > 50) {
            return 'Team size seems too large. Consider splitting into multiple teams.';
          }
          return true;
        }
      } as QuestionStep,

      // Step 5: Team Members
      {
        id: 'teamMembers',
        type: 'question',
        questionType: 'text',
        prompt: '👤 Who are the team members?',
        helpText: 'List team member names or emails, separated by commas',
        required: true
      } as QuestionStep,

      // Step 6: Capacity Planning
      {
        id: 'capacityPerPerson',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '⚡ What is the average capacity per team member?',
        helpText: 'Consider holidays, meetings, and other commitments',
        options: [
          '20% (1 day per week)',
          '40% (2 days per week)',
          '60% (3 days per week)',
          '80% (4 days per week)',
          '100% (full time)'
        ],
        defaultValue: '80% (4 days per week)',
        required: true
      } as QuestionStep,

      // Step 7: Story Points per Day
      {
        id: 'velocityEstimate',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '📊 Based on past performance, how many story points can the team complete per day?',
        helpText: 'If unsure, start conservative and adjust in future sprints',
        options: [
          '1-2 points/day (new team)',
          '3-5 points/day (developing team)',
          '6-8 points/day (experienced team)',
          '9+ points/day (high-performing team)',
          'Not sure (we\'ll estimate)'
        ],
        defaultValue: '3-5 points/day (developing team)',
        required: true
      } as QuestionStep,

      // Step 8: Focus Areas
      {
        id: 'focusAreas',
        type: 'question',
        questionType: 'text',
        prompt: '🎯 What are the main focus areas for this sprint?',
        helpText: 'List key features, components, or themes (e.g., "authentication, user profile, API integration")',
        required: true
      } as QuestionStep,

      // Step 9: Known Risks
      {
        id: 'knownRisks',
        type: 'question',
        questionType: 'text',
        prompt: '⚠️ Are there any known risks or dependencies?',
        helpText: 'Identify blockers, external dependencies, or technical challenges',
        required: false
      } as QuestionStep,

      // Step 10: Definition of Done
      {
        id: 'definitionOfDone',
        type: 'question',
        questionType: 'yesNo',
        prompt: '✅ Do you have a clear Definition of Done for this sprint?',
        helpText: 'This ensures everyone agrees on what "complete" means',
        defaultValue: true
      } as QuestionStep,

      // Step 11: DoD Details (conditional)
      {
        id: 'dodDetails',
        type: 'question',
        questionType: 'text',
        prompt: '📝 What are your Definition of Done criteria?',
        helpText: 'List requirements like "code reviewed, tests passing, documented" (separate with semicolons)',
        required: false,
        validation: (value: any, responses: any) => {
          if (responses.definitionOfDone === true && (!value || value.trim().length === 0)) {
            return 'Please provide Definition of Done criteria';
          }
          return true;
        }
      } as QuestionStep,

      // Step 12: Sprint Ceremonies
      {
        id: 'ceremonies',
        type: 'question',
        questionType: 'multiSelect',
        prompt: '📅 Which ceremonies will you conduct?',
        helpText: 'Select all that apply',
        options: [
          'Daily Standup',
          'Sprint Planning (this session)',
          'Sprint Review',
          'Sprint Retrospective',
          'Backlog Refinement'
        ],
        defaultValue: ['Daily Standup', 'Sprint Planning (this session)', 'Sprint Review', 'Sprint Retrospective'],
        required: true
      } as QuestionStep,

      // Step 13: Start Date
      {
        id: 'startDate',
        type: 'question',
        questionType: 'text',
        prompt: '📅 When will the sprint start?',
        helpText: 'Enter a date (e.g., "Monday", "Tomorrow", "2024-01-15")',
        defaultValue: 'Monday',
        required: true
      } as QuestionStep,

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

      // Step 15: Confirmation
      {
        id: 'confirmation',
        type: 'confirmation',
        prompt: '✅ Ready to create the sprint and start planning?',
        summary: {}, // Will be populated dynamically
        editableFields: ['sprintName', 'sprintGoal', 'duration', 'startDate']
      } as ConfirmationStep
    ];

    // Add story selection step if there are backlog items
    if (backlogStories.length > 0) {
      const storySelectionStep: QuestionStep = {
        id: 'storySelection',
        type: 'question',
        questionType: 'text',
        prompt: `📖 Which stories would you like to include in this sprint?\n\nAvailable backlog items:\n${backlogStories.map((s, i) => `${i + 1}. ${s.title} (${s.storyPoints} points)`).join('\n')}\n\nEnter story numbers separated by commas (e.g., "1,3,5") or "none" to skip`,
        helpText: 'Select stories that align with your sprint goal and capacity',
        required: false
      };
      
      // Insert before review step
      steps.splice(steps.length - 2, 0, storySelectionStep);
    }

    const workflow = this.interactionManager.createWorkflow(
      'Sprint Planning Wizard',
      'Interactive sprint planning with capacity and goal setting',
      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 DoD details if no DoD
    if (currentStep?.id === 'definitionOfDone' && response === false) {
      workflow.responses['dodDetails'] = '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;

    // Calculate capacity
    const teamSize = parseInt(responses.teamSize);
    const capacityMap: Record<string, number> = {
      '20% (1 day per week)': 0.2,
      '40% (2 days per week)': 0.4,
      '60% (3 days per week)': 0.6,
      '80% (4 days per week)': 0.8,
      '100% (full time)': 1.0
    };
    const capacityPercent = capacityMap[responses.capacityPerPerson] || 0.8;
    const durationMap: Record<string, number> = {
      '1 week': 5,
      '2 weeks (recommended)': 10,
      '3 weeks': 15,
      '4 weeks': 20
    };
    const workingDays = durationMap[responses.duration] || 10;
    const totalCapacity = teamSize * capacityPercent * workingDays;

    reviewStep.sections = [
      {
        title: '🏃 Sprint Overview',
        content: `**Name**: ${responses.sprintName}
**Goal**: ${responses.sprintGoal}
**Duration**: ${responses.duration}
**Start Date**: ${responses.startDate}`,
        editable: true
      },
      {
        title: '👥 Team & Capacity',
        content: `**Team Size**: ${responses.teamSize} members
**Team Members**: ${responses.teamMembers}
**Capacity**: ${capacityPercent * 100}% per person
**Total Capacity**: ~${Math.round(totalCapacity)} person-days
**Velocity Estimate**: ${responses.velocityEstimate}`,
        editable: false
      },
      {
        title: '🎯 Focus & Planning',
        content: `**Focus Areas**: ${responses.focusAreas}
**Ceremonies**: ${responses.ceremonies}
${responses.definitionOfDone ? `**Definition of Done**: ${responses.dodDetails}` : '**Definition of Done**: Not specified'}`,
        editable: false
      }
    ];

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

    if (responses.storySelection && responses.storySelection !== 'none') {
      reviewStep.sections.push({
        title: '📖 Selected Stories',
        content: `Story IDs: ${responses.storySelection}`,
        editable: true
      });
    }
  }

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

    confirmStep.summary = {
      'Sprint Name': responses.sprintName,
      'Sprint Goal': responses.sprintGoal,
      'Duration': responses.duration,
      'Team Size': `${responses.teamSize} members`,
      'Start Date': responses.startDate,
      'Focus Areas': responses.focusAreas
    };
  }

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

    const responses = result.responses;
    
    // Map duration to days
    const durationMap: Record<string, number> = {
      '1 week': 7,
      '2 weeks (recommended)': 14,
      '3 weeks': 21,
      '4 weeks': 28
    };
    const duration = durationMap[responses.duration] || 14;

    // Parse team members
    const teamMembers = responses.teamMembers
      .split(',')
      .map((member: string) => member.trim())
      .filter((member: string) => member.length > 0);

    // Parse focus areas
    const focusAreas = responses.focusAreas
      .split(',')
      .map((area: string) => area.trim())
      .filter((area: string) => area.length > 0);

    // Parse DoD criteria
    const dodCriteria = responses.dodDetails !== 'N/A' && responses.dodDetails
      ? responses.dodDetails.split(';').map((c: string) => c.trim()).filter((c: string) => c.length > 0)
      : [];

    // Parse selected stories
    const selectedStoryIndices = responses.storySelection && responses.storySelection !== 'none'
      ? responses.storySelection.split(',').map((n: string) => parseInt(n.trim()) - 1).filter((n: number) => !isNaN(n))
      : [];

    return {
      name: responses.sprintName,
      goal: responses.sprintGoal,
      duration,
      startDate: responses.startDate,
      team: teamMembers,
      capacity: responses.capacityPerPerson,
      velocityEstimate: responses.velocityEstimate,
      focusAreas,
      knownRisks: responses.knownRisks,
      definitionOfDone: dodCriteria,
      ceremonies: responses.ceremonies,
      selectedStoryIndices,
      metadata: {
        createdVia: 'interactive-wizard',
        teamSize: parseInt(responses.teamSize)
      }
    };
  }

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