/**
 * VariantsStep — pricing/variants section of the vendor add-deal form.
 *
 * Mode "single": flat price + qty (mirrors legacy single-SKU deal).
 * Mode "variants": 1-3 axes, each with kind + names + options → auto-expand SKU grid.
 */
'use client';

import { useState } from 'react';
import { Controller, useWatch, type UseFormReturn } from 'react-hook-form';
import { useT } from '@/lib/i18n/react';
import { FormField } from '@/components/ui/primitives/FormField';
import { Input } from '@/components/ui/primitives/Input';
import { NumberInput } from '@/components/ui/primitives/NumberInput';
import { RadioGroup, RadioItem } from '@/components/ui/primitives/RadioGroup';
import { Button } from '@/components/ui/primitives/Button';
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogAction,
  AlertDialogCancel,
} from '@/components/ui/overlays/AlertDialog';
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from '@/components/ui/primitives/Select';
import { Pill } from '@/components/ui/primitives/Pill';
import { SkuGrid, mergeSkulRows } from '../SkuGrid';
import { QtyTierEditor } from '../QtyTierEditor';
import { discountedPriceStr } from '../discount';
import { MIN_DISCOUNT_PERCENT } from '../useAddDeal';
import type { AddDealFormValues } from '../useAddDeal';
import { VARIANT_AXIS_KIND, type VariantAxisKind } from '@/lib/enums/variant-axis-kind';
import { FALLBACK_SWATCH_BLACK } from '@/lib/theme-fallbacks';

const AXIS_KINDS = VARIANT_AXIS_KIND;
type AxisKind = VariantAxisKind;

export interface VariantsStepProps {
  form: UseFormReturn<AddDealFormValues>;
}

