/**
 * QtyTierEditor — collapsible per-SKU quantity-discount tier editor.
 *
 * Used in both variants mode (SkuGrid, one per SKU row) and single mode
 * (VariantsStep, once for the whole deal).
 */
'use client';

import { useState } from 'react';
import { useT } from '@/lib/i18n/react';
import { NumberInput } from '@/components/ui/primitives/NumberInput';
import { Button } from '@/components/ui/primitives/Button';
import { IconButton } from '@/components/ui/primitives/IconButton';
import { Trash2, Plus, ChevronDown, ChevronUp } from 'lucide-react';
import { applyQtyTier } from '@/server/pricing/qty-tier';
import { formatAgorotPlain } from '@/lib/money';

export interface QtyTier {
  /** Stable row id for React keys (client-generated when missing). */
  id?: string;
  minQty: number;
  discountPercent: number;
}

export interface QtyTierEditorProps {
  /** Unique id suffix used to scope aria-* IDs. Pass SKU index for variants, 'single' for single mode. */
  panelId: string;
  /** The SKU's discounted price in ₪ (string). Used for live preview. */
  discountedPrice: string;
  tiers: QtyTier[];
  onChange: (tiers: QtyTier[]) => void;
}

// ─── Simple interpolation helper ─────────────────────────────────────────────

function interp(template: string, vars: Record<string, string | number>): string {
  return Object.entries(vars).reduce((s, [k, v]) => s.replaceAll(`{${k}}`, String(v)), template);
}

// ─── Component ───────────────────────────────────────────────────────────────

