import { html, css, cssManager } from '@design.estate/dees-element';
import '@design.estate/dees-wcctools/demotools';
import '../dees-panel/dees-panel.js';
import type { IStatsTile, ICpuCore, IPartitionData, IDiskData } from '../dees-statsgrid/dees-statsgrid.js';

// Helper function to generate random CPU core data
const generateCpuCores = (count: number): ICpuCore[] => {
  return Array.from({ length: count }, (_, i) => ({
    id: i,
    usage: Math.round(Math.random() * 100),
    label: `${i}`,
  }));
};

export const demoFunc = () => {
  return html`
  <dees-demowrapper>
    <style>
      ${css`
        .demo-container {
          display: flex;
          flex-direction: column;
          gap: 24px;
          padding: 24px;
          max-width: 1400px;
          margin: 0 auto;
        }
        
        dees-panel {
          margin-bottom: 24px;
        }
        
        dees-panel:last-child {
          margin-bottom: 0;
        }
        
        .tile-config {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
          gap: 16px;
          margin-top: 16px;
        }
        
        .config-section {
          padding: 16px;
          background: ${cssManager.bdTheme('hsl(210 40% 96.1%)', 'hsl(215 20.2% 16.8%)')};
          border-radius: 6px;
        }
        
        .config-title {
          font-size: 14px;
          font-weight: 600;
          margin-bottom: 8px;
          color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};
        }
        
        .config-description {
          font-size: 13px;
          color: ${cssManager.bdTheme('hsl(215.4 16.3% 56.9%)', 'hsl(215 20.2% 55.1%)')};
        }
        
        .code-block {
          background: ${cssManager.bdTheme('hsl(210 40% 96.1%)', 'hsl(215 20.2% 11.8%)')};
          border: 1px solid ${cssManager.bdTheme('hsl(214.3 31.8% 91.4%)', 'hsl(215 20.2% 16.8%)')};
          border-radius: 6px;
          padding: 16px;
          font-family: monospace;
          font-size: 13px;
          overflow-x: auto;
          white-space: pre;
        }
      `}
    </style>
    
    <div class="demo-container">
      <dees-panel .title=${'1. Comprehensive Dashboard'} .subtitle=${'Full-featured stats grid with various tile types, actions, and Lucide icons'}>
        <dees-statsgrid
          .tiles=${[
            {
              id: 'revenue',
              title: 'Total Revenue',
              value: 125420,
              unit: '$',
              type: 'number',
              icon: 'lucide:dollar-sign',
              description: '+12.5% from last month',
              actions: [
                {
                  name: 'View Details',
                  iconName: 'lucide:trending-up',
                  action: async () => {
                    const output = document.querySelector('#action-output');
                    if (output) {
                      output.textContent = 'Viewing revenue details: $125,420 (+12.5%)';
                    }
                  }
                },
                {
                  name: 'Export Data',
                  iconName: 'lucide:download',
                  action: async () => {
                    const output = document.querySelector('#action-output');
                    if (output) {
                      output.textContent = 'Exporting revenue data to CSV...';
                    }
                  }
                }
              ]
            },
            {
              id: 'users',
              title: 'Active Users',
              value: 3847,
              type: 'number',
              icon: 'lucide:users',
              description: '324 new this week',
              actions: [
                {
                  name: 'View User List',
                  iconName: 'lucide:list',
                  action: async () => {
                    const output = document.querySelector('#action-output');
                    if (output) {
                      output.textContent = 'Opening user list...';
                    }
                  }
                }
              ]
            },
            {
              id: 'cpu',
              title: 'CPU Usage',
              value: 73,
              unit: '%',
              type: 'gauge',
              icon: 'lucide:cpu',
              gaugeOptions: {
                min: 0,
                max: 100,
                thresholds: [
                  { value: 0, color: 'hsl(142.1 76.2% 36.3%)' },
                  { value: 60, color: 'hsl(45.4 93.4% 47.5%)' },
                  { value: 80, color: 'hsl(0 84.2% 60.2%)' }
                ]
              }
            },
            {
              id: 'storage',
              title: 'Storage Used',
              value: 65,
              type: 'percentage',
              icon: 'lucide:hard-drive',
              description: '650 GB of 1 TB',
            },
            {
              id: 'latency',
              title: 'Response Time',
              value: 142,
              unit: 'ms',
              type: 'trend',
              icon: 'lucide:activity',
              trendData: [150, 145, 148, 142, 138, 140, 135, 145, 142],
              description: 'P95'
            },
            {
              id: 'uptime',
              title: 'System Uptime',
              value: '99.95%',
              type: 'text',
              icon: 'lucide:check-circle',
              color: 'hsl(142.1 76.2% 36.3%)',
              description: 'Last 30 days'
            }
          ]}
          .gridActions=${[
            {
              name: 'Refresh',
              iconName: 'lucide:refresh-cw',
              action: async () => {
                const grid = document.querySelector('dees-statsgrid');
                if (grid) {
                  grid.style.opacity = '0.5';
                  setTimeout(() => {
                    grid.style.opacity = '1';
                  }, 300);
                }
              }
            },
            {
              name: 'Export',
              iconName: 'lucide:share',
              action: async () => {
                const output = document.querySelector('#action-output');
                if (output) {
                  output.textContent = 'Exporting dashboard report...';
                }
              }
            },
            {
              name: 'Settings',
              iconName: 'lucide:settings',
              action: async () => {
                const output = document.querySelector('#action-output');
                if (output) {
                  output.textContent = 'Opening dashboard settings...';
                }
              }
            }
          ]}
          .minTileWidth=${250}
          .gap=${16}
        ></dees-statsgrid>
        
        <div id="action-output" style="margin-top: 16px; padding: 12px; background: ${cssManager.bdTheme('hsl(210 40% 96.1%)', 'hsl(215 20.2% 16.8%)')}; border-radius: 6px; font-size: 14px; font-family: monospace; color: ${cssManager.bdTheme('hsl(215.3 25% 8.8%)', 'hsl(210 40% 98%)')};">
          <em>Click on tile actions or grid actions to see the result...</em>
        </div>
      </dees-panel>
      
      <dees-panel .title=${'2. Tile Types'} .subtitle=${'Different visualization types available in the stats grid'}>
        <dees-statsgrid
          .tiles=${[
            {
              id: 'number-example',
              title: 'Number Tile',
              value: 42195,
              unit: '$',
              type: 'number',
              icon: 'lucide:hash',
              description: 'Simple numeric display'
            },
            {
              id: 'gauge-example',
              title: 'Gauge Tile',
              value: 68,
              unit: '%',
              type: 'gauge',
              icon: 'lucide:gauge',
              gaugeOptions: {
                min: 0,
                max: 100,
                thresholds: [
                  { value: 0, color: 'hsl(142.1 76.2% 36.3%)' },
                  { value: 50, color: 'hsl(45.4 93.4% 47.5%)' },
                  { value: 80, color: 'hsl(0 84.2% 60.2%)' }
                ]
              }
            },
            {
              id: 'percentage-example',
              title: 'Percentage Tile',
              value: 78,
              type: 'percentage',
              icon: 'lucide:percent',
              description: 'Progress bar visualization'
            },
            {
              id: 'trend-example',
              title: 'Trend Tile',
              value: 892,
              unit: 'ops/s',
              type: 'trend',
              icon: 'lucide:trending-up',
              trendData: [720, 750, 780, 795, 810, 835, 850, 865, 880, 892],
              description: 'avg'
            },
            {
              id: 'text-example',
              title: 'Text Tile',
              value: 'Operational',
              type: 'text',
              icon: 'lucide:info',
              color: 'hsl(142.1 76.2% 36.3%)',
              description: 'Status display'
            }
          ]}
          .minTileWidth=${280}
          .gap=${16}
        ></dees-statsgrid>
        
        <div class="tile-config">
          <div class="config-section">
            <div class="config-title">Configuration Options</div>
            <div class="config-description">
              Each tile type supports different properties:
              <ul style="margin: 8px 0; padding-left: 20px;">
                <li><strong>Number:</strong> value, unit, color, description</li>
                <li><strong>Gauge:</strong> value, unit, gaugeOptions (min, max, thresholds)</li>
                <li><strong>Percentage:</strong> value (0-100), color, description</li>
                <li><strong>Trend:</strong> value, unit, trendData array, description</li>
                <li><strong>Text:</strong> value (string), color, description</li>
              </ul>
            </div>
          </div>
        </div>
      </dees-panel>
      
      <dees-panel .title=${'3. Grid Configurations'} .subtitle=${'Different layout options and responsive behavior'}>
        <h4 style="margin: 0 0 16px 0; font-size: 16px; font-weight: 600;">Compact Layout (180px tiles)</h4>
        <dees-statsgrid
          .tiles=${[
            { id: '1', title: 'Orders', value: 156, type: 'number', icon: 'lucide:shopping-cart' },
            { id: '2', title: 'Revenue', value: 8420, unit: '$', type: 'number', icon: 'lucide:dollar-sign' },
            { id: '3', title: 'Users', value: 423, type: 'number', icon: 'lucide:users' },
            { id: '4', title: 'Growth', value: 12.5, unit: '%', type: 'number', icon: 'lucide:trending-up', color: 'hsl(142.1 76.2% 36.3%)' }
          ]}
          .minTileWidth=${180}
          .gap=${12}
        ></dees-statsgrid>
        
        <h4 style="margin: 24px 0 16px 0; font-size: 16px; font-weight: 600;">Spacious Layout (320px tiles)</h4>
        <dees-statsgrid
          .tiles=${[
            {
              id: 'spacious1',
              title: 'Monthly Revenue',
              value: 184500,
              unit: '$',
              type: 'number',
              icon: 'lucide:credit-card',
              description: 'Total revenue this month'
            },
            {
              id: 'spacious2',
              title: 'Customer Satisfaction',
              value: 94,
              type: 'percentage',
              icon: 'lucide:smile',
              description: 'Based on 1,234 reviews'
            },
            {
              id: 'spacious3',
              title: 'Server Response',
              value: 98,
              unit: 'ms',
              type: 'trend',
              icon: 'lucide:server',
              trendData: [105, 102, 100, 99, 98, 98, 97, 98],
              description: 'avg response time'
            }
          ]}
          .minTileWidth=${320}
          .gap=${20}
        ></dees-statsgrid>
      </dees-panel>
      
      <dees-panel .title=${'4. CPU Cores Visualization'} .subtitle=${'Vertical bar visualization for multi-core CPU usage with column spanning'}>
        <dees-statsgrid
          id="cpu-cores-grid"
          .tiles=${[
            {
              id: 'cpu-cores-8',
              title: 'CPU Cores (8-core)',
              value: 0,
              type: 'cpuCores',
              icon: 'lucide:cpu',
              columnSpan: 2,
              coresData: generateCpuCores(8),
              description: 'Intel i7 - 8 cores'
            },
            {
              id: 'memory',
              title: 'Memory Usage',
              value: 68,
              type: 'percentage',
              icon: 'lucide:database',
              description: '13.6 GB of 20 GB'
            },
            {
              id: 'cpu-cores-16',
              title: 'CPU Cores (16-core)',
              value: 0,
              type: 'cpuCores',
              icon: 'lucide:cpu',
              columnSpan: 2,
              coresData: generateCpuCores(16),
              description: 'AMD Ryzen 9 - 16 cores'
            },
            {
              id: 'network',
              title: 'Network I/O',
              value: 245,
              unit: 'MB/s',
              type: 'trend',
              icon: 'lucide:network',
              trendData: [200, 220, 235, 240, 238, 245],
              description: 'throughput'
            },
            {
              id: 'cpu-cores-32',
              title: 'Server CPU (32-core)',
              value: 0,
              type: 'cpuCores',
              icon: 'lucide:server',
              columnSpan: 3,
              coresData: generateCpuCores(32),
              description: 'AMD EPYC - 32 cores'
            },
            {
              id: 'disk',
              title: 'Disk Usage',
              value: 42,
              type: 'percentage',
              icon: 'lucide:hard-drive',
              description: '420 GB of 1 TB'
            }
          ]}
          .gridActions=${[
            {
              name: 'Randomize',
              iconName: 'lucide:shuffle',
              action: async () => {
                const grid = document.querySelector('#cpu-cores-grid') as any;
                if (!grid) return;
                const tiles = grid.tiles.map((tile: any) => {
                  if (tile.type === 'cpuCores' && tile.coresData) {
                    return {
                      ...tile,
                      coresData: tile.coresData.map((core: any) => ({
                        ...core,
                        usage: Math.round(Math.random() * 100)
                      }))
                    };
                  }
                  return tile;
                });
                grid.tiles = tiles;
              }
            }
          ]}
          .minTileWidth=${250}
          .gap=${16}
        ></dees-statsgrid>
      </dees-panel>

      <dees-panel .title=${'5. Interactive Features'} .subtitle=${'Tiles with actions and real-time updates'}>
        <dees-statsgrid
          id="interactive-grid"
          .tiles=${[
            {
              id: 'live-cpu',
              title: 'Live CPU',
              value: 45,
              unit: '%',
              type: 'gauge',
              icon: 'lucide:cpu',
              gaugeOptions: {
                min: 0,
                max: 100,
                thresholds: [
                  { value: 0, color: 'hsl(142.1 76.2% 36.3%)' },
                  { value: 60, color: 'hsl(45.4 93.4% 47.5%)' },
                  { value: 80, color: 'hsl(0 84.2% 60.2%)' }
                ]
              }
            },
            {
              id: 'live-requests',
              title: 'Requests/sec',
              value: 892,
              type: 'trend',
              icon: 'lucide:activity',
              trendData: [850, 860, 870, 880, 885, 890, 892]
            },
            {
              id: 'live-memory',
              title: 'Memory Usage',
              value: 62,
              type: 'percentage',
              icon: 'lucide:database'
            },
            {
              id: 'counter',
              title: 'Event Counter',
              value: 0,
              type: 'number',
              icon: 'lucide:zap',
              actions: [
                {
                  name: 'Increment',
                  iconName: 'lucide:plus',
                  action: async () => {
                    const grid = document.querySelector('#interactive-grid') as any;
                    if (!grid) return;
                    const tile = grid.tiles.find((t: any) => t.id === 'counter');
                    tile.value = typeof tile.value === 'number' ? tile.value + 1 : 1;
                    grid.tiles = [...grid.tiles];
                  }
                },
                {
                  name: 'Reset',
                  iconName: 'lucide:rotate-ccw',
                  action: async () => {
                    const grid = document.querySelector('#interactive-grid') as any;
                    if (!grid) return;
                    const tile = grid.tiles.find((t: any) => t.id === 'counter');
                    tile.value = 0;
                    grid.tiles = [...grid.tiles];
                  }
                }
              ]
            }
          ]}
          .gridActions=${[
            {
              name: 'Start Live Updates',
              iconName: 'lucide:play',
              action: async function() {
                // Toggle live updates
                if (!(window as any).liveUpdateInterval) {
                  (window as any).liveUpdateInterval = setInterval(() => {
                    const grid = document.querySelector('#interactive-grid') as any;
                    if (grid) {
                      const tiles = [...grid.tiles];
                      
                      // Update CPU gauge
                      const cpuTile = tiles.find(t => t.id === 'live-cpu');
                      cpuTile.value = Math.max(0, Math.min(100, cpuTile.value + (Math.random() * 20 - 10)));
                      
                      // Update requests trend
                      const requestsTile = tiles.find(t => t.id === 'live-requests');
                      const newValue = requestsTile.value + Math.round(Math.random() * 50 - 25);
                      requestsTile.value = Math.max(800, newValue);
                      requestsTile.trendData = [...requestsTile.trendData.slice(1), requestsTile.value];
                      
                      // Update memory percentage
                      const memoryTile = tiles.find(t => t.id === 'live-memory');
                      memoryTile.value = Math.max(0, Math.min(100, memoryTile.value + (Math.random() * 10 - 5)));
                      
                      grid.tiles = tiles;
                    }
                  }, 1000);
                  
                  this.name = 'Stop Live Updates';
                  this.iconName = 'lucide:pause';
                } else {
                  clearInterval((window as any).liveUpdateInterval);
                  (window as any).liveUpdateInterval = null;
                  this.name = 'Start Live Updates';
                  this.iconName = 'lucide:play';
                }
              }
            }
          ]}
          .minTileWidth=${250}
          .gap=${16}
        ></dees-statsgrid>
      </dees-panel>
      
      <dees-panel .title=${'6. Code Example'} .subtitle=${'How to implement a stats grid with TypeScript'}>
        <div class="code-block">${`const tiles: IStatsTile[] = [
  {
    id: 'revenue',
    title: 'Total Revenue',
    value: 125420,
    unit: '$',
    type: 'number',
    icon: 'lucide:dollar-sign',
    description: '+12.5% from last month',
    actions: [
      {
        name: 'View Details',
        iconName: 'lucide:trending-up',
        action: async () => {
          console.log('View revenue details');
        }
      }
    ]
  },
  {
    id: 'cpu',
    title: 'CPU Usage',
    value: 73,
    unit: '%',
    type: 'gauge',
    icon: 'lucide:cpu',
    gaugeOptions: {
      min: 0,
      max: 100,
      thresholds: [
        { value: 0, color: 'hsl(142.1 76.2% 36.3%)' },
        { value: 60, color: 'hsl(45.4 93.4% 47.5%)' },
        { value: 80, color: 'hsl(0 84.2% 60.2%)' }
      ]
    }
  }
];