export function VariantsStep({ form }: VariantsStepProps) {
  const t = useT('variants');
  const tDeal = useT('vendor_add_deal');
  const tImg = useT('vendor_images');
  const tCommon = useT('common');
  const [pendingVisualAxis, setPendingVisualAxis] = useState<string | null>(null);
  const {
    control,
    setValue,
    register,
    watch,
    formState: { errors },
  } = form;

  const mode = useWatch({ control, name: 'variantsMode' }) ?? 'single';
  const axes = useWatch({ control, name: 'variantsAxes' }) ?? [];
  const skus = useWatch({ control, name: 'variantsSkus' }) ?? [];
  const singleQtyTiers = useWatch({ control, name: 'singleQtyTiers' }) ?? [];
  const discountPercent = useWatch({ control, name: 'discountPercent' });
  const originalPrice = useWatch({ control, name: 'originalPrice' });

  // ── Helpers ────────────────────────────────────────────────────────────────

  function syncSkuGrid(nextAxes: AddDealFormValues['variantsAxes']) {
    const safeAxes = nextAxes ?? [];
    const nextSkus = mergeSkulRows(safeAxes, skus);
    setValue('variantsSkus', nextSkus, { shouldDirty: true });
  }

  function setAxes(nextAxes: AddDealFormValues['variantsAxes']) {
    setValue('variantsAxes', nextAxes, { shouldDirty: true });
    syncSkuGrid(nextAxes);
  }

  function addAxis() {
    if ((axes.length ?? 0) >= 3) return;
    const newAxis = {
      axisOrder: axes.length,
      kind: 'SIZE' as AxisKind,
      nameHe: '',
      nameEn: '',
      options: [{ optionOrder: 0, valueCode: '', labelHe: '', labelEn: '' }],
    };
    setAxes([...axes, newAxis]);
  }

  function removeAxis(axIdx: number) {
    const next = axes.filter((_, i) => i !== axIdx).map((ax, i) => ({ ...ax, axisOrder: i }));
    setAxes(next);
  }

  function updateAxis(
    axIdx: number,
    patch: Partial<NonNullable<AddDealFormValues['variantsAxes']>[number]>,
  ) {
    const next = axes.map((ax, i) => (i === axIdx ? { ...ax, ...patch } : ax));
    setAxes(next);
  }

  function addOption(axIdx: number) {
    const ax = axes[axIdx];
    if (!ax) return;
    const newOpt = {
      optionOrder: ax.options.length,
      valueCode: '',
      labelHe: '',
      labelEn: '',
    };
    updateAxis(axIdx, { options: [...ax.options, newOpt] });
  }

  function removeOption(axIdx: number, optIdx: number) {
    const ax = axes[axIdx];
    if (!ax) return;
    const next = ax.options
      .filter((_, i) => i !== optIdx)
      .map((opt, i) => ({ ...opt, optionOrder: i }));
    updateAxis(axIdx, { options: next });
  }

  function updateOption(
    axIdx: number,
    optIdx: number,
    patch: Partial<NonNullable<AddDealFormValues['variantsAxes']>[number]['options'][number]>,
  ) {
    const ax = axes[axIdx];
    if (!ax) return;
    const nextOpts = ax.options.map((opt, i) => (i === optIdx ? { ...opt, ...patch } : opt));
    updateAxis(axIdx, { options: nextOpts });
  }

  // ── Render ─────────────────────────────────────────────────────────────────

  return (
    <div className="flex flex-col gap-6">
      {/* Mode selector */}
      <Controller
        name="variantsMode"
        control={control}
        render={({ field }) => (
          <div className="flex flex-col gap-2">
            <label className="text-sm font-semibold text-neutral-800">
              {tDeal('pricing_mode_label')}
            </label>
            <div className="flex gap-3">
              {(['single', 'variants'] as const).map((m) => (
                <Button
                  key={m}
                  type="button"
                  variant={field.value === m ? 'secondary' : 'ghost'}
                  size="sm"
                  onClick={() => {
                    field.onChange(m);
                    if (m === 'variants' && (axes.length ?? 0) === 0) {
                      addAxis();
                    }
                  }}
                  aria-pressed={field.value === m}
                >
                  {m === 'single' ? t('mode_single') : t('mode_variants')}
                </Button>
              ))}
            </div>
          </div>
        )}
      />

      {/* ── Single mode ───────────────────────────────────────────────────── */}
      {mode === 'single' && (
        <div className="flex flex-col gap-4">
          {/* Original price */}
          <FormField
            label={t('single_original_price')}
            htmlFor="single-original-price"
            error={errors.originalPrice?.message}
          >
            <Input
              id="single-original-price"
              type="text"
              inputMode="decimal"
              placeholder="100.00"
              {...register('originalPrice')}
              invalid={!!errors.originalPrice}
            />
          </FormField>

          {/* Discount % */}
          <FormField
            label={t('single_discount')}
            htmlFor="single-discount-pct"
            tooltip={tDeal('discount_tooltip')}
            hint={tDeal('discount_range_hint')}
            error={errors.discountPercent?.message}
          >
            <Controller
              name="discountPercent"
              control={control}
              render={({ field }) => (
                <NumberInput
                  id="single-discount-pct"
                  min={50}
                  max={99}
                  invalid={!!errors.discountPercent}
                  value={field.value ?? 50}
                  onChange={(n) => field.onChange(n)}
                />
              )}
            />
          </FormField>

          {(discountPercent ?? 0) < MIN_DISCOUNT_PERCENT && (
            <Pill tone="danger" size="sm" role="alert">
              {tDeal('discount_min_warning')}
            </Pill>
          )}

          {/* Quantity */}
          <FormField
            label={t('single_qty')}
            htmlFor="single-quantity"
            error={errors.quantity?.message}
          >
            <Controller
              name="quantity"
              control={control}
              render={({ field }) => (
                <NumberInput
                  id="single-quantity"
                  min={1}
                  invalid={!!errors.quantity}
                  value={field.value ?? 1}
                  onChange={(n) => field.onChange(n)}
                />
              )}
            />
          </FormField>

          {/* Quantity-discount tiers for single-SKU deals */}
          <QtyTierEditor
            panelId="single"
            discountedPrice={
              originalPrice && discountPercent
                ? discountedPriceStr(Number(originalPrice), discountPercent)
                : ''
            }
            tiers={singleQtyTiers}
            onChange={(tiers) => setValue('singleQtyTiers', tiers, { shouldDirty: true })}
          />
        </div>
      )}

      {/* ── Variants mode ─────────────────────────────────────────────────── */}
      {mode === 'variants' && (
        <div className="flex flex-col gap-6">
          {/* Axes */}
          {axes.map((ax, axIdx) => (
            <div
              key={axIdx}
              className="border-border-default flex flex-col gap-4 rounded-xl border p-4"
            >
              <div className="flex items-center justify-between gap-2">
                <span className="text-sm font-semibold text-neutral-800">
                  {t('axis_kind_label')} {axIdx + 1}
                </span>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={() => removeAxis(axIdx)}
                  aria-label={t('remove_axis')}
                >
                  {t('remove_axis')}
                </Button>
              </div>

              {/* Kind */}
              <FormField label={t('axis_kind_label')} htmlFor={`ax-kind-${axIdx}`}>
                <Select
                  value={ax.kind}
                  onValueChange={(v) => updateAxis(axIdx, { kind: v as AxisKind })}
                >
                  <SelectTrigger id={`ax-kind-${axIdx}`}>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {AXIS_KINDS.map((k) => (
                      <SelectItem key={k} value={k}>
                        {t(`axis_kind_${k}` as Parameters<typeof t>[0])}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </FormField>

              {/* Name He */}
              <FormField label={t('axis_name_he')} htmlFor={`ax-name-he-${axIdx}`}>
                <Input
                  id={`ax-name-he-${axIdx}`}
                  value={ax.nameHe}
                  onChange={(e) => updateAxis(axIdx, { nameHe: e.target.value })}
                  placeholder={t('axis_name_he_placeholder')}
                />
              </FormField>

              {/* Name En */}
              <FormField label={t('axis_name_en')} htmlFor={`ax-name-en-${axIdx}`}>
                <Input
                  id={`ax-name-en-${axIdx}`}
                  value={ax.nameEn}
                  onChange={(e) => updateAxis(axIdx, { nameEn: e.target.value })}
                  placeholder={t('axis_name_en_placeholder')}
                />
              </FormField>

              {/* Options */}
              <div className="flex flex-col gap-3">
                {ax.options.map((opt, optIdx) => (
                  <div key={optIdx} className="flex items-end gap-2">
                    <FormField
                      label={t('option_value_code')}
                      htmlFor={`ax-${axIdx}-opt-code-${optIdx}`}
                      tooltip={tDeal('option_value_code_tooltip')}
                      className="flex-1"
                    >
                      <Input
                        id={`ax-${axIdx}-opt-code-${optIdx}`}
                        value={opt.valueCode}
                        onChange={(e) => updateOption(axIdx, optIdx, { valueCode: e.target.value })}
                        placeholder={t('axis_value_en_placeholder')}
                      />
                    </FormField>
                    <FormField
                      label={t('option_label_he')}
                      htmlFor={`ax-${axIdx}-opt-he-${optIdx}`}
                      className="flex-1"
                    >
                      <Input
                        id={`ax-${axIdx}-opt-he-${optIdx}`}
                        value={opt.labelHe}
                        onChange={(e) => updateOption(axIdx, optIdx, { labelHe: e.target.value })}
                        placeholder={t('option_label_he_placeholder')}
                      />
                    </FormField>
                    <FormField
                      label={t('option_label_en')}
                      htmlFor={`ax-${axIdx}-opt-en-${optIdx}`}
                      className="flex-1"
                    >
                      <Input
                        id={`ax-${axIdx}-opt-en-${optIdx}`}
                        value={opt.labelEn}
                        onChange={(e) => updateOption(axIdx, optIdx, { labelEn: e.target.value })}
                        placeholder={t('option_label_en_placeholder')}
                      />
                    </FormField>
                    {ax.kind === 'COLOR' && (
                      <FormField
                        label={t('option_swatch_hex')}
                        htmlFor={`ax-${axIdx}-opt-swatch-${optIdx}`}
                        className="w-28"
                      >
                        <Input
                          id={`ax-${axIdx}-opt-swatch-${optIdx}`}
                          type="color"
                          value={opt.swatchHex ?? FALLBACK_SWATCH_BLACK}
                          onChange={(e) =>
                            updateOption(axIdx, optIdx, { swatchHex: e.target.value })
                          }
                        />
                      </FormField>
                    )}
                    {ax.kind === 'TIMESLOT' && (
                      <>
                        <FormField
                          label={t('option_slot_start')}
                          htmlFor={`ax-${axIdx}-opt-slotstart-${optIdx}`}
                          className="flex-1"
                        >
                          <Input
                            id={`ax-${axIdx}-opt-slotstart-${optIdx}`}
                            type="datetime-local"
                            value={opt.slotStart ?? ''}
                            onChange={(e) =>
                              updateOption(axIdx, optIdx, { slotStart: e.target.value || null })
                            }
                          />
                        </FormField>
                        <FormField
                          label={t('option_slot_end')}
                          htmlFor={`ax-${axIdx}-opt-slotend-${optIdx}`}
                          className="flex-1"
                        >
                          <Input
                            id={`ax-${axIdx}-opt-slotend-${optIdx}`}
                            type="datetime-local"
                            value={opt.slotEnd ?? ''}
                            onChange={(e) =>
                              updateOption(axIdx, optIdx, { slotEnd: e.target.value || null })
                            }
                          />
                        </FormField>
                      </>
                    )}
                    {ax.options.length > 1 && (
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => removeOption(axIdx, optIdx)}
                        aria-label={t('remove_option')}
                      >
                        {t('remove_option')}
                      </Button>
                    )}
                  </div>
                ))}

                <Button
                  type="button"
                  variant="secondary"
                  size="sm"
                  onClick={() => addOption(axIdx)}
                >
                  {t('add_option')}
                </Button>
              </div>
            </div>
          ))}

          {/* Add axis button */}
          {(axes.length ?? 0) < 3 && (
            <Button type="button" variant="secondary" size="md" onClick={addAxis}>
              {t('add_axis')}
            </Button>
          )}

          {/* Visual-axis selector — only meaningful when axes exist */}
          {axes.length > 0 && (
            <Controller
              control={control}
              name="imageSet.visualAxisOrder"
              render={({ field }) => (
                <fieldset className="border-border-default flex flex-col gap-2 rounded-xl border p-4">
                  <legend className="px-1 text-sm font-semibold text-neutral-800">
                    {tImg('visualAxisLabel')}
                  </legend>
                  <p className="text-xs text-[color:var(--text-muted)]">{tImg('visualAxisHint')}</p>
                  <RadioGroup
                    value={field.value == null ? 'none' : String(field.value)}
                    onValueChange={(v) => {
                      const hadSkus = (watch('imageSet.skus') ?? []).length > 0;
                      if (hadSkus) {
                        setPendingVisualAxis(v);
                        return;
                      }
                      field.onChange(v === 'none' ? null : parseInt(v, 10));
                    }}
                  >
                    <RadioItem id="visual-axis-none" value="none" label={tImg('visualAxisNone')} />
                    {axes.map((ax) => (
                      <RadioItem
                        key={ax.axisOrder}
                        id={`visual-axis-${ax.axisOrder}`}
                        value={String(ax.axisOrder)}
                        label={`${t(`axis_kind_${ax.kind}` as Parameters<typeof t>[0])}${ax.nameHe ? ` (${ax.nameHe})` : ax.nameEn ? ` (${ax.nameEn})` : ''}`}
                      />
                    ))}
                  </RadioGroup>
                </fieldset>
              )}
            />
          )}

          {/* SKU grid */}
          {axes.length > 0 && skus.length > 0 && (
            <div className="flex flex-col gap-2">
              <p className="text-sm font-semibold text-neutral-800">{t('sku_grid_title')}</p>
              <Controller
                name="variantsSkus"
                control={control}
                render={({ field }) => (
                  <SkuGrid
                    axes={axes}
                    skus={field.value ?? []}
                    onChange={(next) => field.onChange(next)}
                  />
                )}
              />
            </div>
          )}
        </div>
      )}

      <AlertDialog
        open={pendingVisualAxis != null}
        onOpenChange={(open) => !open && setPendingVisualAxis(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{tImg('visualAxisLabel')}</AlertDialogTitle>
            <AlertDialogDescription>{tImg('switchVisualAxisConfirm')}</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                if (pendingVisualAxis == null) return;
                setValue('imageSet.skus', [], { shouldDirty: true });
                setValue(
                  'imageSet.visualAxisOrder',
                  pendingVisualAxis === 'none' ? null : parseInt(pendingVisualAxis, 10),
                  { shouldDirty: true },
                );
                setPendingVisualAxis(null);
              }}
            >
              {tCommon('confirm')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