export function QtyTierEditor({ panelId, discountedPrice, tiers, onChange }: QtyTierEditorProps) {
  const t = useT('variants');
  const [open, setOpen] = useState(false);
  function resolveTierId(tier: QtyTier, index: number): string {
    if (tier.id) return tier.id;
    return `qty-tier-${panelId}-${index}`;
  }

  const skuUnitAgorot = Math.round(Number(discountedPrice) * 100) || 0;

  function addTier() {
    if (tiers.length >= 5) return;
    const lastMinQty = tiers[tiers.length - 1]?.minQty ?? 1;
    const lastPercent = tiers[tiers.length - 1]?.discountPercent ?? 0;
    const minQty = lastMinQty + 1;
    const id = crypto.randomUUID();
    onChange([...tiers, { id, minQty, discountPercent: Math.min(lastPercent + 5, 100) }]);
  }

  function removeTier(i: number) {
    onChange(tiers.filter((_, idx) => idx !== i));
  }

  function updateTier(i: number, patch: Partial<QtyTier>) {
    onChange(tiers.map((row, idx) => (idx === i ? { ...row, ...patch } : row)));
  }

  function minQtyError(i: number): string | null {
    const row = tiers[i];
    if (!row) return null;
    if (row.minQty < 2) return t('qty_tier_err_min_qty');
    if (i > 0 && tiers[i - 1] && row.minQty <= (tiers[i - 1]?.minQty ?? 0))
      return t('qty_tier_err_min_qty');
    return null;
  }

  function percentError(i: number): string | null {
    const row = tiers[i];
    if (!row) return null;
    if (i > 0 && tiers[i - 1] && row.discountPercent <= (tiers[i - 1]?.discountPercent ?? 0))
      return t('qty_tier_err_percent');
    return null;
  }

  return (
    <div className="mt-2 rounded-lg border border-dashed border-neutral-300 bg-neutral-50 p-3">
      <Button
        type="button"
        variant="ghost"
        size="sm"
        className="flex w-full items-center justify-between text-start font-semibold text-neutral-700"
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
        aria-controls={`qty-tier-panel-${panelId}`}
        iconEnd={
          open ? (
            <ChevronUp size={16} className="text-neutral-500" />
          ) : (
            <ChevronDown size={16} className="text-neutral-500" />
          )
        }
      >
        {t('qty_tier_heading')}
      </Button>

      {open && (
        <div id={`qty-tier-panel-${panelId}`} className="mt-3 space-y-3">
          <p className="text-xs text-neutral-500">{t('qty_tier_hint')}</p>

          {tiers.length === 0 && (
            <>
              <p className="text-text-muted text-xs">{t('qty_tier_empty')}</p>
              <p className="text-text-muted text-xs">{t('qty_tier_add_row')}</p>
            </>
          )}

          {tiers.map((tier, i) => {
            const tierId = resolveTierId(tier, i);
            const preview =
              skuUnitAgorot > 0
                ? (() => {
                    const { effectiveUnitAgorot } = applyQtyTier(skuUnitAgorot, tier.minQty, [
                      { minQty: tier.minQty, discountPercent: tier.discountPercent },
                    ]);
                    return interp(t('qty_tier_preview'), {
                      minQty: tier.minQty,
                      unit: formatAgorotPlain(effectiveUnitAgorot),
                      percent: tier.discountPercent,
                    });
                  })()
                : null;

            const mqErr = minQtyError(i);
            const pctErr = percentError(i);

            return (
              <div key={tierId} className="flex flex-wrap items-end gap-2">
                {/* Min quantity */}
                <div className="flex flex-col gap-1">
                  <label
                    htmlFor={`qty-tier-minqty-${panelId}-${tierId}`}
                    className="text-text-muted text-xs font-medium"
                  >
                    {t('qty_tier_min_qty_label')}
                  </label>
                  <NumberInput
                    id={`qty-tier-minqty-${panelId}-${tierId}`}
                    min={2}
                    value={tier.minQty}
                    className="w-20"
                    onChange={(n) => updateTier(i, { minQty: n || 2 })}
                    aria-invalid={!!mqErr}
                    aria-describedby={
                      mqErr ? `qty-tier-minqty-err-${panelId}-${tierId}` : undefined
                    }
                  />
                  {mqErr && (
                    <span
                      id={`qty-tier-minqty-err-${panelId}-${tierId}`}
                      role="alert"
                      className="text-xs text-red-600"
                    >
                      {mqErr}
                    </span>
                  )}
                </div>

                {/* Discount percent */}
                <div className="flex flex-col gap-1">
                  <label
                    htmlFor={`qty-tier-pct-${panelId}-${tierId}`}
                    className="text-text-muted text-xs font-medium"
                  >
                    {t('qty_tier_percent_label')}
                  </label>
                  <NumberInput
                    id={`qty-tier-pct-${panelId}-${tierId}`}
                    min={1}
                    max={100}
                    value={tier.discountPercent}
                    className="w-20"
                    onChange={(n) => updateTier(i, { discountPercent: n || 1 })}
                    aria-invalid={!!pctErr}
                    aria-describedby={pctErr ? `qty-tier-pct-err-${panelId}-${tierId}` : undefined}
                  />
                  {pctErr && (
                    <span
                      id={`qty-tier-pct-err-${panelId}-${tierId}`}
                      role="alert"
                      className="text-xs text-red-600"
                    >
                      {pctErr}
                    </span>
                  )}
                </div>

                {/* Remove */}
                <IconButton
                  variant="ghost"
                  size="sm"
                  aria-label={t('qty_tier_remove_row')}
                  onClick={() => removeTier(i)}
                >
                  <Trash2 size={14} />
                </IconButton>

                {/* Live preview */}
                {preview && (
                  <span className="self-center text-xs text-neutral-500 italic">{preview}</span>
                )}
              </div>
            );
          })}

          {tiers.length >= 5 && (
            <p className="text-xs text-amber-600">{t('qty_tier_err_max_rows')}</p>
          )}

          <Button
            type="button"
            variant="ghost"
            size="sm"
            disabled={tiers.length >= 5}
            iconStart={<Plus size={14} />}
            onClick={addTier}
          >
            {t('qty_tier_add_row')}
          </Button>
        </div>
      )}
    </div>
  );
}
