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

export class BoardSetupWizard {
  private interactionManager: InteractionManager;

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

  startBoardSetup() {
    const steps = [
      // Step 1: Board Name
      {
        id: 'boardName',
        type: 'question',
        questionType: 'text',
        prompt: '📋 What would you like to name your Kanban board?',
        helpText: 'Choose a name that reflects the project or team (e.g., "Product Development", "Marketing Campaigns")',
        required: true,
        validation: (value: string) => {
          if (!value || value.trim().length < 3) {
            return 'Board name must be at least 3 characters long';
          }
          if (value.length > 50) {
            return 'Board name must be less than 50 characters';
          }
          return true;
        }
      } as QuestionStep,

      // Step 2: Team Workflow
      {
        id: 'workflowType',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '🔄 What type of workflow does your team follow?',
        helpText: 'This helps us suggest appropriate columns for your board',
        options: [
          'Software Development',
          'Marketing/Content',
          'Sales Pipeline',
          'Customer Support',
          'Generic Task Management',
          'Custom Workflow'
        ],
        defaultValue: 'Software Development',
        required: true
      } as QuestionStep,

      // Step 3: Team Size
      {
        id: 'teamSize',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '👥 How many people will use this board?',
        helpText: 'This helps us optimize the board layout',
        options: [
          'Just me',
          '2-5 people',
          '6-10 people',
          '11-20 people',
          'More than 20 people'
        ],
        defaultValue: '2-5 people',
        required: true
      } as QuestionStep,

      // Step 4: Work Item Types
      {
        id: 'workItemTypes',
        type: 'question',
        questionType: 'text',
        prompt: '📝 What types of work items will you track?',
        helpText: 'List the types separated by commas (e.g., "Features, Bugs, Tasks, Improvements")',
        defaultValue: 'Features, Bugs, Tasks',
        required: true
      } as QuestionStep,

      // Step 5: Column Preferences
      {
        id: 'columnPreference',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '🏗️ How would you like to set up your columns?',
        options: [
          'Use recommended columns for my workflow',
          'Start with basic columns (To Do, In Progress, Done)',
          'Let me customize my columns'
        ],
        defaultValue: 'Use recommended columns for my workflow',
        required: true
      } as QuestionStep,

      // Step 6: Custom Columns (conditional)
      {
        id: 'customColumns',
        type: 'question',
        questionType: 'text',
        prompt: '📊 Enter your custom column names',
        helpText: 'List column names in order, separated by commas (e.g., "Backlog, Analysis, Development, Testing, Done")',
        required: false,
        validation: (value: any, responses: any) => {
          if (responses.columnPreference === 'Let me customize my columns' && (!value || value.trim().length === 0)) {
            return 'Please provide column names';
          }
          return true;
        }
      } as QuestionStep,

      // Step 7: WIP Limits
      {
        id: 'useWipLimits',
        type: 'question',
        questionType: 'yesNo',
        prompt: '🚦 Would you like to set Work In Progress (WIP) limits?',
        helpText: 'WIP limits help prevent overload and improve flow',
        defaultValue: true
      } as QuestionStep,

      // Step 8: WIP Limit Values (conditional)
      {
        id: 'wipLimitValue',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '📏 What WIP limit would you like per person?',
        helpText: 'This limits how many items can be "In Progress" at once',
        options: [
          '1 item per person',
          '2 items per person',
          '3 items per person',
          '5 items per person',
          'No limit'
        ],
        defaultValue: '2 items per person',
        required: false
      } as QuestionStep,

      // Step 9: Priority Levels
      {
        id: 'priorityLevels',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '🎯 How many priority levels do you need?',
        options: [
          'Simple (High, Low)',
          'Standard (High, Medium, Low)',
          'Detailed (Critical, High, Medium, Low)',
          'No priorities'
        ],
        defaultValue: 'Standard (High, Medium, Low)',
        required: true
      } as QuestionStep,

      // Step 10: Labels/Tags
      {
        id: 'useTags',
        type: 'question',
        questionType: 'yesNo',
        prompt: '🏷️ Would you like to use labels/tags for categorization?',
        helpText: 'Tags help filter and organize work items',
        defaultValue: true
      } as QuestionStep,

      // Step 11: Initial Tags (conditional)
      {
        id: 'initialTags',
        type: 'question',
        questionType: 'text',
        prompt: '🏷️ What initial tags would you like to create?',
        helpText: 'List tags separated by commas (e.g., "frontend, backend, urgent, documentation")',
        required: false
      } as QuestionStep,

      // Step 12: Automation
      {
        id: 'automationPreference',
        type: 'question',
        questionType: 'multipleChoice',
        prompt: '🤖 Would you like any automation rules?',
        helpText: 'Automation can help move cards or update statuses automatically',
        options: [
          'No automation',
          'Basic automation (auto-move completed items)',
          'Advanced automation (I\'ll set up rules later)'
        ],
        defaultValue: 'Basic automation (auto-move completed items)'
      } as QuestionStep,

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

      // Step 14: Confirmation
      {
        id: 'confirmation',
        type: 'confirmation',
        prompt: '✅ Ready to create your Kanban board?',
        summary: {}, // Will be populated dynamically
        editableFields: ['boardName', 'workflowType']
      } as ConfirmationStep
    ];

    const workflow = this.interactionManager.createWorkflow(
      'Kanban Board Setup Wizard',
      'Interactive board creation with workflow optimization',
      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 custom columns if not customizing
    if (currentStep?.id === 'columnPreference' && response !== 'Let me customize my columns') {
      workflow.responses['customColumns'] = 'N/A';
      workflow.currentStep++; // Skip the next step
    }

    // Skip WIP limit value if not using WIP limits
    if (currentStep?.id === 'useWipLimits' && response === false) {
      workflow.responses['wipLimitValue'] = 'N/A';
      workflow.currentStep++;
    }

    // Skip initial tags if not using tags
    if (currentStep?.id === 'useTags' && response === false) {
      workflow.responses['initialTags'] = 'N/A';
      workflow.currentStep++;
    }

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

    // Determine columns based on preferences
    const columns = this.determineColumns(responses);

    reviewStep.sections = [
      {
        title: '📋 Board Configuration',
        content: `**Name**: ${responses.boardName}
**Workflow Type**: ${responses.workflowType}
**Team Size**: ${responses.teamSize}`,
        editable: true
      },
      {
        title: '📊 Columns',
        content: `**Setup**: ${responses.columnPreference}
**Columns**: ${columns.join(' → ')}`,
        editable: true
      },
      {
        title: '⚙️ Board Settings',
        content: `**Work Item Types**: ${responses.workItemTypes}
**Priority Levels**: ${responses.priorityLevels}
**WIP Limits**: ${responses.useWipLimits ? responses.wipLimitValue : 'Disabled'}
**Tags**: ${responses.useTags ? 'Enabled' : 'Disabled'}`,
        editable: false
      }
    ];

    if (responses.initialTags && responses.initialTags !== 'N/A') {
      reviewStep.sections.push({
        title: '🏷️ Initial Tags',
        content: responses.initialTags,
        editable: true
      });
    }

    reviewStep.sections.push({
      title: '🤖 Automation',
      content: responses.automationPreference,
      editable: false
    });
  }

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

    confirmStep.summary = {
      'Board Name': responses.boardName,
      'Workflow Type': responses.workflowType,
      'Columns': columns.join(' → '),
      'Team Size': responses.teamSize,
      'WIP Limits': responses.useWipLimits ? 'Enabled' : 'Disabled',
      'Tags': responses.useTags ? 'Enabled' : 'Disabled'
    };
  }

