// UI functions for Structure Building System
// Handles structure selection interfaces and user feedback

import { ActionFormData, MessageFormData, ModalFormData } from '@minecraft/server-ui';
import { buildStructureAtLocation } from './events.js';
import { structureTemplates } from './config.js';
import { debug, calculateStructureDimensions } from './utils.js';

/**
 * Show structure selection UI when multiple templates are available
 * @param {Player} player - The player to show UI to
 * @param {Object} structureItem - The structure item configuration
 * @param {Vector3} location - The build location
 * @param {string} face - The block face
 */
export function showStructureSelectionUI(player, structureItem, location, face) {
    const form = new ActionFormData()
      .title(`Select ${structureItem.display_name} Type`)
      .body('Choose which variant of this structure to build:');
    
    // Add button for each available template
    const templateKeys = [];
    for (const templateKey of structureItem.structure_templates) {
      const template = structureTemplates[templateKey];
      if (template) {
        form.button(template.display_name, 'textures/blocks/structure_block');
        templateKeys.push(templateKey);
      }
    }
    
    // Add cancel button
    form.button('Cancel', 'textures/ui/cancel');
    
    form.show(player).then((response) => {
      if (response.canceled || response.selection === undefined) {
        player.onScreenDisplay.setActionBar('§7Structure placement canceled.');
        return;
      }
      
      // Check if cancel was selected (last button)
      if (response.selection === templateKeys.length) {
        player.onScreenDisplay.setActionBar('§7Structure placement canceled.');
        return;
      }
      
      const selectedTemplateKey = templateKeys[response.selection];
      debug('info', `Player selected template: ${selectedTemplateKey}`);
      
      // Show dimension selection UI for the selected template
      showDimensionSelectionUI(player, structureItem, selectedTemplateKey, location, face);
    })
}

/**
 * Show dimension selection UI for structures with repeatable parts
 * @param {Player} player - The player to show UI to
 * @param {Object} structureItem - The structure item configuration
 * @param {string} templateKey - The selected template key
 * @param {Vector3} location - The build location
 * @param {string} face - The block face
 */
export function showDimensionSelectionUI(player, structureItem, templateKey, location, face) {
  const template = structureTemplates[templateKey];
  if (!template) {
    debug('error', `Template '${templateKey}' not found`);
    return;
  }
  
  // Calculate structure dimensions
  const dimensions = calculateStructureDimensions(template);
  
  // Check if structure has any repeatable parts
  const hasRepeatableParts = dimensions.height.repeatable.length > 0 || 
                            dimensions.width.repeatable.length > 0 || 
                            dimensions.depth.repeatable.length > 0;
  
  if (!hasRepeatableParts) {
    // No repeatable parts, build directly
    buildStructureAtLocation(player, structureItem, templateKey, location, face);
    return;
  }
  
  const form = new ModalFormData()
    .title(`Configure ${template.display_name}`);

  const sliderData = [];
  
  // Add height slider if applicable
  if (dimensions.height.repeatable.length > 0) {
    const minHeight = dimensions.height.min;
    const maxHeight = dimensions.height.max;
    
    form.slider('Height', minHeight, maxHeight, 1, minHeight);
    sliderData.push({ type: 'height', min: minHeight, max: maxHeight });
  }
  
  // Add width slider if applicable
  if (dimensions.width.repeatable.length > 0) {
    const minWidth = dimensions.width.min;
    const maxWidth = dimensions.width.max;
    
    if (template.display_name.includes('Double')) form.slider('Width', minWidth, maxWidth, 2, minWidth);
    else form.slider('Width', minWidth, maxWidth, 1, minWidth);
    
    sliderData.push({ type: 'width', min: minWidth, max: maxWidth });
  }
  
  // Add depth slider if applicable
  if (dimensions.depth.repeatable.length > 0) {
    const minDepth = dimensions.depth.min;
    const maxDepth = dimensions.depth.max;
    
    form.slider('Depth', minDepth, maxDepth, 1, minDepth);
    sliderData.push({ type: 'depth', min: minDepth, max: maxDepth });
  }
  
  form.show(player).then((response) => {
    if (response.canceled) {
      player.onScreenDisplay.setActionBar('§7Structure placement canceled.');
      return;
    }
    
    // Build selected dimensions object
    const selectedDimensions = {};
    let sliderIndex = 0;
    
    for (const slider of sliderData) {
      const value = response.formValues[sliderIndex];
      selectedDimensions[slider.type] = value;
      debug('info', `Selected ${slider.type}: ${value}`);
      sliderIndex++;
    }
    
    // Build structure with selected dimensions
    buildStructureAtLocation(player, structureItem, templateKey, location, face, selectedDimensions);
  }).catch((error) => {
    debug('error', `Dimension selection UI error: ${error.message}`);
    player.onScreenDisplay.setActionBar('§cError showing dimension selection. Building with default size.');
    buildStructureAtLocation(player, structureItem, templateKey, location, face);
  });
}

