<script lang="ts">
  import { onDestroy } from 'svelte';
  import { Calculator, Info, TriangleAlert, X } from 'lucide-svelte';
  import { api } from '$lib/api';
  import { featureFlags } from '$lib/features';
  import { formatNumber } from '$lib/format';
  import { clientSession, hasModuleAccess } from '$lib/session';
  import { toast } from '$lib/toast';
  import type {
    MixCalculatorCreateInput,
    MixCalculatorOptions,
    MixCalculatorPreview,
    MixCalculatorSession
  } from '$lib/types';
  import MixCalculatorResultsPanel from './MixCalculatorResultsPanel.svelte';

  let { options, initialSession = null }: { options: MixCalculatorOptions; initialSession?: MixCalculatorSession | null } = $props();

  const todayIso = new Date().toISOString().slice(0, 10);

  function initialClientNameValue() {
    return initialSession?.client_name ?? '';
  }

  function initialProductIdValue() {
    return initialSession?.product_id ?? 0;
  }

  function initialMixDateValue() {
    return initialSession?.mix_date ?? todayIso;
  }

  function initialBatchSizeValue() {
    return initialSession ? `${initialSession.batch_size_kg}` : '';
  }

  function initialPreparedByNameValue() {
    return initialSession?.prepared_by_name ?? '';
  }

  function initialNotesValue() {
    return initialSession?.notes ?? '';
  }

  function initialPreviewValue() {
    return initialSession;
  }

  let clientName = $state(initialClientNameValue());
  let productId = $state(initialProductIdValue());
  let mixDate = $state(initialMixDateValue());
  let batchSizeKg = $state(initialBatchSizeValue());
  let preparedByName = $state(initialPreparedByNameValue());
  let notes = $state(initialNotesValue());
  // Notes are optional and stay hidden behind "+ Add a note" until needed,
  // matching the throughput composer. Auto-open when a saved session has one.
  let showNote = $state(Boolean(initialSession?.notes));
  let preview = $state<MixCalculatorPreview | MixCalculatorSession | null>(initialPreviewValue());
  let formError = $state('');
  let formHint = $state('Select a mix date and prepared by name, then choose a client to unlock mixes.');
  let previewLoading = $state(false);
  let printPdfUrl = $state<string | null>(null);
  let printFrame = $state<HTMLIFrameElement | null>(null);
  let printAfterPdfLoad = $state(false);

  const canEdit = $derived(hasModuleAccess($clientSession, 'mix_calculator', 'edit'));
  const availableClients = $derived(
    Array.from(new Set([...(options.clients ?? []), ...(initialSession ? [initialSession.client_name] : [])]))
  );
  const availableProducts = $derived(
    initialSession && !options.products.some((product) => product.product_id === initialSession.product_id)
      ? [
          ...options.products,
          {
            product_id: initialSession.product_id,
            client_name: initialSession.client_name,
            product_name: initialSession.product_name,
            mix_id: initialSession.mix_id,
            mix_name: initialSession.mix_name,
            unit_of_measure: initialSession.product_unit_of_measure,
            unit_size_kg: initialSession.product_unit_size_kg,
            mix_total_kg: initialSession.total_kg
          }
        ]
      : options.products
  );
  const filteredProducts = $derived(availableProducts.filter((product) => product.client_name === clientName));
  const selectedProduct = $derived(filteredProducts.find((product) => product.product_id === productId) ?? null);

  $effect(() => {
    if (!filteredProducts.some((product) => product.product_id === productId)) {
      productId = 0;
    }
  });

  $effect(() => {
    if (!preparedByName && $clientSession?.name) {
      preparedByName = $clientSession.name;
    }
  });

  function buildPayload(): MixCalculatorCreateInput | null {
    formError = '';
    formHint = '';

    const numericBatchSize = Number(batchSizeKg);
    if (!mixDate) {
      formError = 'Select a mix date.';
      formHint = 'Choose the production date before calculating the mix.';
      return null;
    }
    if (!preparedByName.trim()) {
      formError = 'Enter the prepared by name.';
      formHint = 'Record the operator or staff member responsible for this mix.';
      return null;
    }
    if (!clientName) {
      formError = 'Select a client to unlock matching mixes.';
      formHint = 'Mixes stay disabled until a client is selected.';
      return null;
    }
    if (!productId) {
      formError = 'Select a mix.';
      formHint = 'Pick one of the mixes available for the selected client.';
      return null;
    }
    if (!Number.isFinite(numericBatchSize) || numericBatchSize <= 0) {
      formError = 'Enter a batch size greater than zero.';
      formHint = 'Batch size must be a positive number before the mix can be calculated.';
      return null;
    }

    return {
      mix_date: mixDate,
      client_name: clientName,
      product_id: productId,
      batch_size_kg: numericBatchSize,
      prepared_by_name: preparedByName.trim(),
      status: initialSession?.status ?? 'saved',
      notes: notes.trim() || null
    };
  }

  async function calculatePreview() {
    const payload = buildPayload();
    if (!payload) {
      toast.error(formError);
      return;
    }

    previewLoading = true;
    const tid = toast.loading('Calculating…');
    try {
      preview = await api.previewMixCalculatorSession(payload);
      toast.dismiss(tid);
    } catch (error) {
      toast.dismiss(tid);
      toast.error(error instanceof Error ? error.message : 'Unable to calculate the mix session.');
      formError = error instanceof Error ? error.message : 'Unable to calculate the mix session.';
    } finally {
      previewLoading = false;
    }
  }

  // Collapse the note field again, discarding anything typed.
  function dismissNote() {
    notes = '';
    showNote = false;
  }

  function clearForm() {
    clientName = '';
    productId = 0;
    mixDate = todayIso;
    batchSizeKg = '';
    preparedByName = $clientSession?.name ?? '';
    notes = '';
    showNote = false;
    preview = null;
    formError = '';
    formHint = 'Select a mix date and prepared by name, then choose a client to unlock mixes.';
  }

  $effect(() => {
    if (!clientName) {
      formHint = 'Select a client to unlock the mix list.';
      return;
    }

    if (!filteredProducts.length) {
      formHint = `No mixes are available for ${clientName}.`;
      return;
    }

    if (!productId) {
      formHint = 'Select a mix for the chosen client.';
      return;
    }

    formHint = `Ready to calculate ${selectedProduct?.product_name ?? 'the selected mix'}.`;
  });

  async function downloadPdf() {
    const tid = toast.loading('Generating PDF…');
    try {
      const payload = buildPayload();
      if (!payload) {
        toast.dismiss(tid);
        toast.error(formError || 'Complete the mix details first.');
        return;
      }

      const blob = await api.previewMixCalculatorPdf(payload);
      const url = URL.createObjectURL(blob);
      const anchor = document.createElement('a');
      anchor.href = url;
      anchor.download = `mix_calculator_${payload.client_name}_${payload.mix_date}.pdf`.replace(/[^\w.-]+/g, '_');
      document.body.appendChild(anchor);
      anchor.click();
      anchor.remove();
      URL.revokeObjectURL(url);
      toast.dismiss(tid);
    } catch (error) {
      toast.dismiss(tid);
      toast.error(error instanceof Error ? error.message : 'Unable to generate PDF.');
    }
  }

  function revokePrintPdfUrl() {
    if (printPdfUrl) {
      URL.revokeObjectURL(printPdfUrl);
      printPdfUrl = null;
    }
  }

  async function printCurrent() {
    if (!preview) {
      toast.error('Calculate the mix before printing.');
      return;
    }

    const payload = buildPayload();
    if (!payload) {
      toast.error(formError || 'Complete the mix details first.');
      return;
    }

    const tid = toast.loading('Preparing print...');
    try {
      const blob = initialSession ? await api.mixCalculatorSessionPdf(initialSession.id) : await api.previewMixCalculatorPdf(payload);
      revokePrintPdfUrl();
      printAfterPdfLoad = true;
      printPdfUrl = URL.createObjectURL(blob);
      toast.dismiss(tid);
    } catch (error) {
      toast.dismiss(tid);
      toast.error(error instanceof Error ? error.message : 'Unable to prepare the PDF for printing.');
    }
  }

  function printLoadedPdf() {
    printFrame?.contentWindow?.focus();
    printFrame?.contentWindow?.print();
  }

  function handlePrintFrameLoad() {
    if (printAfterPdfLoad) {
      printAfterPdfLoad = false;
      requestAnimationFrame(printLoadedPdf);
    }
  }

  onDestroy(() => {
    revokePrintPdfUrl();
  });