  private determineColumns(responses: any): string[] {
    if (responses.columnPreference === 'Let me customize my columns' && responses.customColumns !== 'N/A') {
      return responses.customColumns.split(',').map((col: string) => col.trim()).filter((col: string) => col.length > 0);
    }

    if (responses.columnPreference === 'Start with basic columns (To Do, In Progress, Done)') {
      return ['To Do', 'In Progress', 'Done'];
    }

    // Recommended columns based on workflow type
    const workflowColumns: Record<string, string[]> = {
      'Software Development': ['Backlog', 'Ready', 'In Development', 'Code Review', 'Testing', 'Done'],
      'Marketing/Content': ['Ideas', 'Planning', 'In Creation', 'Review', 'Scheduled', 'Published'],
      'Sales Pipeline': ['Leads', 'Qualified', 'Proposal', 'Negotiation', 'Closed Won', 'Closed Lost'],
      'Customer Support': ['New', 'Triaged', 'In Progress', 'Waiting on Customer', 'Resolved'],
      'Generic Task Management': ['To Do', 'In Progress', 'Review', 'Done'],
      'Custom Workflow': ['Backlog', 'To Do', 'In Progress', 'Review', 'Done']
    };

    return workflowColumns[responses.workflowType] || workflowColumns['Generic Task Management'];
  }

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

    const responses = result.responses;
    const columns = this.determineColumns(responses);

    // Parse work item types
    const workItemTypes = responses.workItemTypes
      .split(',')
      .map((type: string) => type.trim())
      .filter((type: string) => type.length > 0);

    // Parse initial tags
    const initialTags = responses.initialTags !== 'N/A' && responses.initialTags
      ? responses.initialTags.split(',').map((tag: string) => tag.trim()).filter((tag: string) => tag.length > 0)
      : [];

    // Determine WIP limits
    const wipLimitMap: Record<string, number> = {
      '1 item per person': 1,
      '2 items per person': 2,
      '3 items per person': 3,
      '5 items per person': 5,
      'No limit': 0
    };
    const wipLimitPerPerson = responses.useWipLimits ? (wipLimitMap[responses.wipLimitValue] || 2) : 0;

    return {
      name: responses.boardName,
      columns,
      workflowType: responses.workflowType,
      teamSize: responses.teamSize,
      workItemTypes,
      priorityLevels: responses.priorityLevels,
      useWipLimits: responses.useWipLimits,
      wipLimitPerPerson,
      useTags: responses.useTags,
      initialTags,
      automationPreference: responses.automationPreference,
      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);
  }
}