import * as XLSX from 'xlsx';

// Generate markdown overview
export const generateMarkdownOverview = (config, printedParts, hardwareParts, filamentTotals, totalTime, total) => {
  const md = [];
  
  md.push('# OSSM Build Configuration');
  md.push(`\n**Generated:** ${new Date().toLocaleString()}\n`);
  
  // Motor
  if (config.motor) {
    md.push(`## Motor: ${config.motor.name}`);
    md.push(`- **Price:** ${config.motor.price}`);
    md.push(`- **Speed:** ${config.motor.speed}`);
    md.push(`- **Wattage:** ${config.motor.wattage}`);
    md.push('');
  }
  
  // Power Supply
  if (config.powerSupply) {
    md.push(`## Power Supply: ${config.powerSupply.name}`);
    md.push(`- **Price:** ${config.powerSupply.price}`);
    md.push('');
  }
  
  // Colors
  md.push(`## Colors`);
  md.push(`- **Primary:** ${config.primaryColor || 'Not selected'}`);
  md.push(`- **Accent:** ${config.accentColor || 'Not selected'}`);
  md.push('');
  
  // Mount
  if (config.mount) {
    md.push(`## Mount: ${config.mount.name}`);
    md.push('');
  }
  
  // Cover
  if (config.cover) {
    md.push(`## Cover: ${config.cover.name}`);
    md.push('');
  }
  
  // PCB Mount
  if (config.pcbMount) {
    md.push(`## PCB Mount: ${config.pcbMount.name}`);
    md.push('');
  }
  
  // Stand Options
  if (config.standHinge || config.standFeet || config.standCrossbarSupports?.length > 0) {
    md.push(`## Stand Options`);
    if (config.standHinge) md.push(`- **Hinges:** ${config.standHinge.name}`);
    if (config.standFeet) md.push(`- **Feet:** ${config.standFeet.name}`);
    if (config.standCrossbarSupports?.length > 0) {
      md.push(`- **Crossbar Supports:** ${config.standCrossbarSupports.map(s => s.name).join(', ')}`);
    }
    md.push('');
  }
  
  // Remote
  if (config.remote || config.remoteKnob) {
    md.push(`## Remote`);
    if (config.remote) md.push(`- **Type:** ${config.remote.name}`);
    if (config.remoteKnob) md.push(`- **Knob:** ${config.remoteKnob.name}`);
    md.push('');
  }
  
  // Filament Summary
  if (filamentTotals.total > 0) {
    md.push(`## Filament Summary`);
    md.push(`- **Total:** ~${filamentTotals.total.toFixed(2)}g`);
    if (filamentTotals.primary > 0) md.push(`  - Primary: ~${filamentTotals.primary.toFixed(2)}g`);
    if (filamentTotals.secondary > 0) md.push(`  - Accent: ~${filamentTotals.secondary.toFixed(2)}g`);
    md.push(`- **Estimated Print Time:** ${totalTime}`);
    md.push('');
  }
  
  // Print Parts Summary
  if (printedParts.length > 0) {
    md.push(`## Printed Parts Summary`);
    md.push(`- **Total Parts:** ${printedParts.length}`);
    
    // Group by category
    const partsByCategory = {};
    printedParts.forEach(part => {
      const category = part.category || 'Other';
      if (!partsByCategory[category]) {
        partsByCategory[category] = [];
      }
      partsByCategory[category].push(part);
    });
    
    Object.entries(partsByCategory).forEach(([category, parts]) => {
      md.push(`### ${category} (${parts.length} parts)`);
      parts.forEach(part => {
        md.push(`- ${part.name}${part.filamentEstimate ? ` (~${part.filamentEstimate}g)` : ''}`);
      });
    });
    md.push('');
  }
  
  // Hardware Summary
  if (hardwareParts.length > 0) {
    md.push(`## Hardware Summary`);
    md.push(`- **Total Items:** ${hardwareParts.length}`);
    md.push('');
  }
  
  // Cost Summary
  if (total > 0) {
    md.push(`## Estimated Cost`);
    md.push(`- **Total:** $${total.toFixed(2)}`);
    md.push('');
  }
  
  return md.join('\n');
};

