/**
 * VendorUpgrade — UpgradeFormStep.
 *
 * Main business-details form shown after phone verification. Collects
 * business name, display name, description, business types, business email, ToS +
 * commission consent. Presentational: shell wires the form, submit handler,
 * derived helpers (descLength, displayName-touch flag).
 */

'use client';
import { ErrorState } from '@/components/ui/feedback/ErrorState';

import type { UseFormReturn, Control } from 'react-hook-form';
import { Controller } from 'react-hook-form';
import { Button } from '@/components/ui/primitives/Button';
import { Input } from '@/components/ui/primitives/Input';
import { Textarea } from '@/components/ui/primitives/Textarea';
import { Checkbox } from '@/components/ui/primitives/Checkbox';
import { FormField } from '@/components/ui/primitives/FormField';
import { FilterChip } from '@/components/ui/primitives/FilterChip';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/primitives/Select';
import { useT, useLocale } from '@/lib/i18n/react';
import { interpolate } from '@/lib/i18n/interpolate';
import { useQuery } from '@tanstack/react-query';

export interface UpgradeFormValues {
  businessName: string;
  displayName: string;
  description?: string;
  businessTypeIds: string[];
  businessEmail: string;
  tosAccepted: true;
}

export const UPGRADE_MAX_DESCRIPTION = 500;

export interface UpgradeFormStepProps {
  form: UseFormReturn<UpgradeFormValues>;
  control: Control<UpgradeFormValues>;
  isSubmitting: boolean;
  descLength: number;
  submitError: string | null;
  platformFeePct: number;
  onSubmit: (values: UpgradeFormValues) => void | Promise<void>;
  onDisplayNameChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}

