// @design-system: domain/TierEditor
/**
 * TierEditor — add/remove/reorder tier thresholds for deal creation.
 *
 * Each tier: participants (min count) + price (₪).
 * Validates:
 *  - Participant counts unique
 *  - Min 2 participants per tier
 *  - Price > 0
 *
 * Reorder via drag-and-drop (keyboard: move buttons for a11y).
 * Sorted ascending by participants on render.
 *
 * Tokens: `--color-brand-primary-*`, `--color-surface-raised`, `--color-border`,
 *          `--color-danger-*`, `--color-text-*`
 */

'use client';

import { useId } from 'react';
import { cn } from '@/lib/cn';
import { useT } from '@/lib/i18n/react';
import { Icon } from '@/components/ui/icons/Icon';
import { Button } from '@/components/ui/primitives/Button';
import { IconButton } from '@/components/ui/primitives/IconButton';

export interface TierThreshold {
  /** Stable row id for React keys (client-generated when missing). */
  id?: string;
  /** Minimum participant count. */
  participants: number;
  /** Price at this tier (₪). */
  price: number;
}

export interface TierEditorProps {
  /** Current tier list. */
  tiers: TierThreshold[];
  /** Called whenever tiers change. */
  onChange: (tiers: TierThreshold[]) => void;
  /** Optional price floor — lowest tier price must be ≥ this value. */
  priceFloor?: number;
  /** Extra class names. */
  className?: string;
}

/**
 * TierEditor
 *
 * Controlled component — caller owns the `tiers` state.
 */
export function TierEditor({ tiers, onChange, priceFloor, className }: TierEditorProps) {
  const t = useT('tier_editor');
  const baseId = useId();
  function resolveTierId(tier: TierThreshold, index: number): string {
    if (tier.id) return tier.id;
    return `${baseId}-tier-${index}`;
  }

  const sorted = [...tiers].sort((a, b) => a.participants - b.participants);

  function addTier() {
    const maxPart = sorted.length > 0 ? sorted[sorted.length - 1]!.participants : 0;
    const participants = maxPart + 10;
    const id = crypto.randomUUID();
    onChange([...sorted, { id, participants, price: 0 }]);
  }

  function removeTier(index: number) {
    const next = sorted.filter((_, i) => i !== index);
    onChange(next);
  }

  function updateTier(index: number, field: keyof TierThreshold, rawValue: string) {
    const num = parseFloat(rawValue);
    if (isNaN(num)) return;
    const next = sorted.map((t, i) =>
      i === index ? { ...t, [field]: field === 'participants' ? Math.floor(num) : num } : t,
    );
    onChange(next);
  }

  function moveTier(index: number, direction: 'up' | 'down') {
    const swapIdx = direction === 'up' ? index - 1 : index + 1;
    if (swapIdx < 0 || swapIdx >= sorted.length) return;
    const next = [...sorted];
    [next[index], next[swapIdx]] = [next[swapIdx]!, next[index]!];
    onChange(next);
  }

  const hasDuplicates = new Set(sorted.map((t) => t.participants)).size !== sorted.length;

  return (
    <div className={cn('flex flex-col gap-3', className)}>
      <div className="flex items-center justify-between">
        <h3 className="text-text-primary text-sm font-semibold">{t('title')}</h3>
        <Button
          variant="ghost"
          size="sm"
          onClick={addTier}
          iconStart={<Icon name="Plus" size="xs" />}
        >
          {t('add_tier')}
        </Button>
      </div>

      {sorted.length === 0 && <p className="text-text-muted py-2 text-xs">{t('add_tier')}</p>}

      <ul className="flex flex-col gap-2" aria-label={t('title')}>
        {sorted.map((tier, i) => {
          const tierId = resolveTierId(tier, i);
          const participantsId = `${baseId}-part-${tierId}`;
          const priceId = `${baseId}-price-${tierId}`;
          const isDup =
            hasDuplicates && sorted.filter((t) => t.participants === tier.participants).length > 1;
          const isPriceError = priceFloor != null && tier.price < priceFloor && tier.price > 0;

          return (
            <li
              key={tierId}
              className="bg-surface-raised border-border grid grid-cols-[1fr_1fr_auto_auto_auto] items-center gap-2 rounded-lg border p-3"
            >
              {/* Participants input */}
              <div className="flex flex-col gap-1">
                <label htmlFor={participantsId} className="text-text-muted text-xs">
                  {t('participants_label')}
                </label>
                <input
                  id={participantsId}
                  type="number"
                  min={2}
                  value={tier.participants}
                  onChange={(e) => updateTier(i, 'participants', e.target.value)}
                  className={cn(
                    'h-8 w-full rounded-md border px-2 text-sm font-[var(--font-en)] tabular-nums',
                    'bg-surface-base text-text-primary',
                    'focus-visible:ring-brand-primary-500 focus-visible:ring-2 focus-visible:outline-none',
                    isDup ? 'border-danger-400' : 'border-border',
                  )}
                  aria-describedby={isDup ? `${participantsId}-err` : undefined}
                />
                {isDup && (
                  <p id={`${participantsId}-err`} className="text-danger-600 text-xs">
                    {t('duplicate_error')}
                  </p>
                )}
              </div>

              {/* Price input */}
              <div className="flex flex-col gap-1">
                <label htmlFor={priceId} className="text-text-muted text-xs">
                  {t('price_label')}
                </label>
                <input
                  id={priceId}
                  type="number"
                  min={0}
                  step={0.01}
                  value={tier.price}
                  onChange={(e) => updateTier(i, 'price', e.target.value)}
                  className={cn(
                    'h-8 w-full rounded-md border px-2 text-sm font-[var(--font-en)] tabular-nums',
                    'bg-surface-base text-text-primary',
                    'focus-visible:ring-brand-primary-500 focus-visible:ring-2 focus-visible:outline-none',
                    isPriceError ? 'border-danger-400' : 'border-border',
                  )}
                  aria-describedby={isPriceError ? `${priceId}-err` : undefined}
                />
                {isPriceError && (
                  <p id={`${priceId}-err`} className="text-danger-600 text-xs">
                    {t('price_floor_error')}
                  </p>
                )}
              </div>

              {/* Move up */}
              <IconButton
                variant="ghost"
                size="sm"
                aria-label={`${t('drag_aria')} ${i + 1}`}
                onClick={() => moveTier(i, 'up')}
                disabled={i === 0}
              >
                <Icon name="ChevronUp" size="xs" aria-hidden />
              </IconButton>

              {/* Move down */}
              <IconButton
                variant="ghost"
                size="sm"
                aria-label={`${t('drag_aria')} ${i + 1}`}
                onClick={() => moveTier(i, 'down')}
                disabled={i === sorted.length - 1}
              >
                <Icon name="ChevronDown" size="xs" aria-hidden />
              </IconButton>

              {/* Remove */}
              <IconButton
                variant="ghost"
                size="sm"
                aria-label={t('remove_tier_aria')}
                onClick={() => removeTier(i)}
              >
                <Icon name="Trash2" size="xs" color="danger" aria-hidden />
              </IconButton>
            </li>
          );
        })}
      </ul>
    </div>
  );
}