// Generate Excel BOM with purchase links
export const generateExcelBOM = (hardwareParts, printedParts, config) => {
  const rows = [];
  
  // Header
  rows.push(['Item', 'Name', 'Quantity', 'Price', 'Link', 'Category', 'Type']);
  
  // Add motor
  if (config.motor) {
    const motorLinks = config.motor.links || [];
    const firstLink = motorLinks.length > 0 ? motorLinks[0].link : '';
    rows.push([
      'Motor',
      config.motor.name,
      1,
      config.motor.price,
      firstLink,
      'Motor',
      'Hardware'
    ]);
  }
  
  // Add power supply
  if (config.powerSupply) {
    const psuLinks = config.powerSupply.links || [];
    const firstLink = psuLinks.length > 0 ? psuLinks[0].link : '';
    rows.push([
      'Power Supply',
      config.powerSupply.name,
      1,
      config.powerSupply.price,
      firstLink,
      'Power Supply',
      'Hardware'
    ]);
  }
  
  // Add hardware parts
  hardwareParts.forEach(hw => {
    const links = hw.links || [];
    const firstLink = links.length > 0 ? links[0].link : (hw.url || '');
    rows.push([
      hw.id || '',
      hw.name || '',
      hw.quantity || 1,
      hw.price ? `$${parseFloat(hw.price).toFixed(2)}` : '',
      firstLink,
      hw.category || 'Hardware',
      'Hardware'
    ]);
  });
  
  // Add printed parts (for reference, not purchase)
  printedParts.forEach(part => {
    rows.push([
      part.id || '',
      part.name || '',
      1,
      'N/A',
      part.url || '',
      part.category || 'Printed',
      'Printed Part'
    ]);
  });
  
  // Create workbook and worksheet
  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.aoa_to_sheet(rows);
  
  // Set column widths
  ws['!cols'] = [
    { wch: 30 }, // Item
    { wch: 40 }, // Name
    { wch: 10 }, // Quantity
    { wch: 12 }, // Price
    { wch: 50 }, // Link
    { wch: 20 }, // Category
    { wch: 15 }  // Type
  ];
  
  XLSX.utils.book_append_sheet(wb, ws, 'BOM');
  
  return wb;
};

// Generate Excel Print List with completion tracker
export const generateExcelPrintList = (printedParts, filamentTotals) => {
  const rows = [];
  
  // Header
  rows.push(['Part Name', 'Category', 'Color', 'Quantity', 'Filament (g)', 'Print Time', 'Status', 'Completed']);
  
  // Group parts by category and color
  const partsByCategoryColor = {};
  printedParts.forEach(part => {
    const category = part.category || 'Other';
    const color = part.colour === 'primary' ? 'Primary' : part.colour === 'secondary' ? 'Accent' : 'Other';
    const key = `${category}_${color}`;
    
    if (!partsByCategoryColor[key]) {
      partsByCategoryColor[key] = [];
    }
    partsByCategoryColor[key].push(part);
  });
  
  // Sort by category, then color
  const sortedKeys = Object.keys(partsByCategoryColor).sort();
  
  sortedKeys.forEach(key => {
    const parts = partsByCategoryColor[key];
    const [category, color] = key.split('_');
    
    parts.forEach(part => {
      const filament = typeof part.filamentEstimate === 'number' 
        ? part.filamentEstimate 
        : parseFloat(part.filamentEstimate?.replace('~', '').replace('g', '')) || 0;
      
      rows.push([
        part.name || part.id || '',
        category,
        color,
        1,
        filament > 0 ? filament.toFixed(2) : '',
        part.timeEstimate || '',
        '', // Status column (user fills in)
        ''  // Completed column (user checks)
      ]);
    });
  });
  
  // Add summary row
  rows.push([]);
  rows.push(['TOTAL', '', '', printedParts.length, filamentTotals.total.toFixed(2), '', '', '']);
  
  // Create workbook and worksheet
  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.aoa_to_sheet(rows);
  
  // Set column widths
  ws['!cols'] = [
    { wch: 40 }, // Part Name
    { wch: 20 }, // Category
    { wch: 12 }, // Color
    { wch: 10 }, // Quantity
    { wch: 15 }, // Filament
    { wch: 15 }, // Print Time
    { wch: 15 }, // Status
    { wch: 12 }  // Completed
  ];
  
  XLSX.utils.book_append_sheet(wb, ws, 'Print List');
  
  // Create a summary sheet with progress calculation
  // Note: Excel formulas need to reference cells properly
  const summaryRows = [
    ['Print Progress Summary'],
    [],
    ['Total Parts', printedParts.length],
    ['Completed Parts', { f: `COUNTIF('Print List'.H:H,"✓")` }],
    ['Progress %', { f: `IF(B3>0, (B4/B3)*100, 0)` }],
    [],
    ['Filament Summary'],
    ['Total Filament (g)', filamentTotals.total.toFixed(2)],
    ['Primary Color (g)', filamentTotals.primary.toFixed(2)],
    ['Accent Color (g)', (filamentTotals.secondary || 0).toFixed(2)]
  ];
  
  const summaryWs = XLSX.utils.aoa_to_sheet(summaryRows);
  summaryWs['!cols'] = [
    { wch: 25 },
    { wch: 15 }
  ];
  XLSX.utils.book_append_sheet(wb, summaryWs, 'Summary');
  
  return wb;
};
