<script lang="ts">
  import { ArrowUpDown, ChevronLeft, ChevronRight, History, Pencil, Search, Trash2, TriangleAlert, X } from 'lucide-svelte';
  import { fade } from 'svelte/transition';

  import type { SortKey } from '$lib/components/throughput/utils';
  import type { ThroughputEntry, ThroughputProduct, ThroughputQuantityType } from '$lib/types';

  let {
    products,
    filtersActive,
    showFilters = $bindable(false),
    dateFrom = $bindable(''),
    dateTo = $bindable(''),
    productFilter = $bindable(''),
    staffFilter = $bindable(''),
    typeFilter = $bindable<'' | ThroughputQuantityType>(''),
    isLoading,
    errorMessage,
    sortKey,
    highlightId,
    deletingId,
    sortedEntries,
    paginatedEntries,
    page = $bindable(1),
    totalPages,
    pageStart,
    pageEnd,
    formatDate,
    formatNumber,
    packedMain,
    packedDetail,
    destinationOf,
    onApplyFilters,
    onClearFilters,
    onToggleSort,
    onStartEdit,
    onRequestDelete
  }: {
    products: ThroughputProduct[];
    filtersActive: boolean;
    showFilters?: boolean;
    dateFrom?: string;
    dateTo?: string;
    productFilter?: string;
    staffFilter?: string;
    typeFilter?: '' | ThroughputQuantityType;
    isLoading: boolean;
    errorMessage: string;
    sortKey: SortKey;
    highlightId: number | null;
    deletingId: number | null;
    sortedEntries: ThroughputEntry[];
    paginatedEntries: ThroughputEntry[];
    page: number;
    totalPages: number;
    pageStart: number;
    pageEnd: number;
    formatDate: (value: string) => string;
    formatNumber: (value: number | null | undefined, digits?: number) => string;
    packedMain: (entry: ThroughputEntry) => string;
    packedDetail: (entry: ThroughputEntry) => string;
    destinationOf: (entry: ThroughputEntry) => { label: string; detail: string | null };
    onApplyFilters: () => void;
    onClearFilters: () => void;
    onToggleSort: (key: SortKey) => void;
    onStartEdit: (entry: ThroughputEntry) => void;
    onRequestDelete: (entry: ThroughputEntry) => void;
  } = $props();
</script>