export function UpgradeFormStep({
  form,
  control,
  isSubmitting,
  descLength,
  submitError,
  platformFeePct,
  onSubmit,
  onDisplayNameChange,
}: UpgradeFormStepProps) {
  const t = useT('vendor_upgrade');
  const tCommon = useT('common');
  const { locale } = useLocale();
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = form;

  const {
    data: businessTypeOptions = [],
    isError,
    refetch,
  } = useQuery({
    queryKey: ['business-types'],
    queryFn: async () => {
      const r = await fetch('/api/business-types');
      const j = (await r.json()) as {
        ok: boolean;
        businessTypes?: { id: string; nameHe: string; nameEn: string }[];
      };
      return j.businessTypes ?? [];
    },
  });

  if (isError) {
    return (
      <ErrorState
        title={tCommon('error_loading')}
        action={
          <Button variant="secondary" size="sm" onClick={() => refetch()}>
            {tCommon('retry')}
          </Button>
        }
      />
    );
  }
  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate className="flex flex-col gap-3">
      {/* Business Name */}
      <FormField
        htmlFor="vu-business-name"
        label={t('field_business_name')}
        required
        error={errors.businessName?.message}
      >
        <Input
          id="vu-business-name"
          type="text"
          autoComplete="organization"
          disabled={isSubmitting}
          invalid={!!errors.businessName}
          {...register('businessName')}
        />
      </FormField>

      {/* Display Name */}
      <FormField
        htmlFor="vu-display-name"
        label={t('field_display_name')}
        required
        error={errors.displayName?.message}
      >
        <Input
          id="vu-display-name"
          type="text"
          autoComplete="off"
          disabled={isSubmitting}
          invalid={!!errors.displayName}
          {...register('displayName', { onChange: onDisplayNameChange })}
        />
      </FormField>

      {/* Description */}
      <FormField
        htmlFor="vu-description"
        label={t('field_description')}
        error={errors.description?.message}
      >
        <div className="relative">
          <Textarea
            id="vu-description"
            rows={4}
            maxLength={UPGRADE_MAX_DESCRIPTION}
            disabled={isSubmitting}
            invalid={!!errors.description}
            {...register('description')}
          />
          <span
            aria-live="polite"
            className="text-text-muted pointer-events-none absolute end-[var(--spacing-2)] bottom-1 text-xs"
          >
            {descLength}/{UPGRADE_MAX_DESCRIPTION}
          </span>
        </div>
      </FormField>

      {/* Business types — multi-select (1..5) */}
      <Controller
        name="businessTypeIds"
        control={control}
        render={({ field, fieldState }) => {
          const selected = field.value ?? [];
          const add = (id: string) => {
            if (!id || selected.includes(id) || selected.length >= 5) return;
            field.onChange([...selected, id]);
          };
          const remove = (id: string) => field.onChange(selected.filter((x) => x !== id));
          const nameOf = (id: string) => {
            const bt = businessTypeOptions.find((o) => o.id === id);
            if (!bt) return id;
            if (locale === 'he') return bt.nameHe || bt.nameEn;
            return bt.nameEn || bt.nameHe;
          };
          const selectLabelOf = (o: { nameHe: string; nameEn: string }) =>
            locale === 'he' ? o.nameHe || o.nameEn : o.nameEn || o.nameHe;
          return (
            <FormField
              htmlFor="vu-business-type"
              label={t('field_business_type')}
              required
              error={fieldState.error?.message}
            >
              <div className="flex flex-col gap-2">
                <Select value="" onValueChange={add}>
                  <SelectTrigger
                    id="vu-business-type"
                    disabled={isSubmitting || selected.length >= 5}
                  >
                    <SelectValue placeholder={t('field_business_type_placeholder')} />
                  </SelectTrigger>
                  <SelectContent>
                    {businessTypeOptions
                      .filter((o) => !selected.includes(o.id))
                      .map((o) => (
                        <SelectItem key={o.id} value={o.id}>
                          {selectLabelOf(o)}
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
                <p className="text-text-muted text-xs">{t('business_types_limit_help')}</p>
                {selected.length > 0 && (
                  <div className="flex flex-wrap gap-1">
                    {selected.map((id) => {
                      const label = nameOf(id);
                      return (
                        <FilterChip
                          key={id}
                          pressed
                          onClick={() => remove(id)}
                          aria-label={interpolate(t('business_type_remove'), { name: label })}
                        >
                          {label} ×
                        </FilterChip>
                      );
                    })}
                  </div>
                )}
              </div>
            </FormField>
          );
        }}
      />

      {/* Business Email */}
      <FormField
        htmlFor="vu-email"
        label={t('field_business_email')}
        required
        error={errors.businessEmail?.message}
      >
        <Input
          id="vu-email"
          type="email"
          dir="ltr"
          autoComplete="email"
          disabled={isSubmitting}
          invalid={!!errors.businessEmail}
          {...register('businessEmail')}
        />
      </FormField>

      {/* Commission disclosure + ToS */}
      <div className="flex flex-col gap-2">
        <p className="text-text-muted text-xs">
          {interpolate(t('commission_disclosure'), { pct: String(platformFeePct) })}
        </p>
        <label className="text-text-secondary flex cursor-pointer items-start gap-2 text-xs">
          <Controller
            name="tosAccepted"
            control={control}
            render={({ field }) => (
              <Checkbox
                id="vu-tos"
                disabled={isSubmitting}
                checked={field.value === true}
                onCheckedChange={(checked) => field.onChange(checked === true)}
                onBlur={field.onBlur}
                aria-describedby={errors.tosAccepted ? 'vu-tos-error' : undefined}
              />
            )}
          />
          <span className="mt-0.5">
            {t('tos_label')}
            <a
              href="/legal/tos-vendor"
              target="_blank"
              rel="noopener noreferrer"
              className="text-brand-primary-600 hover:text-brand-primary-700 underline"
            >
              {t('tos_link')}
            </a>
          </span>
        </label>
        {errors.tosAccepted && (
          <p id="vu-tos-error" role="alert" className="text-danger-600 text-xs">
            {errors.tosAccepted.message}
          </p>
        )}
      </div>

      {/* Server error */}
      {submitError && (
        <p role="alert" className="text-danger-600 text-sm">
          {submitError}
        </p>
      )}

      <Button
        type="submit"
        variant="primary"
        size="lg"
        loading={isSubmitting}
        disabled={isSubmitting}
        className="w-full"
      >
        {t('submit')}
      </Button>
    </form>
  );
}
