<script lang="ts">
  import AppSecondaryRail from '$lib/components/navigation/AppSecondaryRail.svelte';
  import AppSecondaryRailLayout from '$lib/components/navigation/AppSecondaryRailLayout.svelte';
  import {
    BarChart3,
    TrendingUp,
    Wheat,
    FlaskConical,
    Boxes,
    AlertTriangle,
    ClipboardCheck,
    FileText,
  } from 'lucide-svelte';
  import type { ComponentType } from 'svelte';

  type ReportId =
    | 'sales-target-report'
    | 'finished-product-kanban'
    | 'summary'
    | 'raw-material-costs'
    | 'mix-cost-summary'
    | 'product-pricing'
    | 'data-quality'
    | 'price-review';

  type ReportItem = {
    id: ReportId;
    label: string;
    description: string;
    icon: ComponentType;
    group: string;
  };

  const reports: ReportItem[] = [
    {
      id: 'sales-target-report',
      label: 'Sales Target Report',
      description: 'Embedded Power BI sales target view for current sales tracking and review.',
      icon: FileText,
      group: 'Power BI',
    },
    {
      id: 'finished-product-kanban',
      label: 'Finished Product - Kanban',
      description: 'Embedded Power BI board for finished product review and kanban-style planning.',
      icon: FileText,
      group: 'Power BI',
    },
    {
      id: 'summary',
      label: 'Overview',
      description: 'High-level snapshot of the current costing model.',
      icon: BarChart3,
      group: 'Overview',
    },
    {
      id: 'raw-material-costs',
      label: 'Raw Material Costs',
      description: 'Current prices, waste assumptions, and cost per kg for all tracked inputs.',
      icon: Wheat,
      group: 'Costing',
    },
    {
      id: 'mix-cost-summary',
      label: 'Mix Cost Summary',
      description: 'Per-mix cost per kg across the current mix master.',
      icon: FlaskConical,
      group: 'Costing',
    },
    {
      id: 'product-pricing',
      label: 'Product Pricing',
      description: 'Finished delivered cost and selling price outputs by product.',
      icon: Boxes,
      group: 'Costing',
    },
    {
      id: 'data-quality',
      label: 'Data Quality',
      description: 'Items with missing costs, unresolved warnings, or stale inputs.',
      icon: AlertTriangle,
      group: 'Quality',
    },
    {
      id: 'price-review',
      label: 'Price Review',
      description: 'Current vs proposed pricing status across all products.',
      icon: ClipboardCheck,
      group: 'Quality',
    },
  ];

  const SALES_TARGET_REPORT_URL =
    'https://app.powerbi.com/view?r=eyJrIjoiZjc1NjljNmEtMmJkMi00ZDlmLThjN2MtNjgyMzcxZDUwMzIyIiwidCI6IjEwNjk4Y2EyLTVmMmUtNGUwYS04ZTQ2LWE5ZGI0Nzk3ZjQ3MCJ9';

  const FINISHED_PRODUCT_KANBAN_URL =
    'https://app.powerbi.com/view?r=eyJrIjoiOTBjYTQ2MjMtZjMwNi00MjAzLTgxNDYtMmEzM2QwNjhlNmFlIiwidCI6IjEwNjk4Y2EyLTVmMmUtNGUwYS04ZTQ2LWE5ZGI0Nzk3ZjQ3MCJ9';

  const orderedGroups = ['Power BI', 'Overview', 'Costing', 'Quality'];

  const railGroups = orderedGroups
    .filter((group) => reports.some((report) => report.group === group))
    .map((group) => ({
    label: group,
    items: reports.filter((report) => report.group === group)
  }));

  let activeId = $state<ReportId>('sales-target-report');

  const activeReport = $derived(reports.find((r) => r.id === activeId) ?? reports[0]);
</script>