/**
 * Show structure information UI
 * @param {Player} player - The player to show UI to
 * @param {Object} structureItem - The structure item configuration
 */
export function showStructureInfoUI(player, structureItem) {
    let bodyText = `§l${structureItem.display_name}§r\n\n`;
    bodyText += `§7Item ID: §f${structureItem.item}\n`;
    bodyText += `§7Available Templates: §f${structureItem.structure_templates.length}\n\n`;

    // Add template information
    bodyText += '§lAvailable Variants:§r\n';
    for (const templateKey of structureItem.structure_templates) {
        const template = structureTemplates[templateKey];
        if (template) {
        bodyText += `§8• §f${template.display_name}\n`;
        bodyText += `  §7Parts: ${template.parts.length}\n`;
        }
    }

    const form = new MessageFormData()
        .title('Structure Information')
        .body(bodyText)
        .button1('Close')
        .button2('Build');

    form.show(player).then((response) => {
        if (response.selection === 1) {
        player.onScreenDisplay.setActionBar('§aUse the item on a block to build this structure!');
        }
    })
}

/**
 * Show structure building progress UI
 * @param {Player} player - The player to show progress to
 * @param {string} structureName - Name of the structure being built
 * @param {number} progress - Progress percentage (0-100)
 */
export function showBuildProgressUI(player, structureName, progress) {
    const progressBar = createProgressBar(progress);
    const message = `§aBuildng ${structureName}...\n${progressBar} §f${progress}%`;
    
    // Use action bar for non-intrusive progress display
    player.onScreenDisplay.setActionBar(message);
}

/**
 * Create a visual progress bar
 * @param {number} progress - Progress percentage (0-100)
 * @returns {string} Progress bar string
 */
function createProgressBar(progress) {
  const barLength = 20;
  const filledLength = Math.floor((progress / 100) * barLength);
  const emptyLength = barLength - filledLength;
  
  const filledBar = '§a█'.repeat(filledLength);
  const emptyBar = '§7█'.repeat(emptyLength);
  
  return `[${filledBar}${emptyBar}]`;
}

/**
 * Show structure building error UI
 * @param {Player} player - The player to show error to
 * @param {string} errorMessage - The error message
 * @param {Object} structureItem - The structure item that failed
 */
export function showBuildErrorUI(player, errorMessage, structureItem) {
    const form = new MessageFormData()
      .title('§cStructure Build Failed')
      .body(`Failed to build ${structureItem.display_name}:\n\n§c${errorMessage}\n\n§7Please check the placement location and try again.`)
      .button1('OK')
      .button2('Show Info');
    
    form.show(player).then((response) => {
      if (response.selection === 1) {
        showStructureInfoUI(player, structureItem);
      }
    })
}

/**
 * Show structure building success UI
 * @param {Player} player - The player to show success message to
 * @param {Object} structureItem - The structure item that was built
 * @param {string} templateKey - The template that was used
 * @param {number} partsPlaced - Number of parts placed
 */
export function showBuildSuccessUI(player, structureItem, templateKey, partsPlaced) {
    const template = structureTemplates[templateKey];
    const templateName = template ? template.display_name : templateKey;
    
    const message = `§aSuccessfully built ${structureItem.display_name}!\n` +
                   `§7Type: §f${templateName}\n` +
                   `§7Parts placed: §f${partsPlaced}`;
    
    // Show both action bar and chat message
    player.onScreenDisplay.setActionBar('§aStructure built successfully!');
    player.onScreenDisplay.setActionBar(message);
}

/**
 * Show structure management UI for administrators
 * @param {Player} player - The player (must have admin permissions)
 */
