/**
 * FieldsGroup — GROUP-deal-specific fields:
 * fill rule, min/max, per-customer limit, deadline, cancellation policy,
 * tiered pricing (with lazy TierEditor), early bird, social sharing, bulk pickup.
 *
 * Extracted from AddDealShell as part of arch spec 06.
 */
'use client';

import { lazy, Suspense, useEffect, useMemo, useState } from 'react';
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 { Label } from '@/components/ui/primitives/Label';
import { Switch } from '@/components/ui/primitives/Switch';
import { RadioGroup, RadioItem } from '@/components/ui/primitives/RadioGroup';
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from '@/components/ui/primitives/Select';
import { Skeleton } from '@/components/ui/feedback/Skeleton';
import { RetryPanel } from '@/components/ui/feedback/RetryPanel';
import { ErrorBoundary } from '@/components/ui/feedback/ErrorBoundary';
import { useT } from '@/lib/i18n/react';
import type { AddDealFormValues } from '../useAddDeal';
import type { FillRule } from '@/lib/enums/fill-rule';
import type { CancellationPolicy } from '@/lib/enums/cancellation-policy';

const importTierEditor = () =>
  import('@/components/ui/domain/vendor/TierEditor').then((m) => ({ default: m.TierEditor }));
const TierEditorLazy = lazy(importTierEditor);

function TierEditorSkeleton() {
  return (
    <div className="flex flex-col gap-2" aria-busy="true">
      <Skeleton className="h-10 w-full" />
      <Skeleton className="h-10 w-full" />
    </div>
  );
}

export interface FieldsGroupProps {
  form: UseFormReturn<AddDealFormValues>;
  calculatedPrice: string | null | undefined;
}

