// SamplesScreen — Persian form for logging count of received samples per product.

const { useState: useStateS, useMemo: useMemoS, useEffect: useEffectS } = React;

const faNumS = (n) => String(n).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);

// The sample product catalogue is defined by the admin and arrives via the
// app store (window.useAppStore().products) — no longer hard-coded here.

function Stepper({ value, onChange, max = 999 }) {
  const btn = (label, action, disabled) => (
    <button
      onClick={action}
      disabled={disabled}
      style={{
        all: 'unset', cursor: disabled ? 'not-allowed' : 'pointer',
        width: 32, height: 32, borderRadius: 10,
        background: disabled ? 'var(--icon-bg)' : 'var(--surface)',
        border: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 16, fontWeight: 700,
        color: disabled ? 'var(--muted)' : 'var(--ink)',
        userSelect: 'none',
        transition: 'background 140ms ease',
      }}>{label}</button>
  );
  const empty = value === 0;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 6,
      background: empty ? 'transparent' : 'color-mix(in oklab, var(--accent) 8%, transparent)',
      padding: empty ? 0 : '3px 6px',
      borderRadius: 14,
      transition: 'background 200ms ease',
    }}>
      {btn('−', () => onChange(Math.max(0, value - 1)), value === 0)}
      <div style={{
        minWidth: 36, textAlign: 'center',
        fontSize: 16, fontWeight: 700,
        fontFamily: 'JetBrains Mono, ui-monospace, monospace',
        fontVariantNumeric: 'tabular-nums',
        color: empty ? 'var(--muted)' : 'var(--ink)',
      }}>{faNumS(value)}</div>
      {btn('+', () => onChange(Math.min(max, value + 1)), value >= max)}
    </div>
  );
}

function ProductRow({ product, count, onChange }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 14px',
      borderTop: '1px solid var(--border)',
    }}>
      {/* product thumb placeholder */}
      <div style={{
        width: 44, height: 44, borderRadius: 12,
        background: 'var(--icon-bg)',
        border: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 9, color: 'var(--muted)',
        fontFamily: 'JetBrains Mono, ui-monospace, monospace',
        letterSpacing: '0.04em',
        flexShrink: 0,
      }}>{product.code}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 13.5, fontWeight: 600, color: 'var(--ink)',
          marginBottom: 2,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{product.name}</div>
        <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{product.spec}</div>
      </div>
      <Stepper value={count} onChange={onChange} />
    </div>
  );
}

