/**
 * FieldsCommon — common form fields shared by every dealType:
 * title, description, category, tags, voucher checkbox, image upload,
 * price row, calculated price hint, quantity.
 *
 * Extracted from AddDealShell as part of arch spec 06.
 */
'use client';

import { Controller, type UseFormReturn } from 'react-hook-form';
import { Input } from '@/components/ui/primitives/Input';
import { NumberInput } from '@/components/ui/primitives/NumberInput';
import { Textarea } from '@/components/ui/primitives/Textarea';
import { FormField } from '@/components/ui/primitives/FormField';
import { DealImageManager, type DealImageEntryUI } from '@/components/ui/domain/DealImageManager';
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from '@/components/ui/primitives/Select';
import { TagPillGroup } from '@/components/ui/domain/TagPillGroup';
import { VoucherCheckbox } from '@/components/ui/domain/VoucherCheckbox';
import { Pill } from '@/components/ui/primitives/Pill';
import type { CategoryItem } from '@/components/ui/domain/CategoryPillGroup';
import type { TagItem } from '@/components/ui/domain/TagPillGroup';
import { pickLocalized } from '@/lib/i18n';
import { useT, useLocale } from '@/lib/i18n/react';
import { MIN_DISCOUNT_PERCENT } from '../useAddDeal';
import type { AddDealFormValues } from '../useAddDeal';
import { ShippingConfigStep } from './ShippingConfigStep';
import type { DealType } from '@/components/ui/domain/DealCard';

export interface FieldsCommonProps {
  form: UseFormReturn<AddDealFormValues>;
  categories: CategoryItem[];
  displayedTags: TagItem[];
  calculatedPrice: string | null | undefined;
  maxImagesPerDeal: number;
  dealType?: DealType;
}

export function FieldsCommon({
  form,
  categories,
  displayedTags,
  calculatedPrice,
  maxImagesPerDeal,
  dealType,
}: FieldsCommonProps) {
  const t = useT('vendor_add_deal');
  const tImg = useT('vendor_images');
  const { locale } = useLocale();
  const {
    register,
    control,
    watch,
    formState: { errors },
  } = form;
  const discountPercent = watch('discountPercent') ?? 0;

  return (
    <>
      {/* Title */}
      <FormField htmlFor="deal-name" label={t('name')} error={errors.title?.message}>
        <Input id="deal-name" type="text" invalid={!!errors.title} {...register('title')} />
      </FormField>

      {/* Description */}
      <FormField htmlFor="deal-desc" label={t('description')}>
        <Textarea id="deal-desc" rows={3} {...register('description')} />
      </FormField>

      {/* Category */}
      {categories.length > 0 && (
        <FormField htmlFor="deal-category" label={t('category_label')}>
          <Controller
            name="categoryId"
            control={form.control}
            render={({ field }) => (
              <Select
                value={field.value ?? ''}
                onValueChange={(id) => {
                  field.onChange(id);
                  form.setValue('tagIds', []);
                }}
              >
                <SelectTrigger id="deal-category">
                  <SelectValue placeholder={t('category_placeholder')} />
                </SelectTrigger>
                <SelectContent>
                  {categories.map((cat) => (
                    <SelectItem key={cat.id} value={cat.id}>
                      {pickLocalized(cat, locale)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
          />
        </FormField>
      )}

      {/* Tags */}
      {displayedTags.length > 0 && (
        <Controller
          name="tagIds"
          control={form.control}
          render={({ field }) => (
            <TagPillGroup
              tags={displayedTags}
              selected={field.value ?? []}
              onToggle={(id) => {
                const current = field.value ?? [];
                field.onChange(
                  current.includes(id)
                    ? current.filter((tagId: string) => tagId !== id)
                    : [...current, id],
                );
              }}
              locale={locale}
              label={t('tags_label')}
              collapseThreshold={10}
              seeAllLabel={t('tags_see_all')}
              showLessLabel={t('tags_show_less')}
            />
          )}
        />
      )}

      {/* Voucher */}
      <Controller
        name="isVoucher"
        control={form.control}
        render={({ field }) => (
          <VoucherCheckbox checked={field.value ?? false} onChange={field.onChange} />
        )}
      />

      {/* Deal images */}
      <Controller
        control={form.control}
        name="imageSet.deal"
        rules={{
          validate: (v: DealImageEntryUI[] | undefined) =>
            (v && v.length >= 1) || tImg('cannotRemoveLast'),
        }}
        render={({ field, fieldState }) => (
          <FormField label={tImg('addImage')} error={fieldState.error?.message} required>
            <DealImageManager
              value={(field.value as DealImageEntryUI[]) ?? []}
              onChange={field.onChange}
              max={maxImagesPerDeal}
            />
          </FormField>
        )}
      />

      {dealType !== 'COUPON' && (
        <>
          {/* Price row — COUPON pricing lives in VariantsStep */}
          <div className="flex flex-wrap gap-3">
            <FormField
              htmlFor="deal-price"
              label={t('original_price')}
              error={errors.originalPrice?.message}
            >
              <Controller
                name="originalPrice"
                control={control}
                render={({ field }) => (
                  <NumberInput
                    id="deal-price"
                    min={0}
                    step={0.01}
                    dir="ltr"
                    className="w-32"
                    invalid={!!errors.originalPrice}
                    value={field.value ? parseFloat(field.value as string) : 0}
                    onChange={(n) => field.onChange(String(n))}
                  />
                )}
              />
            </FormField>
            <FormField
              htmlFor="deal-discount"
              label={t('discount')}
              tooltip={t('discount_tooltip')}
              hint={t('discount_range_hint')}
              error={errors.discountPercent?.message}
            >
              <Controller
                name="discountPercent"
                control={control}
                render={({ field }) => (
                  <NumberInput
                    id="deal-discount"
                    min={50}
                    max={99}
                    dir="ltr"
                    className="w-20"
                    invalid={!!errors.discountPercent}
                    value={field.value ?? 50}
                    onChange={(n) => field.onChange(n)}
                  />
                )}
              />
            </FormField>
          </div>

          {/* Minimum discount warning */}
          {discountPercent < MIN_DISCOUNT_PERCENT && (
            <Pill tone="danger" size="sm" role="alert">
              {t('discount_min_warning')}
            </Pill>
          )}

          {/* Calculated price */}
          {calculatedPrice && (
            <p className="text-mode-vendor-700 text-sm font-semibold">
              {t('calculated_price')}: ₪{calculatedPrice}
            </p>
          )}

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

      {/* Max per user */}
      <FormField
        htmlFor="deal-max-per-user"
        label={t('max_per_user_label')}
        hint={t('max_per_user_help')}
        error={errors.maxPerUser?.message}
      >
        <Controller
          name="maxPerUser"
          control={control}
          render={({ field }) => (
            <NumberInput
              id="deal-max-per-user"
              min={1}
              max={1000}
              dir="ltr"
              className="w-28"
              placeholder={t('max_per_user_placeholder')}
              invalid={!!errors.maxPerUser}
              value={field.value ?? undefined}
              onChange={(n) => field.onChange(n)}
              onInput={(e) => {
                if ((e.target as HTMLInputElement).value === '') {
                  field.onChange(null);
                }
              }}
            />
          )}
        />
      </FormField>

      {dealType === 'ITEM' && <ShippingConfigStep form={form} />}
    </>
  );
}