export function FieldsGroup({ form, calculatedPrice }: FieldsGroupProps) {
  const t = useT('vendor_add_deal');
  const {
    register,
    control,
    watch,
    setValue,
    formState: { errors },
  } = form;

  const groupFillRule = watch('groupFillRule') ?? 'ALL_OR_NOTHING';
  const groupCancellationPolicy = watch('groupCancellationPolicy') ?? 'LEGAL_ONLY';
  const groupTieredPricing = watch('groupTieredPricing') ?? false;
  const groupEarlyBird = watch('groupEarlyBird') ?? false;
  const groupSocialSharing = watch('groupSocialSharing') ?? false;
  const groupBulkPickup = watch('groupBulkPickup') ?? false;
  const watchedGroupTiers = watch('groupTiers');
  const groupTiers = useMemo(() => watchedGroupTiers ?? [], [watchedGroupTiers]);

  // Assign stable client ids once for prefilled tiers (edit path) so TierEditor keys survive edits.
  useEffect(() => {
    if (!groupTieredPricing || groupTiers.length === 0) return;
    if (groupTiers.every((t) => t.id)) return;
    setValue(
      'groupTiers',
      groupTiers.map((t) => ({
        ...t,
        id: t.id ?? crypto.randomUUID(),
      })),
      { shouldDirty: false },
    );
  }, [groupTieredPricing, groupTiers, setValue]);

  // Force-remount key for TierEditor ErrorBoundary retry.
  const [tierEditorRetryKey, setTierEditorRetryKey] = useState(0);

  return (
    <>
      <div className="border-border-default border-t pt-3">
        <h3 className="text-text-primary mb-3 text-sm font-semibold">
          {t('group_settings_title')}
        </h3>
      </div>

      {/* Fill Rule */}
      <div className="flex flex-col gap-1">
        <Label>{t('group_fill_rule')}</Label>
        <RadioGroup
          value={groupFillRule}
          onValueChange={(v: string) => setValue('groupFillRule', v as FillRule)}
        >
          <RadioItem
            id="fill-all-or-nothing"
            value="ALL_OR_NOTHING"
            label={t('group_fill_rule_all_or_nothing')}
          />
          <RadioItem
            id="fill-minimum-threshold"
            value="MINIMUM_THRESHOLD"
            label={t('group_fill_rule_minimum_threshold')}
          />
        </RadioGroup>
      </div>

      {/* Min / Max group size */}
      <div className="grid grid-cols-2 gap-2">
        <FormField
          htmlFor="group-min-size"
          label={t('group_min_size')}
          error={errors.groupMinSize?.message}
        >
          <Controller
            name="groupMinSize"
            control={control}
            render={({ field }) => (
              <NumberInput
                id="group-min-size"
                min={2}
                dir="ltr"
                invalid={!!errors.groupMinSize}
                value={field.value ?? 2}
                onChange={(n) => field.onChange(n)}
              />
            )}
          />
        </FormField>
        <FormField
          htmlFor="group-max-size"
          label={t('group_max_size')}
          error={errors.groupMaxSize?.message}
        >
          <Controller
            name="groupMaxSize"
            control={control}
            render={({ field }) => (
              <NumberInput
                id="group-max-size"
                min={2}
                dir="ltr"
                invalid={!!errors.groupMaxSize}
                value={field.value ?? 2}
                onChange={(n) => field.onChange(n)}
              />
            )}
          />
        </FormField>
      </div>

      {/* Per customer limit */}
      <FormField
        htmlFor="group-per-customer"
        label={t('group_per_customer_limit')}
        error={errors.groupPerCustomerLimit?.message}
      >
        <Controller
          name="groupPerCustomerLimit"
          control={control}
          render={({ field }) => (
            <NumberInput
              id="group-per-customer"
              min={1}
              dir="ltr"
              invalid={!!errors.groupPerCustomerLimit}
              value={field.value ?? 1}
              onChange={(n) => field.onChange(n)}
            />
          )}
        />
      </FormField>

      {/* Deadline */}
      <FormField htmlFor="group-deadline" label={t('group_deadline')}>
        <Input id="group-deadline" type="datetime-local" dir="ltr" {...register('groupDeadline')} />
      </FormField>

      {/* Cancellation policy */}
      <FormField htmlFor="group-cancellation" label={t('group_cancellation_policy')}>
        <Select
          value={groupCancellationPolicy}
          onValueChange={(v: string) =>
            setValue('groupCancellationPolicy', v as CancellationPolicy)
          }
        >
          <SelectTrigger id="group-cancellation">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="LEGAL_ONLY">{t('cancellation_policy_legal_only')}</SelectItem>
            <SelectItem value="FLEXIBLE">{t('cancellation_policy_flexible')}</SelectItem>
            <SelectItem value="CUSTOM_WINDOW">{t('cancellation_policy_custom_window')}</SelectItem>
          </SelectContent>
        </Select>
      </FormField>

      {/* Custom cancellation window hours */}
      {groupCancellationPolicy === 'CUSTOM_WINDOW' && (
        <FormField
          htmlFor="group-cancel-hours"
          label={t('group_cancellation_window_hours')}
          error={errors.groupCancellationWindowHours?.message}
        >
          <Controller
            name="groupCancellationWindowHours"
            control={control}
            render={({ field }) => (
              <NumberInput
                id="group-cancel-hours"
                min={1}
                dir="ltr"
                invalid={!!errors.groupCancellationWindowHours}
                value={field.value ?? 1}
                onChange={(n) => field.onChange(n)}
              />
            )}
          />
        </FormField>
      )}

      {/* Tiered pricing toggle */}
      <div className="flex items-center justify-between gap-3">
        <Label htmlFor="group-tiered">{t('group_tiered_pricing')}</Label>
        <Switch
          id="group-tiered"
          checked={groupTieredPricing}
          onCheckedChange={(v: boolean) => setValue('groupTieredPricing', v)}
          className="scroll-mt-16"
        />
      </div>

      {/* Tier rows — TierEditor (lazy: mounts only when tiered pricing enabled) */}
      {groupTieredPricing && (
        <ErrorBoundary
          key={`tier-editor-${tierEditorRetryKey}`}
          fallback={
            <RetryPanel
              variant="inline"
              onRetry={() => {
                void importTierEditor();
                setTierEditorRetryKey((k) => k + 1);
              }}
            />
          }
        >
          <Suspense fallback={<TierEditorSkeleton />}>
            <TierEditorLazy
              tiers={groupTiers.map((tier) => ({
                id: tier.id,
                participants: tier.minParticipants ?? 2,
                price: tier.pricePerUnit ?? 0,
              }))}
              onChange={(updated) => {
                setValue(
                  'groupTiers',
                  updated.map((u) => ({
                    id: u.id,
                    minParticipants: u.participants,
                    pricePerUnit: u.price,
                  })),
                );
              }}
              priceFloor={Number(calculatedPrice) || undefined}
            />
          </Suspense>
        </ErrorBoundary>
      )}

      {/* Early bird toggle */}
      <div className="flex items-center justify-between gap-3">
        <Label htmlFor="group-early-bird">{t('group_early_bird')}</Label>
        <Switch
          id="group-early-bird"
          checked={groupEarlyBird}
          onCheckedChange={(v: boolean) => setValue('groupEarlyBird', v)}
          className="scroll-mt-16"
        />
      </div>

      {groupEarlyBird && (
        <div className="grid grid-cols-2 gap-2">
          <FormField
            htmlFor="group-eb-slots"
            label={t('group_early_bird_slots')}
            error={errors.groupEarlyBirdSlots?.message}
          >
            <Controller
              name="groupEarlyBirdSlots"
              control={control}
              render={({ field }) => (
                <NumberInput
                  id="group-eb-slots"
                  min={1}
                  dir="ltr"
                  invalid={!!errors.groupEarlyBirdSlots}
                  value={field.value ?? 1}
                  onChange={(n) => field.onChange(n)}
                />
              )}
            />
          </FormField>
          <FormField
            htmlFor="group-eb-discount"
            label={t('group_early_bird_discount')}
            error={errors.groupEarlyBirdDiscountPercent?.message}
          >
            <Controller
              name="groupEarlyBirdDiscountPercent"
              control={control}
              render={({ field }) => (
                <NumberInput
                  id="group-eb-discount"
                  min={1}
                  max={50}
                  dir="ltr"
                  invalid={!!errors.groupEarlyBirdDiscountPercent}
                  value={field.value ?? 1}
                  onChange={(n) => field.onChange(n)}
                />
              )}
            />
          </FormField>
        </div>
      )}

      {/* Social sharing toggle */}
      <div className="flex items-center justify-between gap-3">
        <Label htmlFor="group-social">{t('group_social_sharing')}</Label>
        <Switch
          id="group-social"
          checked={groupSocialSharing}
          onCheckedChange={(v: boolean) => setValue('groupSocialSharing', v)}
          className="scroll-mt-16"
        />
      </div>

      {groupSocialSharing && (
        <FormField htmlFor="group-social-reward" label={t('group_social_sharing_reward')}>
          <Textarea id="group-social-reward" rows={2} {...register('groupSocialSharingReward')} />
        </FormField>
      )}

      {/* Bulk pickup toggle */}
      <div className="flex items-center justify-between gap-3">
        <Label htmlFor="group-bulk-pickup">{t('group_bulk_pickup')}</Label>
        <Switch
          id="group-bulk-pickup"
          checked={groupBulkPickup}
          onCheckedChange={(v: boolean) => setValue('groupBulkPickup', v)}
          className="scroll-mt-16"
        />
      </div>

      {groupBulkPickup && (
        <FormField htmlFor="group-bulk-details" label={t('group_bulk_pickup_details')}>
          <Textarea id="group-bulk-details" rows={2} {...register('groupBulkPickupDetails')} />
        </FormField>
      )}
    </>
  );
}