<AppSecondaryRailLayout>
  {#snippet rail()}
    <AppSecondaryRail
      sectionLabel="Reporting"
      identityTitle="Workspace reports"
      identitySubtitle="Costing and quality views"
      identityIcon={TrendingUp}
      groups={railGroups}
      activeId={activeId}
      onSelect={(id) => (activeId = id as ReportId)}
    />
  {/snippet}

  <div class="report-panel">
    <div class="panel-body">
      {#if activeId === 'summary'}
        <div class="report-placeholder">
          <div class="placeholder-icon" aria-hidden="true">
            <BarChart3 size={32} strokeWidth={1.25} />
          </div>
          <strong>Overview report</strong>
          <span>A summary of raw material count, mix count, product pricing outputs, and open data quality issues will appear here.</span>
          <div class="placeholder-chips">
            <span class="chip">Raw Material Costs</span>
            <span class="chip">Mix Cost Summary</span>
            <span class="chip">Product Pricing</span>
            <span class="chip">Data Quality</span>
          </div>
        </div>

      {:else if activeId === 'raw-material-costs'}
        <div class="report-placeholder">
          <div class="placeholder-icon" aria-hidden="true">
            <Wheat size={32} strokeWidth={1.25} />
          </div>
          <strong>Raw Material Costs</strong>
          <span>Market value, waste percentage, cost per unit, and cost per kg for every tracked raw material will display here.</span>
          <div class="placeholder-table-preview">
            <div class="preview-header-row">
              <span>Raw Material</span><span>Market Value</span><span>Waste %</span><span>Cost / Kg</span>
            </div>
            {#each [1, 2, 3, 4] as _}
              <div class="preview-data-row">
                <div class="shimmer wide"></div>
                <div class="shimmer medium"></div>
                <div class="shimmer short"></div>
                <div class="shimmer medium"></div>
              </div>
            {/each}
          </div>
        </div>

      {:else if activeId === 'mix-cost-summary'}
        <div class="report-placeholder">
          <div class="placeholder-icon" aria-hidden="true">
            <FlaskConical size={32} strokeWidth={1.25} />
          </div>
          <strong>Mix Cost Summary</strong>
          <span>Total ingredients, total kg, total mix cost, and cost per kg for each mix in the current mix master will appear here.</span>
          <div class="placeholder-table-preview">
            <div class="preview-header-row">
              <span>Mix Name</span><span>Client</span><span>Ingredients</span><span>Cost / Kg</span>
            </div>
            {#each [1, 2, 3, 4] as _}
              <div class="preview-data-row">
                <div class="shimmer wide"></div>
                <div class="shimmer medium"></div>
                <div class="shimmer short"></div>
                <div class="shimmer medium"></div>
              </div>
            {/each}
          </div>
        </div>

      {:else if activeId === 'product-pricing'}
        <div class="report-placeholder">
          <div class="placeholder-icon" aria-hidden="true">
            <Boxes size={32} strokeWidth={1.25} />
          </div>
          <strong>Product Pricing Output</strong>
          <span>Cleaned product cost, process costs, packaging, freight, finished delivered cost, and selling price by product will appear here.</span>
          <div class="placeholder-table-preview">
            <div class="preview-header-row">
              <span>Product</span><span>Cleaned Cost</span><span>Delivered</span><span>Distributor</span>
            </div>
            {#each [1, 2, 3, 4] as _}
              <div class="preview-data-row">
                <div class="shimmer wide"></div>
                <div class="shimmer medium"></div>
                <div class="shimmer medium"></div>
                <div class="shimmer medium"></div>
              </div>
            {/each}
          </div>
        </div>

      {:else if activeId === 'data-quality'}
        <div class="report-placeholder">
          <div class="placeholder-icon warning" aria-hidden="true">
            <AlertTriangle size={32} strokeWidth={1.25} />
          </div>
          <strong>Data Quality Issues</strong>
          <span>Raw materials missing costs, mixes with unresolved warnings, and products with stale or missing inputs will be listed here.</span>
          <div class="placeholder-chips">
            <span class="chip warning">Missing prices</span>
            <span class="chip warning">Unresolved notes</span>
            <span class="chip warning">Zero quantities</span>
          </div>
        </div>

      {:else if activeId === 'price-review'}
        <div class="report-placeholder">
          <div class="placeholder-icon" aria-hidden="true">
            <ClipboardCheck size={32} strokeWidth={1.25} />
          </div>
          <strong>Price Review Status</strong>
          <span>Current vs proposed wholesale and distributor pricing, with review status and delta for each product line, will appear here.</span>
          <div class="placeholder-table-preview">
            <div class="preview-header-row">
              <span>Product</span><span>Current</span><span>Proposed</span><span>Status</span>
            </div>
            {#each [1, 2, 3, 4] as _}
              <div class="preview-data-row">
                <div class="shimmer wide"></div>
                <div class="shimmer medium"></div>
                <div class="shimmer medium"></div>
                <div class="shimmer short"></div>
              </div>
            {/each}
          </div>
        </div>

      {:else if activeId === 'sales-target-report'}
        <section class="powerbi-embed">
          <header class="embed-header">
            <div>
              <h2>Sales Target Report</h2>
              <p>Live embedded Power BI view for sales target tracking and review.</p>
            </div>
            <a class="powerbi-link" href={SALES_TARGET_REPORT_URL} target="_blank" rel="noreferrer">
              Open in Power BI
            </a>
          </header>

          <div class="powerbi-frame-shell">
            <iframe
              title="Sales Target Report"
              src={SALES_TARGET_REPORT_URL}
              class="powerbi-frame"
              allowfullscreen
            ></iframe>
          </div>
        </section>

      {:else if activeId === 'finished-product-kanban'}
        <section class="powerbi-embed">
          <header class="embed-header">
            <div>
              <h2>Finished Product - Kanban</h2>
              <p>Live embedded Power BI view for finished product review and kanban-style planning.</p>
            </div>
            <a class="powerbi-link" href={FINISHED_PRODUCT_KANBAN_URL} target="_blank" rel="noreferrer">
              Open in Power BI
            </a>
          </header>

          <div class="powerbi-frame-shell">
            <iframe
              title="Finished Product - Kanban"
              src={FINISHED_PRODUCT_KANBAN_URL}
              class="powerbi-frame"
              allowfullscreen
            ></iframe>
          </div>
        </section>
      {/if}
    </div>
  </div>
</AppSecondaryRailLayout>

<style>
  .report-panel {
    display: flex;
    flex-direction: column;
    min-width: 0;
    background: var(--panel);
  }

  .panel-body {
    padding: 1.25rem 1.35rem 1.35rem;
  }

  .powerbi-embed {
    display: grid;
    gap: 0.85rem;
    min-height: 42rem;
  }

  .embed-header {
    position: sticky;
    top: 0;
    z-index: 2;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1.25rem;
    padding: 0 0 0.35rem;
    background: color-mix(in srgb, var(--panel) 90%, transparent);
    backdrop-filter: blur(8px);
  }

  .embed-header h2 {
    margin: 0;
    color: var(--text);
    font-size: 1.08rem;
    font-weight: 700;
  }

  .embed-header p {
    margin: 0.18rem 0 0;
    color: var(--muted);
    font-size: 0.82rem;
    line-height: 1.45;
  }

  .powerbi-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0.56rem 0.2rem;
    border: none;
    border-bottom: 1px solid color-mix(in srgb, var(--color-brand) 22%, transparent);
    border-radius: 0;
    background: transparent;
    color: #405148;
    font-size: 0.84rem;
    font-weight: 600;
    white-space: nowrap;
  }

  .powerbi-frame-shell {
    min-height: 36rem;
    border-top: 1px solid color-mix(in srgb, var(--line) 88%, transparent);
    overflow: hidden;
    background: #f6f8f6;
  }

  .powerbi-frame {
    width: 100%;
    height: min(78vh, 980px);
    border: 0;
    background: #fff;
  }

  /* ── Report placeholders ───────────────────────────────────────── */

  .report-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.6rem;
    padding: 2.5rem 1.5rem 2rem;
    text-align: center;
  }

  .placeholder-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 3.5rem;
    height: 3.5rem;
    border-radius: 1rem;
    background: var(--color-brand-tint);
    color: var(--color-brand);
    border: 1px solid color-mix(in srgb, var(--color-brand) 15%, transparent);
    margin-bottom: 0.4rem;
  }

  .placeholder-icon.warning {
    background: #fff6e6;
    color: #b06a10;
    border-color: rgba(176, 106, 16, 0.2);
  }

  .report-placeholder strong {
    font-size: 1rem;
    font-weight: 700;
    color: var(--text);
  }

  .report-placeholder span {
    max-width: 36rem;
    font-size: 0.87rem;
    color: var(--muted);
    line-height: 1.55;
  }

  .placeholder-chips {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 0.45rem;
    margin-top: 0.75rem;
  }

  .chip {
    display: inline-flex;
    align-items: center;
    padding: 0.3rem 0.72rem;
    border-radius: 999px;
    background: var(--color-brand-tint);
    color: var(--color-brand);
    font-size: 0.78rem;
    font-weight: 600;
    border: 1px solid color-mix(in srgb, var(--color-brand) 12%, transparent);
  }

  .chip.warning {
    background: #fff6e6;
    color: #b06a10;
    border-color: rgba(176, 106, 16, 0.15);
  }

  /* ── Shimmer table preview ─────────────────────────────────────── */

  .placeholder-table-preview {
    width: 100%;
    max-width: 44rem;
    margin-top: 1.25rem;
    border: 1px solid var(--line);
    border-radius: 0.9rem;
    overflow: hidden;
  }

  .preview-header-row {
    display: grid;
    grid-template-columns: 2fr 1fr 1fr 1fr;
    gap: 1rem;
    padding: 0.6rem 1rem;
    background: var(--panel-soft);
    border-bottom: 1px solid var(--line);
    color: var(--muted);
    font-size: 0.72rem;
    font-weight: 700;
    letter-spacing: 0.07em;
    text-transform: uppercase;
  }

  .preview-data-row {
    display: grid;
    grid-template-columns: 2fr 1fr 1fr 1fr;
    gap: 1rem;
    align-items: center;
    padding: 0.72rem 1rem;
    border-bottom: 1px solid var(--line);
  }

  .preview-data-row:last-child {
    border-bottom: none;
  }

  .shimmer {
    height: 0.65rem;
    border-radius: 999px;
    background: linear-gradient(
      90deg,
      var(--color-border) 25%,
      color-mix(in srgb, var(--color-border) 40%, white) 50%,
      var(--color-border) 75%
    );
    background-size: 200% 100%;
    animation: shimmer 1.9s ease-in-out infinite;
  }

  .shimmer.short  { width: 45%; }
  .shimmer.medium { width: 70%; }
  .shimmer.wide   { width: 92%; }

  @keyframes shimmer {
    0%   { background-position: 200% 0; }
    100% { background-position: -200% 0; }
  }

  /* ── Responsive ────────────────────────────────────────────────── */

  @media (max-width: 640px) {
    .embed-header {
      flex-direction: column;
      align-items: start;
    }

    .powerbi-link {
      width: 100%;
    }

    .preview-header-row,
    .preview-data-row {
      grid-template-columns: 1fr 1fr;
    }

    .preview-header-row span:nth-child(n+3),
    .preview-data-row .shimmer:nth-child(n+3) {
      display: none;
    }
  }
</style>