<div class="history-shell">
  <div class="log-controls">
    <div class="log-title">
      <h2 class="history-title">
        {#if !filtersActive}<History size={18} strokeWidth={2.1} />{/if}
        <span>{filtersActive ? 'Filtered entries' : 'Recent entries'}</span>
      </h2>
      <span class="log-subtitle">{filtersActive ? 'Matching runs' : 'Last 30 days'}</span>
    </div>
    <button
      type="button"
      class="find-button"
      class:active={showFilters}
      aria-expanded={showFilters}
      onclick={() => (showFilters = !showFilters)}
    >
      <Search size={18} strokeWidth={2.2} />
      <span>Find past entries</span>
      {#if filtersActive}<span class="find-dot" aria-label="filters applied"></span>{/if}
    </button>
  </div>

  {#if showFilters}
    <form
      class="filters"
      transition:fade={{ duration: 120 }}
      onsubmit={(e) => {
        e.preventDefault();
        onApplyFilters();
      }}
    >
      <label>
        <span>From date</span>
        <input type="date" bind:value={dateFrom} />
      </label>
      <label>
        <span>To date</span>
        <input type="date" bind:value={dateTo} />
      </label>
      <label>
        <span>Product</span>
        <select bind:value={productFilter}>
          <option value="">All products</option>
          {#each products as product (product.id)}
            <option value={String(product.id)}>{product.name}</option>
          {/each}
        </select>
      </label>
      <label>
        <span>Staff</span>
        <input type="text" placeholder="Name" bind:value={staffFilter} />
      </label>
      <label>
        <span>Packed as</span>
        <select bind:value={typeFilter}>
          <option value="">Bags or kg</option>
          <option value="bags">Bags</option>
          <option value="kg">Kilograms</option>
        </select>
      </label>
      <div class="filter-actions">
        <button type="submit" class="apply-button" disabled={isLoading}>
          {isLoading ? 'Searching…' : 'Search'}
        </button>
        {#if filtersActive}
          <button type="button" class="clear-button" onclick={onClearFilters}>
            <X size={16} strokeWidth={2.4} /> Clear
          </button>
        {/if}
      </div>
    </form>
  {/if}

  {#if errorMessage}
    <div class="error" role="alert">
      <TriangleAlert size={20} strokeWidth={2.2} />
      <span>{errorMessage}</span>
      <button type="button" class="retry-button" onclick={onApplyFilters}>Try again</button>
    </div>
  {/if}

  <div class="log">
    <div class="log-head">
      <button type="button" class="sort-head" class:active={sortKey === 'date'} onclick={() => onToggleSort('date')}>
        <span>Date</span>
        <ArrowUpDown size={14} strokeWidth={2.1} />
      </button>
      <button type="button" class="sort-head" class:active={sortKey === 'product'} onclick={() => onToggleSort('product')}>
        <span>Product</span>
        <ArrowUpDown size={14} strokeWidth={2.1} />
      </button>
      <button type="button" class="sort-head" class:active={sortKey === 'packed'} onclick={() => onToggleSort('packed')}>
        <span>Packed</span>
        <ArrowUpDown size={14} strokeWidth={2.1} />
      </button>
      <button type="button" class="sort-head" class:active={sortKey === 'total'} onclick={() => onToggleSort('total')}>
        <span>Total kg</span>
        <ArrowUpDown size={14} strokeWidth={2.1} />
      </button>
      <button type="button" class="sort-head" class:active={sortKey === 'staff'} onclick={() => onToggleSort('staff')}>
        <span>Packed by</span>
        <ArrowUpDown size={14} strokeWidth={2.1} />
      </button>
      <button type="button" class="sort-head" class:active={sortKey === 'destination'} onclick={() => onToggleSort('destination')}>
        <span>Destination</span>
        <ArrowUpDown size={14} strokeWidth={2.1} />
      </button>
      <button type="button" class="sort-head col-notes-head" class:active={sortKey === 'notes'} onclick={() => onToggleSort('notes')}>
        <span>Notes</span>
        <ArrowUpDown size={14} strokeWidth={2.1} />
      </button>
      <span class="col-actions-head">Edit</span>
    </div>

    {#if isLoading}
      {#each Array(5) as _, i (i)}
        <div class="row row-skeleton" aria-hidden="true">
          <span class="sk sk-date"></span>
          <span class="sk sk-product"></span>
          <span class="sk sk-packed"></span>
          <span class="sk sk-staff"></span>
          <span class="sk sk-qa"></span>
        </div>
      {/each}
    {:else}
      {#each paginatedEntries as entry (entry.id)}
        {@const dest = destinationOf(entry)}
        <div class="row" class:just-added={entry.id === highlightId}>
          <span class="col-date">
            <span class="cell-label">Date</span>
            {formatDate(entry.production_date)}
          </span>
          <span class="col-product">
            <span class="cell-label">Product</span>
            <span class="product-name">{entry.product_name_snapshot}</span>
          </span>
          <span class="col-packed">
            <span class="cell-label">Packed</span>
            <span class="packed-main">{packedMain(entry)}</span>
            <span class="packed-detail">{packedDetail(entry)}</span>
          </span>
          <span class="col-total">
            <span class="cell-label">Total kg</span>
            <span class="total-kg">{formatNumber(entry.calculated_kg)} kg</span>
          </span>
          <span class="col-staff">
            <span class="cell-label">Packed by</span>
            {entry.staff_name ?? '—'}
          </span>
          <span class="col-dest">
            <span class="cell-label">Destination</span>
            <span
              class="pill"
              class:pill-stock={dest.label === 'Stock'}
              class:pill-order={dest.label === 'Order'}
              class:pill-split={dest.label === 'Split'}
            >{dest.label}</span>
            {#if dest.detail}<span class="dest-detail">{dest.detail}</span>{/if}
          </span>
          <span class="col-actions">
            <button
              type="button"
              class="row-action"
              title="Edit this run"
              aria-label="Edit this run"
              onclick={() => onStartEdit(entry)}
            >
              <Pencil size={16} strokeWidth={2.2} />
            </button>
            <button
              type="button"
              class="row-action row-action-danger"
              title="Delete this run"
              aria-label="Delete this run"
              disabled={deletingId === entry.id}
              onclick={() => onRequestDelete(entry)}
            >
              <Trash2 size={16} strokeWidth={2.2} />
            </button>
          </span>
          {#if entry.notes}
            <p class="row-notes"><span class="cell-label">Note</span>{entry.notes}</p>
          {/if}
        </div>
      {:else}
        <div class="empty">
          {#if filtersActive}
            <p class="empty-title">No entries match your search</p>
            <p class="empty-help">Try a wider date range, or clear the filters to see everything.</p>
            <button type="button" class="clear-button" onclick={onClearFilters}>
              <X size={16} strokeWidth={2.4} /> Clear filters
            </button>
          {:else}
            <p class="empty-title">No packing logged yet</p>
            <p class="empty-help">Use the inline entry area above to add your first run. It appears here immediately, newest first.</p>
          {/if}
        </div>
      {/each}
    {/if}
  </div>

  {#if sortedEntries.length > 0}
    <div class="pagination">
      <p class="pagination-summary">{pageStart}-{pageEnd} of {sortedEntries.length}</p>
      <div class="pagination-actions">
        <button type="button" class="page-button" disabled={page === 1} onclick={() => (page = Math.max(1, page - 1))}>
          <ChevronLeft size={16} strokeWidth={2.2} />
          <span>Previous</span>
        </button>
        <span class="page-indicator">Page {page} of {totalPages}</span>
        <button type="button" class="page-button" disabled={page === totalPages} onclick={() => (page = Math.min(totalPages, page + 1))}>
          <span>Next</span>
          <ChevronRight size={16} strokeWidth={2.2} />
        </button>
      </div>
    </div>
  {/if}
</div>

<style>
  .history-shell {
    display: grid;
    gap: 0.95rem;
  }

  .log-controls {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem;
    flex-wrap: wrap;
  }

  .log-title {
    display: grid;
    gap: 0.2rem;
  }

  .history-title {
    display: inline-flex;
    align-items: center;
    gap: 0.55rem;
    margin: 0;
    font-size: 1.16rem;
    font-weight: 700;
    letter-spacing: -0.02em;
  }

  .log-subtitle {
    color: var(--color-text-secondary);
    font-size: 0.9rem;
  }

  .find-button,
  .apply-button,
  .clear-button,
  .retry-button,
  .sort-head,
  .page-button {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.45rem;
    cursor: pointer;
  }

  .find-button {
    position: relative;
    min-height: 44px;
    padding: 0.6rem 0.95rem;
    border: 1px solid color-mix(in srgb, var(--color-brand) 18%, var(--color-border));
    border-radius: 0.78rem;
    background: var(--color-bg-surface);
    color: var(--color-text-primary);
    font-size: 0.95rem;
    font-weight: 650;
  }

  .find-button.active {
    border-color: var(--color-brand);
    background: var(--color-brand-tint);
    color: var(--color-success);
  }

  .find-dot {
    width: 0.5rem;
    height: 0.5rem;
    border-radius: 50%;
    background: var(--color-brand);
  }

  .filters {
    display: grid;
    grid-template-columns: repeat(5, minmax(0, 1fr)) auto;
    gap: 0.8rem;
    align-items: end;
    padding: 1rem;
    border: 1px solid var(--color-border);
    border-radius: 0.95rem;
    background: color-mix(in srgb, var(--color-bg-surface) 82%, white);
  }

  .filters label {
    display: grid;
    gap: 0.32rem;
    font-size: 0.88rem;
    font-weight: 600;
    color: var(--color-text-secondary);
  }

  .filters input,
  .filters select {
    min-height: 44px;
    padding: 0.58rem 0.72rem;
    border: 1px solid color-mix(in srgb, var(--color-brand) 12%, var(--color-border));
    border-radius: 0.78rem;
    font-size: 0.97rem;
    color: var(--color-text-primary);
    background: var(--color-bg-surface);
  }

  .filter-actions {
    display: inline-flex;
    align-items: center;
    gap: 0.6rem;
    flex-wrap: wrap;
  }

  .apply-button,
  .clear-button,
  .retry-button,
  .page-button {
    min-height: 42px;
    padding: 0.55rem 0.82rem;
    border: 1px solid var(--color-border);
    border-radius: 0.72rem;
    background: var(--color-bg-surface);
    color: var(--color-text-primary);
    font-size: 0.92rem;
    font-weight: 650;
  }

  .apply-button {
    border-color: var(--color-brand);
    background: var(--color-brand);
    color: #fff;
  }

  .clear-button {
    color: var(--color-text-secondary);
  }

  .error {
    display: flex;
    align-items: center;
    gap: 0.7rem;
    flex-wrap: wrap;
    padding: 0.95rem 1rem;
    border: 1px solid #efc6c2;
    border-radius: 0.9rem;
    background: #fff4f2;
    color: #8a1622;
  }

  .log {
    border: 1px solid var(--color-border);
    border-radius: 1rem;
    background: var(--color-bg-surface);
    overflow: clip;
  }

  .log-head,
  .row {
    display: grid;
    grid-template-columns: 8rem minmax(0, 1.1fr) minmax(0, 0.95fr) 6rem minmax(0, 0.8fr) 10.5rem 4.8rem;
    gap: 0.85rem;
    align-items: center;
  }

  .log-head {
    padding: 0.9rem 1.45rem;
    border-bottom: 1px solid var(--color-divider);
    background: color-mix(in srgb, var(--color-bg-app) 55%, var(--color-bg-surface));
  }

  .sort-head {
    justify-content: flex-start;
    padding: 0;
    border: 0;
    background: none;
    color: var(--color-text-secondary);
    font-size: 0.8rem;
    font-weight: 750;
    letter-spacing: 0.08em;
    text-transform: uppercase;
  }

  .sort-head.active,
  .sort-head:hover {
    color: var(--color-text-primary);
  }

  .row {
    padding: 1rem 1.45rem;
    border-bottom: 1px solid var(--color-divider);
    transition: background-color 160ms ease;
  }

  .row:last-child {
    border-bottom: 0;
  }

  .row:hover {
    background: #fafbfc;
  }

  .row.just-added {
    animation: flash-in 1.8s ease-out;
  }

  @keyframes flash-in {
    0% { background: var(--color-brand-tint); }
    100% { background: transparent; }
  }

  .col-product,
  .col-dest,
  .col-packed,
  .col-total {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 0.1rem;
  }

  .product-name,
  .packed-main,
  .total-kg {
    font-weight: 650;
  }

  .dest-detail,
  .packed-detail {
    font-size: 0.88rem;
    color: var(--color-text-secondary);
  }

  .total-kg,
  .packed-main,
  .dest-detail {
    font-variant-numeric: tabular-nums;
  }

  .col-actions {
    display: inline-flex;
    align-items: center;
    justify-content: flex-end;
    gap: 0.3rem;
  }

  .col-actions-head {
    justify-self: end;
    color: var(--color-text-muted);
    font-size: 0.78rem;
    font-weight: 700;
    letter-spacing: 0.08em;
    text-transform: uppercase;
  }

  .row-action {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 2.1rem;
    height: 2.1rem;
    padding: 0;
    border: 1px solid var(--color-border);
    border-radius: 0.55rem;
    background: var(--color-bg-surface);
    color: var(--color-text-secondary);
    cursor: pointer;
    transition: border-color 140ms ease, color 140ms ease, background-color 140ms ease;
  }

  .row-action:hover {
    border-color: var(--color-text-muted);
    color: var(--color-text-primary);
    background: #fafbfc;
  }

  .row-action-danger:hover {
    border-color: #e2a8af;
    color: #b3261e;
    background: #fdecee;
  }

  .row-action:disabled,
  .page-button:disabled,
  .apply-button:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .row-notes {
    grid-column: 1 / -1;
    margin: 0.35rem 0 0;
    padding-top: 0.65rem;
    border-top: 1px dashed var(--color-divider);
    font-size: 0.94rem;
    color: var(--color-text-secondary);
  }

  .cell-label {
    display: none;
    font-size: 0.85rem;
    font-weight: 600;
    color: var(--color-text-muted);
  }

  .col-notes-head {
    display: none;
  }

  .pill {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    padding: 0.42rem 0.78rem;
    border-radius: 999px;
    font-size: 0.86rem;
    font-weight: 650;
    white-space: nowrap;
  }

  .pill-stock {
    background: #e8f1fc;
    color: #0b5cad;
  }

  .pill-order {
    background: var(--color-brand-tint);
    color: var(--color-success);
  }

  .pill-split {
    background: #f3e8fc;
    color: #6b21a8;
  }

  .row-skeleton {
    padding: 1.15rem 1.45rem;
    border-bottom: 1px solid var(--color-divider);
  }

  .sk {
    height: 1.1rem;
    border-radius: 0.4rem;
    background: linear-gradient(90deg, #eef1f4 25%, #f6f8fa 50%, #eef1f4 75%);
    background-size: 200% 100%;
    animation: shimmer 1.3s ease-in-out infinite;
  }

  .sk-staff { width: 70%; }
  .sk-qa { width: 6rem; height: 1.7rem; border-radius: 999px; }

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

  .empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.6rem;
    padding: 3rem 1.5rem;
    text-align: center;
  }

  .empty-title {
    margin: 0;
    font-size: 1.3rem;
    font-weight: 650;
    color: var(--color-text-primary);
  }

  .empty-help {
    margin: 0;
    font-size: 1.02rem;
    color: var(--color-text-secondary);
    max-width: 42ch;
  }

  .pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem;
    flex-wrap: wrap;
    padding: 1rem 1.45rem 1.15rem;
    border-top: 1px solid var(--color-divider);
    background: color-mix(in srgb, var(--color-bg-app) 48%, var(--color-bg-surface));
  }

  .pagination-summary,
  .page-indicator {
    margin: 0;
    color: var(--color-text-secondary);
    font-size: 0.94rem;
    font-weight: 600;
  }

  .pagination-actions {
    display: inline-flex;
    align-items: center;
    gap: 0.6rem;
    flex-wrap: wrap;
  }

  @media (max-width: 760px) {
    .log-controls,
    .filters,
    .error {
      padding-left: 1.15rem;
      padding-right: 1.15rem;
    }

    .history-title {
      font-size: 1.28rem;
    }

    .log-head {
      display: none;
    }

    .row {
      grid-template-columns: 1fr 1fr;
      gap: 0.75rem 1rem;
      padding: 1rem 1.15rem;
    }

    .col-product,
    .row-notes {
      grid-column: 1 / -1;
    }

    .cell-label {
      display: block;
      margin-bottom: 0.1rem;
    }

    .col-actions {
      grid-column: 1 / -1;
      justify-content: flex-start;
      gap: 0.5rem;
      padding-top: 0.5rem;
      border-top: 1px dashed var(--color-divider);
    }

    .row-action {
      width: 2.5rem;
      height: 2.5rem;
    }

    .pagination {
      padding-left: 1.15rem;
      padding-right: 1.15rem;
    }
  }

  @media (min-width: 1280px) {
    .log-head,
    .row {
      grid-template-columns: 8rem minmax(0, 1.1fr) minmax(0, 0.95fr) 6rem minmax(0, 0.8fr) 10.5rem minmax(0, 1.2fr) 4.8rem;
    }

    .col-notes-head {
      display: block;
    }

    .row-notes {
      grid-column: 7;
      align-self: center;
      margin: 0;
      padding-top: 0;
      border-top: 0;
      font-size: 0.95rem;
    }

    .col-actions {
      grid-column: 8;
    }
  }

  @media (prefers-reduced-motion: reduce) {
    .row.just-added,
    .sk {
      animation: none;
    }
  }
</style>