export function showStructureManagementUI(player) {
    // Check if player has admin permissions
    if (!player.isOp() && !player.hasTag('structure_admin')) {
      player.onScreenDisplay.setActionBar('§cYou do not have permission to access structure management.');
      return;
    }
    
    const form = new ActionFormData()
      .title('Structure Management')
      .body('Manage structure building system:')
      .button('List All Structures', 'textures/ui/book_edit_default')
      .button('Validate Templates', 'textures/ui/check')
      .button('System Status', 'textures/ui/info_glyph_color')
      .button('Player Permissions', 'textures/ui/permissions_op_crown')
      .button('Close', 'textures/ui/cancel');
    
    form.show(player).then((response) => {
      if (response.canceled || response.selection === undefined) {
        return;
      }
      
      switch (response.selection) {
        case 0:
          showStructureListUI(player);
          break;
        case 1:
          validateAllTemplates(player);
          break;
        case 2:
          showSystemStatusUI(player);
          break;
        case 3:
          showPermissionManagementUI(player);
          break;
        case 4:
          // Close - do nothing
          break;
      }
    })
}

/**
 * Show list of all available structures
 * @param {Player} player - The player to show list to
 */
function showStructureListUI(player) {
    const { structureItems } = require('./config.js');
    
    let bodyText = '§lAvailable Structures:§r\n\n';
    
    for (const [key, item] of Object.entries(structureItems)) {
      bodyText += `§8• §f${item.display_name}\n`;
      bodyText += `  §7ID: §f${item.item}\n`;
      bodyText += `  §7Templates: §f${item.structure_templates.length}\n\n`;
    }
    
    const form = new MessageFormData()
      .title('Structure List')
      .body(bodyText)
      .button1('Close')
      .button2('Back to Management');
    
    form.show(player).then((response) => {
      if (response.selection === 1) {
        showStructureManagementUI(player);
      }
    })
}

/**
 * Validate all templates and show results
 * @param {Player} player - The player to show results to
 */
function validateAllTemplates(player) {
    const { validateTemplate } = require('./validation.js');
    
    let results = '§lTemplate Validation Results:§r\n\n';
    let validCount = 0;
    let totalCount = 0;
    
    for (const [templateKey, template] of Object.entries(structureTemplates)) {
      totalCount++;
      const validation = validateTemplate(template);
      
      if (validation.valid) {
        results += `§a✓ §f${template.display_name || templateKey}\n`;
        validCount++;
      } else {
        results += `§c✗ §f${template.display_name || templateKey}\n`;
        results += `  §7Error: ${validation.reason}\n`;
      }
    }
    
    results += `\n§7Valid: §a${validCount}§7/§f${totalCount}`;
    
    const form = new MessageFormData()
      .title('Template Validation')
      .body(results)
      .button1('Close')
      .button2('Back to Management');
    
    form.show(player).then((response) => {
      if (response.selection === 1) {
        showStructureManagementUI(player);
      }
    })
}

/**
 * Show system status information
 * @param {Player} player - The player to show status to
 */
function showSystemStatusUI(player) {
    const { structureItems } = require('./config.js');
    
    const itemCount = Object.keys(structureItems).length;
    const templateCount = Object.keys(structureTemplates).length;
    
    const statusText = `§lStructure System Status:§r\n\n` +
                      `§7Registered Items: §f${itemCount}\n` +
                      `§7Available Templates: §f${templateCount}\n` +
                      `§7System Status: §aOnline\n` +
                      `§7Last Initialized: §fWorld Start\n\n` +
                      `§7Memory Usage: §fNormal\n` +
                      `§7Performance: §aGood`;
    
    const form = new MessageFormData()
      .title('System Status')
      .body(statusText)
      .button1('Close')
      .button2('Back to Management');
    
    form.show(player).then((response) => {
      if (response.selection === 1) {
        showStructureManagementUI(player);
      }
    })
}

/**
 * Show permission management UI
 * @param {Player} player - The admin player
 */
function showPermissionManagementUI(player) {
    const form = new ActionFormData()
      .title('Permission Management')
      .body('Manage structure building permissions:')
      .button('Grant Builder Permission', 'textures/ui/check')
      .button('Revoke Builder Permission', 'textures/ui/cancel')
      .button('List Builder Players', 'textures/ui/book_edit_default')
      .button('Back to Management', 'textures/ui/arrow_left');
    
    form.show(player).then((response) => {
      if (response.canceled || response.selection === undefined) {
        return;
      }
      
      switch (response.selection) {
        case 0:
          // Grant permission - would need player selection UI
          player.sendMessage('§7Use: /tag <player> add structure_builder');
          break;
        case 1:
          // Revoke permission - would need player selection UI
          player.sendMessage('§7Use: /tag <player> remove structure_builder');
          break;
        case 2:
          // List builders - would need to query all players
          player.sendMessage('§7Builder players have the "structure_builder" tag.');
          break;
        case 3:
          showStructureManagementUI(player);
          break;
      }
    })
}