// Render the stats grid
html\`
  <dees-statsgrid
    .tiles=\${tiles}
    .minTileWidth=\${250}
    .gap=\${16}
    .gridActions=\${[
      {
        name: 'Refresh',
        iconName: 'lucide:refresh-cw',
        action: async () => console.log('Refresh')
      }
    ]}
  ></dees-statsgrid>
\`;`}</div>
      </dees-panel>

      <dees-panel .title=${'7. Disk & Storage Tiles'} .subtitle=${'Partition and physical disk visualization tiles'}>
        <dees-statsgrid
          .tiles=${[
            {
              id: 'root-partition',
              title: 'Root Partition',
              value: 0,
              type: 'partition',
              icon: 'lucide:folder-root',
              partitionData: {
                used: 698_341_425_152,      // ~650 GB
                total: 1_073_741_824_000,   // ~1 TB
                filesystem: 'ext4',
                mountPoint: '/'
              }
            },
            {
              id: 'home-partition',
              title: 'Home Partition',
              value: 0,
              type: 'partition',
              icon: 'lucide:home',
              partitionData: {
                used: 214_748_364_800,      // ~200 GB
                total: 536_870_912_000,     // ~500 GB
                filesystem: 'ext4',
                mountPoint: '/home'
              }
            },
            {
              id: 'data-partition',
              title: 'Data Partition',
              value: 0,
              type: 'partition',
              icon: 'lucide:database',
              partitionData: {
                used: 1_932_735_283_200,    // ~1.8 TB (90% - critical)
                total: 2_147_483_648_000,   // ~2 TB
                filesystem: 'xfs',
                mountPoint: '/data'
              }
            },
            {
              id: 'nvme-ssd',
              title: 'Primary NVMe',
              value: 0,
              type: 'disk',
              icon: 'lucide:hard-drive',
              columnSpan: 2,
              diskData: {
                capacity: 2_000_000_000_000,  // 2 TB
                model: 'Samsung 990 Pro',
                type: 'nvme',
                iops: {
                  read: 7450,
                  write: 6900
                },
                health: 98
              }
            },
            {
              id: 'sata-ssd',
              title: 'Secondary SSD',
              value: 0,
              type: 'disk',
              icon: 'lucide:hard-drive',
              diskData: {
                capacity: 1_000_000_000_000,  // 1 TB
                model: 'Crucial MX500',
                type: 'ssd',
                iops: {
                  read: 560,
                  write: 510
                },
                health: 85
              }
            },
            {
              id: 'hdd-storage',
              title: 'Backup HDD',
              value: 0,
              type: 'disk',
              icon: 'lucide:archive',
              diskData: {
                capacity: 8_000_000_000_000,  // 8 TB
                model: 'Seagate IronWolf',
                type: 'hdd',
                iops: {
                  read: 210,
                  write: 195
                },
                health: 42
              }
            }
          ]}
          .minTileWidth=${280}
          .gap=${16}
        ></dees-statsgrid>

        <div class="tile-config">
          <div class="config-section">
            <div class="config-title">Partition Tile Properties</div>
            <div class="config-description">
              <ul style="margin: 8px 0; padding-left: 20px;">
                <li><strong>partitionData.used:</strong> Used space in bytes (auto-formatted)</li>
                <li><strong>partitionData.total:</strong> Total capacity in bytes</li>
                <li><strong>partitionData.filesystem:</strong> Filesystem type (ext4, xfs, ntfs)</li>
                <li><strong>partitionData.mountPoint:</strong> Mount point path (optional)</li>
              </ul>
              Color thresholds: Normal (&lt;75%), Warning (75-90%), Critical (&gt;90%)
            </div>
          </div>
          <div class="config-section">
            <div class="config-title">Disk Tile Properties</div>
            <div class="config-description">
              <ul style="margin: 8px 0; padding-left: 20px;">
                <li><strong>diskData.capacity:</strong> Total capacity in bytes</li>
                <li><strong>diskData.model:</strong> Disk model name (optional)</li>
                <li><strong>diskData.type:</strong> Disk type: 'ssd', 'hdd', or 'nvme'</li>
                <li><strong>diskData.iops:</strong> Read/write IOPS (optional)</li>
                <li><strong>diskData.health:</strong> Health percentage 0-100 (optional)</li>
              </ul>
              Health thresholds: Good (70-100%), Warning (30-70%), Critical (&lt;30%)
            </div>
          </div>
        </div>
      </dees-panel>
    </div>

    <script>
      // Cleanup live updates on page unload
      window.addEventListener('beforeunload', () => {
        if ((window as any).liveUpdateInterval) {
          clearInterval((window as any).liveUpdateInterval);
        }
      });
    </script>
  </dees-demowrapper>
  `;
};