</script>

{#if !canEdit && !initialSession}
  <section class="locked-card">
    <p class="eyebrow">Mix Calculator</p>
    <h2>Edit access is required to create a new session.</h2>
    <p>View-only users can open saved sessions from history, but cannot create or update production calculations.</p>
    {#if featureFlags.mixCalculatorSessionHistory}
      <a class="secondary-button" href="/mix-calculator">Back to session history</a>
    {/if}
  </section>
{:else}
  {#if featureFlags.mixCalculatorSessionHistory || initialSession}
    <section class="page-actions">
      {#if featureFlags.mixCalculatorSessionHistory}
        <a class="secondary-button" href="/mix-calculator">Session history</a>
      {/if}
      {#if initialSession}
        <a class="primary-button" href={`/mix-calculator/${initialSession.id}/print`}>Print</a>
        <button class="secondary-button" type="button" onclick={downloadPdf}>Download PDF</button>
      {/if}
    </section>
  {/if}

  <section class="editor-grid">
    <article class="composer">
      <div class="composer-head">
        <div class="composer-title">
          <span class="composer-icon"><Calculator size={18} strokeWidth={2.2} /></span>
          <h2>Mix calculator</h2>
        </div>
        {#if selectedProduct}
          <div class="product-pill">
            <strong>{selectedProduct.unit_size_kg}kg</strong>
            <span>{selectedProduct.unit_of_measure}</span>
          </div>
        {/if}
      </div>

      <div class="composer-body">
      {#if formError}
        <p class="message error"><TriangleAlert size={16} strokeWidth={2.2} /> <span>{formError}</span></p>
      {/if}

      {#if !formError && formHint}
        <p class="message hint"><Info size={16} strokeWidth={2.2} /> <span>{formHint}</span></p>
      {/if}

      <div class="field-grid">
        <label>
          <span>Mix date</span>
          <input bind:value={mixDate} disabled={!canEdit} type="date" />
        </label>

        <label>
          <span>Prepared by</span>
          <input bind:value={preparedByName} disabled={!canEdit} placeholder="Staff name" type="text" />
        </label>

        <label>
          <span>Client</span>
          <select bind:value={clientName} disabled={!canEdit} title="Select a client to unlock matching mixes.">
            <option value="">Select a client</option>
            {#each availableClients as client}
              <option value={client}>{client}</option>
            {/each}
          </select>
        </label>

        <label>
          <span>Mix Name</span>
          <select
            bind:value={productId}
            disabled={!canEdit || !clientName || !filteredProducts.length}
            title={!clientName ? 'Select a client first.' : !filteredProducts.length ? 'No mixes are available for the selected client.' : 'Select a mix.'}
          >
            <option value={0}>Select a mix</option>
            {#each filteredProducts as product}
              <option value={product.product_id}>
                {product.product_name}
              </option>
            {/each}
          </select>
        </label>

        <label>
          <span>Batch size (kg)</span>
          <input bind:value={batchSizeKg} disabled={!canEdit} inputmode="decimal" min="0" placeholder="Batch size" type="number" />
        </label>
      </div>

      <div class="note-area">
        {#if showNote}
          <div class="note-field">
            <textarea
              class="note-input"
              bind:value={notes}
              disabled={!canEdit}
              placeholder="Note (optional) — production notes or shift context"
              rows="3"
            ></textarea>
            {#if canEdit}
              <button type="button" class="note-dismiss" title="Remove note" aria-label="Remove note" onclick={dismissNote}>
                <X size={16} strokeWidth={2.4} />
              </button>
            {/if}
          </div>
        {:else if canEdit}
          <button type="button" class="link-button" onclick={() => (showNote = true)}>+ Add a note</button>
        {/if}
      </div>

      {#if canEdit && selectedProduct}
        <div class="calculation-note">
          <strong>Formula source</strong>
          <span>{selectedProduct.product_name} totals {formatNumber(selectedProduct.mix_total_kg, 2)}kg. Scale factor = batch size / source formula total.</span>
        </div>
      {/if}

      {#if canEdit}
        <div class="action-row">
          <button class="primary-button" disabled={previewLoading} type="button" onclick={calculatePreview}>
            <span class="button-icon" style="--button-icon-url: url('/icons/calculator.svg');" aria-hidden="true"></span>
            <span>{previewLoading ? 'Calculating...' : 'Calculate mix'}</span>
          </button>

          <button class="secondary-button" disabled={previewLoading} type="button" onclick={clearForm}>
            <span class="button-icon" style="--button-icon-url: url('/icons/trash.svg');" aria-hidden="true"></span>
            <span>Clear</span>
          </button>
        </div>
      {/if}
      </div>
    </article>

    <MixCalculatorResultsPanel
      preview={preview}
      sessionNumber={initialSession?.session_number ?? null}
      onPrint={preview ? printCurrent : null}
      onDownloadPdf={preview ? downloadPdf : null}
    />
  </section>

  {#if printPdfUrl}
    <iframe
      bind:this={printFrame}
      class="print-pdf-frame"
      src={printPdfUrl}
      title="Mix calculator PDF print frame"
      onload={handlePrintFrameLoad}
    ></iframe>
  {/if}
{/if}

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

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

  .page-actions,
  .editor-grid {
    margin-bottom: 1.2rem;
  }

  .page-actions {
    display: flex;
    justify-content: flex-end;
    gap: 0.75rem;
    flex-wrap: wrap;
  }

  .calculation-note span {
    color: var(--color-text-secondary);
  }

  .action-row {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    flex-wrap: wrap;
  }

  .editor-grid {
    display: grid;
    grid-template-columns: minmax(0, 0.95fr) minmax(0, 1.05fr);
    gap: 1rem;
  }

  /* The composer mirrors the throughput "Add a packing run" surface: a quiet
     brand-tinted gradient panel that reads as a distinct, on-brand workspace.
     Theme tokens keep it correct in dark mode. */
  .composer {
    border: 1px solid color-mix(in srgb, var(--color-brand) 16%, var(--color-border));
    border-radius: 0.9rem;
    background: linear-gradient(
      180deg,
      color-mix(in srgb, var(--color-brand) 7%, var(--color-bg-surface)),
      color-mix(in srgb, var(--color-brand) 4%, var(--color-bg-surface))
    );
    /* Native selects open within the viewport, so the card can stay open for
       a clean rounded edge without clipping anything. */
    overflow: visible;
  }

  .composer-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem 1.4rem;
    flex-wrap: wrap;
    padding: 1.3rem 1.45rem 1.05rem;
  }

  .composer-title {
    display: inline-flex;
    align-items: center;
    gap: 0.6rem;
  }

  /* Brand-tinted badge echoing the throughput overview's section icon. */
  .composer-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    width: 2rem;
    height: 2rem;
    border-radius: 0.5rem;
    background: var(--color-brand-tint);
    color: var(--color-brand);
  }

  .composer-title h2 {
    margin: 0;
    font-size: clamp(1.25rem, 2vw, 1.7rem);
    line-height: 1.05;
    letter-spacing: -0.03em;
    color: var(--color-text-primary);
  }

  .composer-body {
    padding: 0 1.45rem 1.4rem;
  }

  .locked-card {
    max-width: 42rem;
    padding: 1.2rem;
    border: 1px solid var(--color-border);
    border-radius: var(--radius-panel);
    background: var(--color-bg-surface);
  }

  .locked-card h2 {
    margin: 0.35rem 0 0.45rem;
    font-size: clamp(1.7rem, 3vw, 2.1rem);
  }

  /* Quick brand-tinted chip echoing the selected mix's unit, matching the pill
     language used across the app. */
  .product-pill {
    display: inline-flex;
    align-items: baseline;
    gap: 0.4rem;
    padding: 0.4rem 0.78rem;
    border: 1px solid color-mix(in srgb, var(--color-brand) 18%, var(--color-border));
    border-radius: 999px;
    background: var(--color-brand-tint);
    color: var(--color-success-text);
  }

  .product-pill strong {
    font-size: 0.95rem;
  }

  .product-pill span {
    font-size: 0.76rem;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    opacity: 0.85;
  }

  .field-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 0.9rem;
  }

  .field-grid label {
    display: grid;
    gap: 0.38rem;
  }

  .field-grid label span {
    font-size: 0.88rem;
    font-weight: 600;
  }

  /* Optional note, revealed by "+ Add a note" — mirrors the throughput composer. */
  .note-area {
    margin-top: 0.9rem;
  }

  .link-button {
    padding: 0.25rem 0;
    background: none;
    border: 0;
    color: var(--color-brand);
    font-size: 0.95rem;
    font-weight: 600;
    cursor: pointer;
  }

  .link-button:hover {
    text-decoration: underline;
  }

  .note-field {
    display: flex;
    align-items: flex-start;
    gap: 0.45rem;
  }

  .note-input {
    flex: 1 1 auto;
    min-width: 0;
  }

  .note-dismiss {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    width: 48px;
    height: 48px;
    padding: 0;
    border: 1px solid color-mix(in srgb, var(--color-brand) 14%, var(--color-border));
    border-radius: 0.8rem;
    background: var(--color-bg-surface);
    color: var(--color-text-secondary);
    cursor: pointer;
    transition:
      border-color 140ms ease,
      color 140ms ease,
      background-color 140ms ease;
  }

  .note-dismiss:hover {
    border-color: var(--color-text-muted);
    color: var(--color-text-primary);
    background: var(--color-bg-app);
  }

  .note-dismiss:focus-visible {
    outline: 3px solid var(--color-brand);
    outline-offset: 2px;
  }

  /* White fields on the green tint, with brand-tinted borders and a 48px touch
     target — the same input language as the throughput composer. */
  .composer input,
  .composer select,
  .composer textarea {
    width: 100%;
    min-height: 48px;
    padding: 0.62rem 0.78rem;
    border: 1px solid color-mix(in srgb, var(--color-brand) 14%, var(--color-border));
    border-radius: 0.8rem;
    font-size: 0.98rem;
    background: var(--color-bg-surface);
    color: var(--color-text-primary);
    transition:
      border-color 160ms ease,
      box-shadow 160ms ease;
  }

  .composer input::placeholder,
  .composer textarea::placeholder {
    color: var(--color-text-muted);
    opacity: 1;
  }

  .composer input:focus-visible,
  .composer select:focus-visible,
  .composer textarea:focus-visible {
    outline: 3px solid var(--color-brand);
    outline-offset: 1px;
    border-color: var(--color-brand);
  }

  .composer textarea {
    min-height: 6.5rem;
    resize: vertical;
  }

  /* The Mix Name select stays locked until a client is chosen; make that state
     unmistakable rather than looking like an empty, clickable field. */
  .composer input:disabled,
  .composer select:disabled,
  .composer textarea:disabled {
    background: color-mix(in srgb, var(--color-bg-app) 70%, var(--color-bg-surface));
    border-color: var(--color-border);
    color: var(--color-text-muted);
    cursor: not-allowed;
  }

  .calculation-note {
    display: grid;
    gap: 0.2rem;
    margin-top: 1rem;
    padding: 0.92rem;
    border: 1px solid var(--color-border);
    border-radius: var(--radius-row);
    background: var(--color-bg-app);
  }

  .message {
    display: flex;
    align-items: center;
    gap: 0.55rem;
    margin-bottom: 0.85rem;
    padding: 0.72rem 0.9rem;
    border-radius: 0.7rem;
    font-size: 0.92rem;
    font-weight: 500;
  }

  .message :global(svg) {
    flex-shrink: 0;
  }

  .message.error {
    background: color-mix(in srgb, var(--color-error) 12%, var(--color-bg-surface));
    color: var(--color-error);
    border: 1px solid color-mix(in srgb, var(--color-error) 30%, transparent);
  }

  /* Readable on-brand hint: a white-ish surface with a green info icon, instead
     of low-contrast grey that washed out against the composer's tint. */
  .message.hint {
    background: color-mix(in srgb, var(--color-brand) 16%, var(--color-bg-app));
    color: var(--color-text-primary);
    border: 1px solid color-mix(in srgb, var(--color-brand) 26%, var(--color-border));
  }

  .message.hint :global(svg) {
    color: var(--color-brand);
  }

  .action-row {
    margin-top: 1rem;
  }

  .primary-button,
  .secondary-button {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    padding: 0.78rem 0.96rem;
    border-radius: var(--radius-control);
    border: 1px solid var(--color-border);
    font-weight: 600;
    cursor: pointer;
    transition:
      background-color 160ms ease,
      border-color 160ms ease;
  }

  .primary-button {
    border: none;
    background: var(--color-brand);
    color: var(--color-on-brand);
  }

  /* Composer buttons take the throughput composer's chunkier 48px shape. */
  .composer .action-row .primary-button,
  .composer .action-row .secondary-button {
    min-height: 48px;
    padding: 0.62rem 1.28rem;
    border-radius: 0.8rem;
    font-weight: 700;
  }

  .secondary-button {
    background: var(--color-bg-surface);
    color: var(--color-text-primary);
  }

  .primary-button:hover:not(:disabled) {
    background: var(--color-brand-hover);
  }

  .primary-button:active:not(:disabled) {
    background: var(--color-brand-hover);
  }

  .secondary-button:hover:not(:disabled) {
    border-color: var(--color-text-muted);
    background: var(--color-bg-app);
  }

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

  .button-icon {
    display: inline-block;
    width: 1rem;
    height: 1rem;
    background-color: currentColor;
    -webkit-mask: var(--button-icon-url) center / contain no-repeat;
    mask: var(--button-icon-url) center / contain no-repeat;
    flex-shrink: 0;
  }

  button:disabled {
    cursor: wait;
    opacity: 0.7;
  }

  @media (max-width: 980px) {
    .editor-grid {
      grid-template-columns: 1fr;
    }
  }

  @media (max-width: 720px) {
    .field-grid {
      grid-template-columns: 1fr;
    }
  }

  .print-pdf-frame {
    position: fixed;
    right: 0;
    bottom: 0;
    width: 1px;
    height: 1px;
    border: 0;
    opacity: 0;
    pointer-events: none;
  }
</style>
