<script lang="ts">
  import { clientSession, hasModuleAccess } from '$lib/session';
  import { featureFlags } from '$lib/features';
  import MixCalculatorEditor from '$lib/components/mix-calculator/MixCalculatorEditor.svelte';
  import type { MixCalculatorOptions, MixCalculatorSession } from '$lib/types';

  let { data }: { data: { sessions?: MixCalculatorSession[]; options?: MixCalculatorOptions } } =
    $props();

  const sessions = $derived(data.sessions ?? []);
  const canEdit = $derived(hasModuleAccess($clientSession, 'mix_calculator', 'edit'));

  function formatDate(value: string) {
    return new Intl.DateTimeFormat('en-NZ', {
      dateStyle: 'medium',
      timeStyle: 'short'
    }).format(new Date(value));
  }

  function formatNumber(value: number, digits = 2) {
    return value.toFixed(digits);
  }
</script>

{#if !featureFlags.mixCalculatorSessionHistory}
  <MixCalculatorEditor options={data.options} />
{:else}
{#if canEdit}
  <section class="page-actions">
    <a class="primary-button" href="/mix-calculator/new">New mix session</a>
  </section>
{/if}

<section class="metric-row">
  <article class="metric-card">
    <span>Saved Sessions</span>
    <strong>{sessions.length}</strong>
    <p>Visible under your access scope</p>
  </article>
  <article class="metric-card">
    <span>Total Planned Kg</span>
    <strong>{formatNumber(sessions.reduce((sum, session) => sum + session.total_kg, 0), 2)}</strong>
    <p>Across the visible history</p>
  </article>
  <article class="metric-card">
    <span>Sessions With Warnings</span>
    <strong>{sessions.filter((session) => session.warnings.length).length}</strong>
    <p>Fractional bag outputs need review</p>
  </article>
</section>

<section class="table-card">
  <div class="table-toolbar">
    <div>
      <h3>Session history</h3>
      <p>Operators see their own sessions. Superadmins and admins see the full client history.</p>
    </div>
  </div>

  {#if sessions.length}
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>Session</th>
            <th>Client / Mix</th>
            <th>Batch</th>
            <th>Bags</th>
            <th>Prepared by</th>
            <th>Updated</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {#each sessions as session}
            <tr>
              <td data-label="Session">
                <strong>{session.session_number}</strong>
                <span>{session.mix_name}</span>
              </td>
              <td data-label="Client / Mix">
                <strong>{session.product_name}</strong>
                <span>{session.client_name}</span>
              </td>
              <td data-label="Batch">{formatNumber(session.batch_size_kg, 2)}kg</td>
              <td data-label="Bags">
                {formatNumber(session.total_bags, 2)}
                {#if session.warnings.length}
                  <span class="warning-pill">Warn</span>
                {/if}
              </td>
              <td data-label="Prepared by">{session.prepared_by_name}</td>
              <td data-label="Updated">{formatDate(session.updated_at)}</td>
              <td data-label="Open">
                <div class="row-actions">
                  <a href={`/mix-calculator/${session.id}`}>Open</a>
                  <a href={`/mix-calculator/${session.id}/print`}>Print</a>
                </div>
              </td>
            </tr>
          {/each}
        </tbody>
      </table>
    </div>
  {:else}
    <div class="empty-state">
      <strong>No saved sessions yet</strong>
      <span>{canEdit ? 'Run a new calculation and save it to start your session history.' : 'No sessions are visible under your access scope yet.'}</span>
    </div>
  {/if}
</section>
{/if}

<style>
  h2,
  h3,
  p {
    margin: 0;
  }

  .eyebrow {
    color: #7d8d84;
    font-size: 0.78rem;
    font-weight: 600;
    letter-spacing: 0.08em;
    text-transform: uppercase;
  }

  .page-actions,
  .metric-row,
  .table-card {
    margin-bottom: 1.25rem;
  }

  .page-actions {
    display: flex;
    justify-content: flex-end;
  }

  .metric-card p,
  .table-toolbar p,
  tbody span {
    color: var(--muted);
  }

  .primary-button {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0.78rem 0.96rem;
    border-radius: 0.6rem;
    background: var(--color-brand);
    color: #fff;
    font-weight: 600;
    transition: background-color 160ms ease;
  }

  .primary-button:hover {
    background: #126a33;
  }

  .primary-button:active {
    background: #0f5a2b;
  }

  .primary-button:focus-visible {
    outline: 3px solid color-mix(in srgb, var(--color-brand) 45%, transparent);
    outline-offset: 2px;
  }

  .metric-row {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 1rem;
  }

  .metric-card,
  .table-card {
    border: 1px solid var(--line);
    border-radius: 0.8rem;
    background: var(--panel);
    box-shadow: var(--shadow);
  }

  .metric-card {
    padding: 1.15rem 1.2rem;
  }

  .metric-card span {
    display: block;
    color: var(--muted);
    font-size: 0.9rem;
  }

  .metric-card strong {
    display: block;
    margin: 0.55rem 0 0.3rem;
    font-size: 1.9rem;
  }

  .table-card {
    padding: 1.2rem;
  }

  .table-toolbar {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 1rem;
    margin-bottom: 1rem;
  }

  .table-wrap {
    overflow-x: auto;
  }

  table {
    width: 100%;
    min-width: 54rem;
    border-collapse: separate;
    border-spacing: 0 0.75rem;
  }

  th,
  td {
    padding: 1rem;
    text-align: left;
    white-space: nowrap;
  }

  th {
    color: var(--muted);
    font-size: 0.78rem;
    font-weight: 600;
    letter-spacing: 0.06em;
    text-transform: uppercase;
  }

  tbody td {
    background: var(--panel-soft);
    border-top: 1px solid var(--line);
    border-bottom: 1px solid var(--line);
  }

  tbody td:first-child {
    border-left: 1px solid var(--line);
    border-radius: 0.65rem 0 0 0.65rem;
  }

  tbody td:last-child {
    border-right: 1px solid var(--line);
    border-radius: 0 0.65rem 0.65rem 0;
  }

  .row-actions {
    display: flex;
    align-items: center;
    gap: 0.8rem;
  }

  .row-actions a {
    font-weight: 600;
  }

  .warning-pill {
    display: inline-flex;
    margin-left: 0.55rem;
    padding: 0.25rem 0.5rem;
    border-radius: 999px;
    background: #fdf6e9;
    color: #8a5a00;
    font-size: 0.72rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.06em;
  }

  .empty-state {
    display: grid;
    gap: 0.2rem;
    padding: 1rem;
    border-radius: 0.65rem;
    background: var(--panel-soft);
  }

  @media (max-width: 900px) {
    .metric-row {
      grid-template-columns: 1fr;
    }
  }

  @media (max-width: 760px) {
    .table-toolbar {
      flex-direction: column;
      align-items: flex-start;
    }

    table,
    thead,
    tbody,
    tr,
    td {
      display: block;
      width: 100%;
    }

    table {
      min-width: 0;
      border-spacing: 0;
    }

    thead {
      display: none;
    }

    tbody {
      display: grid;
      gap: 0.9rem;
    }

    tbody tr {
      padding: 0.3rem;
      border: 1px solid var(--line);
      border-radius: 0.65rem;
      background: var(--panel-soft);
    }

    tbody td {
      padding: 0.78rem 0.8rem;
      white-space: normal;
      border: none;
      border-radius: 0;
      background: transparent;
    }

    tbody td:first-child,
    tbody td:last-child {
      border: none;
      border-radius: 0;
    }

    tbody td + td {
      border-top: 1px solid var(--line);
    }

    tbody td::before {
      content: attr(data-label);
      display: block;
      margin-bottom: 0.35rem;
      color: var(--muted);
      font-size: 0.72rem;
      font-weight: 700;
      letter-spacing: 0.06em;
      text-transform: uppercase;
    }
  }
</style>