function SamplesScreen({ onBack, onSubmit }) {
  const store = window.useAppStore();
  const products = store.products || [];
  const [counts, setCounts] = useStateS({}); // productId -> qty
  const [submitted, setSubmitted] = useStateS(false);
  const [storeId, setStoreId] = useStateS(null);
  const [pickerOpen, setPickerOpen] = useStateS(false);

  // Stores assigned to the current user (unique across all scheduled days).
  const assignedStores = useMemoS(() => {
    const byDay = store.assignments[store.currentUserId] || {};
    const seen = new Set();
    const list = [];
    Object.values(byDay).forEach(day => day.forEach(a => {
      if (seen.has(a.storeId)) return;
      const s = store.stores.find(x => x.id === a.storeId);
      if (s) { seen.add(a.storeId); list.push(s); }
    }));
    return list;
  }, [store.assignments, store.stores, store.currentUserId]);

  // Default to the first assigned store once data is available.
  useEffectS(() => {
    if (storeId == null && assignedStores.length > 0) {
      setStoreId(assignedStores[0].id);
    }
  }, [assignedStores, storeId]);

  const selectedStore = assignedStores.find(s => s.id === storeId) || null;

  const total = useMemoS(
    () => products.reduce((a, p) => a + (counts[p.id] || 0), 0),
    [counts, products]
  );
  const distinct = useMemoS(
    () => products.filter(p => (counts[p.id] || 0) > 0).length,
    [counts, products]
  );

  const setOne = (id, v) => setCounts(c => ({ ...c, [id]: v }));

  const canSubmit = total > 0 && !!selectedStore;

  const handleSubmit = () => {
    if (!canSubmit) return;
    setSubmitted(true);
    setTimeout(() => {
      onSubmit?.(counts, total, selectedStore.id);
    }, 700);
  };

  return (
    <div style={{
      direction: 'rtl', background: 'var(--bg)',
      height: '100%',
      fontFamily: 'Vazirmatn, system-ui, sans-serif', color: 'var(--ink)',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      {/* header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 18px 8px',
        flexShrink: 0,
      }}>
        <button onClick={onBack} style={{
          all: 'unset', cursor: 'pointer',
          width: 38, height: 38, borderRadius: 99,
          background: 'var(--surface)', border: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--ink)',
        }}>
          <window.IconChevron size={16} dir="right" />
        </button>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 15, fontWeight: 700 }}>ثبت سمپل دریافتی</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>تعداد هر محصول را وارد کنید</div>
        </div>
        <div style={{ width: 38 }} />
      </div>

      {/* scrollable content */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 18px 14px' }}>
        {/* meta info card */}
        <div style={{
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 14, padding: '12px 14px',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          marginBottom: 14, gap: 8,
        }}>
          <div style={{ flexShrink: 0 }}>
            <div style={{ fontSize: 10.5, color: 'var(--muted)', marginBottom: 3 }}>تاریخ دریافت</div>
            <div style={{ fontSize: 13, fontWeight: 600 }}>۲ خرداد ۱۴۰۵</div>
          </div>
          <div style={{ width: 1, height: 28, background: 'var(--border)', flexShrink: 0 }} />
          {/* محل دریافت — selectable from the user's assigned stores */}
          <div style={{ flex: 1, minWidth: 0, position: 'relative' }}>
            <div style={{ fontSize: 10.5, color: 'var(--muted)', marginBottom: 3 }}>محل دریافت</div>
            <button
              onClick={() => assignedStores.length > 0 && setPickerOpen(o => !o)}
              disabled={assignedStores.length === 0}
              style={{
                all: 'unset',
                cursor: assignedStores.length === 0 ? 'default' : 'pointer',
                display: 'flex', alignItems: 'center', gap: 5,
                fontSize: 13, fontWeight: 600,
                color: selectedStore ? 'var(--ink)' : 'var(--muted)',
                maxWidth: '100%',
              }}>
              <span style={{
                overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              }}>
                {selectedStore ? selectedStore.name
                  : assignedStores.length === 0 ? 'فروشگاهی اختصاص نیافته' : 'انتخاب کنید'}
              </span>
              {assignedStores.length > 0 && (
                <span style={{
                  flexShrink: 0, color: 'var(--muted)', fontSize: 9,
                  transform: pickerOpen ? 'rotate(180deg)' : 'none',
                  transition: 'transform 160ms ease',
                }}>▼</span>
              )}
            </button>

            {pickerOpen && (
              <>
                <div
                  onClick={() => setPickerOpen(false)}
                  style={{ position: 'fixed', inset: 0, zIndex: 20 }}
                />
                <div style={{
                  position: 'absolute', top: '100%', insetInlineStart: 0,
                  marginTop: 6, minWidth: 180, maxWidth: 240, maxHeight: 220,
                  overflowY: 'auto', zIndex: 21,
                  background: 'var(--surface)', border: '1px solid var(--border)',
                  borderRadius: 12, boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
                  padding: 4,
                }}>
                  {assignedStores.map(s => {
                    const active = s.id === storeId;
                    return (
                      <button
                        key={s.id}
                        onClick={() => { setStoreId(s.id); setPickerOpen(false); }}
                        style={{
                          all: 'unset', cursor: 'pointer', display: 'block',
                          width: '100%', boxSizing: 'border-box',
                          padding: '9px 10px', borderRadius: 9,
                          fontSize: 13, fontWeight: active ? 700 : 500,
                          color: active ? 'var(--accent)' : 'var(--ink)',
                          background: active
                            ? 'color-mix(in oklab, var(--accent) 10%, transparent)'
                            : 'transparent',
                        }}>
                        {s.name}
                      </button>
                    );
                  })}
                </div>
              </>
            )}
          </div>
          <div style={{ width: 1, height: 28, background: 'var(--border)', flexShrink: 0 }} />
          <div style={{ flexShrink: 0 }}>
            <div style={{ fontSize: 10.5, color: 'var(--muted)', marginBottom: 3 }}>کد سند</div>
            <div style={{
              fontSize: 13, fontWeight: 600,
              fontFamily: 'JetBrains Mono, ui-monospace, monospace',
              fontVariantNumeric: 'tabular-nums',
            }}>۴۸۲۷</div>
          </div>
        </div>

        <div style={{
          fontSize: 11, color: 'var(--muted)', letterSpacing: '0.04em',
          marginBottom: 8, fontWeight: 500,
          padding: '0 2px',
        }}>محصولات</div>

        <div style={{
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 16, overflow: 'hidden',
        }}>
          {products.length === 0 ? (
            <div style={{
              padding: '24px 14px', textAlign: 'center',
              fontSize: 12.5, color: 'var(--muted)',
            }}>هنوز محصولی توسط مدیر تعریف نشده است</div>
          ) : products.map((p, i) => (
            <div key={p.id} style={{ marginTop: i === 0 ? -1 : 0 }}>
              <ProductRow
                product={p}
                count={counts[p.id] || 0}
                onChange={(v) => setOne(p.id, v)}
              />
            </div>
          ))}
        </div>

        <div style={{ height: 8 }} />
      </div>

      {/* sticky footer */}
      <div style={{
        flexShrink: 0,
        padding: '12px 18px 16px',
        background: 'var(--bg)',
        borderTop: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>
            {faNumS(distinct)} قلم · جمع کل
          </div>
          <div style={{
            fontSize: 22, fontWeight: 700,
            fontFamily: 'JetBrains Mono, ui-monospace, monospace',
            fontVariantNumeric: 'tabular-nums',
            color: total > 0 ? 'var(--accent)' : 'var(--ink)',
            lineHeight: 1.1,
          }}>{faNumS(total)} <span style={{
            fontSize: 12, fontWeight: 500, color: 'var(--muted)',
            fontFamily: 'Vazirmatn, system-ui',
          }}>عدد</span></div>
        </div>
        <button
          disabled={!canSubmit || submitted}
          onClick={handleSubmit}
          style={{
            all: 'unset', cursor: !canSubmit ? 'not-allowed' : 'pointer',
            padding: '13px 22px', borderRadius: 14,
            background: submitted
              ? 'color-mix(in oklab, var(--accent) 75%, #000)'
              : !canSubmit ? 'var(--icon-bg)' : 'var(--accent)',
            color: !canSubmit ? 'var(--muted)' : '#fff',
            fontSize: 14, fontWeight: 700,
            transition: 'background 180ms ease',
            minWidth: 110, textAlign: 'center',
          }}>
          {submitted ? '✓ ثبت شد' : 'ثبت دریافتی'}
        </button>
      </div>
    </div>
  );
}

window.SamplesScreen = SamplesScreen;
